babylon.max.js 2.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. }());
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. }());
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. }());
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. }());
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.clone = function () {
  1188. return new Vector4(this.x, this.y, this.z, this.w);
  1189. };
  1190. Vector4.prototype.copyFrom = function (source) {
  1191. this.x = source.x;
  1192. this.y = source.y;
  1193. this.z = source.z;
  1194. this.w = source.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1198. this.x = x;
  1199. this.y = y;
  1200. this.z = z;
  1201. this.w = w;
  1202. return this;
  1203. };
  1204. // Statics
  1205. Vector4.FromArray = function (array, offset) {
  1206. if (!offset) {
  1207. offset = 0;
  1208. }
  1209. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1210. };
  1211. Vector4.FromArrayToRef = function (array, offset, result) {
  1212. result.x = array[offset];
  1213. result.y = array[offset + 1];
  1214. result.z = array[offset + 2];
  1215. result.w = array[offset + 3];
  1216. };
  1217. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1218. result.x = array[offset];
  1219. result.y = array[offset + 1];
  1220. result.z = array[offset + 2];
  1221. result.w = array[offset + 3];
  1222. };
  1223. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1224. result.x = x;
  1225. result.y = y;
  1226. result.z = z;
  1227. result.w = w;
  1228. };
  1229. Vector4.Zero = function () {
  1230. return new Vector4(0, 0, 0, 0);
  1231. };
  1232. Vector4.Normalize = function (vector) {
  1233. var result = Vector4.Zero();
  1234. Vector4.NormalizeToRef(vector, result);
  1235. return result;
  1236. };
  1237. Vector4.NormalizeToRef = function (vector, result) {
  1238. result.copyFrom(vector);
  1239. result.normalize();
  1240. };
  1241. Vector4.Minimize = function (left, right) {
  1242. var min = left.clone();
  1243. min.MinimizeInPlace(right);
  1244. return min;
  1245. };
  1246. Vector4.Maximize = function (left, right) {
  1247. var max = left.clone();
  1248. max.MaximizeInPlace(right);
  1249. return max;
  1250. };
  1251. Vector4.Distance = function (value1, value2) {
  1252. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1253. };
  1254. Vector4.DistanceSquared = function (value1, value2) {
  1255. var x = value1.x - value2.x;
  1256. var y = value1.y - value2.y;
  1257. var z = value1.z - value2.z;
  1258. var w = value1.w - value2.w;
  1259. return (x * x) + (y * y) + (z * z) + (w * w);
  1260. };
  1261. Vector4.Center = function (value1, value2) {
  1262. var center = value1.add(value2);
  1263. center.scaleInPlace(0.5);
  1264. return center;
  1265. };
  1266. return Vector4;
  1267. }());
  1268. BABYLON.Vector4 = Vector4;
  1269. var Quaternion = (function () {
  1270. function Quaternion(x, y, z, w) {
  1271. if (x === void 0) { x = 0; }
  1272. if (y === void 0) { y = 0; }
  1273. if (z === void 0) { z = 0; }
  1274. if (w === void 0) { w = 1; }
  1275. this.x = x;
  1276. this.y = y;
  1277. this.z = z;
  1278. this.w = w;
  1279. }
  1280. Quaternion.prototype.toString = function () {
  1281. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1282. };
  1283. Quaternion.prototype.asArray = function () {
  1284. return [this.x, this.y, this.z, this.w];
  1285. };
  1286. Quaternion.prototype.equals = function (otherQuaternion) {
  1287. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1288. };
  1289. Quaternion.prototype.clone = function () {
  1290. return new Quaternion(this.x, this.y, this.z, this.w);
  1291. };
  1292. Quaternion.prototype.copyFrom = function (other) {
  1293. this.x = other.x;
  1294. this.y = other.y;
  1295. this.z = other.z;
  1296. this.w = other.w;
  1297. return this;
  1298. };
  1299. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1300. this.x = x;
  1301. this.y = y;
  1302. this.z = z;
  1303. this.w = w;
  1304. return this;
  1305. };
  1306. Quaternion.prototype.add = function (other) {
  1307. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1308. };
  1309. Quaternion.prototype.subtract = function (other) {
  1310. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1311. };
  1312. Quaternion.prototype.scale = function (value) {
  1313. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1314. };
  1315. Quaternion.prototype.multiply = function (q1) {
  1316. var result = new Quaternion(0, 0, 0, 1.0);
  1317. this.multiplyToRef(q1, result);
  1318. return result;
  1319. };
  1320. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1321. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1322. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1323. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1324. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1325. result.copyFromFloats(x, y, z, w);
  1326. return this;
  1327. };
  1328. Quaternion.prototype.multiplyInPlace = function (q1) {
  1329. this.multiplyToRef(q1, this);
  1330. return this;
  1331. };
  1332. Quaternion.prototype.conjugateToRef = function (ref) {
  1333. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugateInPlace = function () {
  1337. this.x *= -1;
  1338. this.y *= -1;
  1339. this.z *= -1;
  1340. return this;
  1341. };
  1342. Quaternion.prototype.conjugate = function () {
  1343. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1344. return result;
  1345. };
  1346. Quaternion.prototype.length = function () {
  1347. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1348. };
  1349. Quaternion.prototype.normalize = function () {
  1350. var length = 1.0 / this.length();
  1351. this.x *= length;
  1352. this.y *= length;
  1353. this.z *= length;
  1354. this.w *= length;
  1355. return this;
  1356. };
  1357. Quaternion.prototype.toEulerAngles = function (order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var result = Vector3.Zero();
  1360. this.toEulerAnglesToRef(result, order);
  1361. return result;
  1362. };
  1363. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1364. if (order === void 0) { order = "YZX"; }
  1365. var heading, attitude, bank;
  1366. var x = this.x, y = this.y, z = this.z, w = this.w;
  1367. switch (order) {
  1368. case "YZX":
  1369. var test = x * y + z * w;
  1370. if (test > 0.499) {
  1371. heading = 2 * Math.atan2(x, w);
  1372. attitude = Math.PI / 2;
  1373. bank = 0;
  1374. }
  1375. if (test < -0.499) {
  1376. heading = -2 * Math.atan2(x, w);
  1377. attitude = -Math.PI / 2;
  1378. bank = 0;
  1379. }
  1380. if (isNaN(heading)) {
  1381. var sqx = x * x;
  1382. var sqy = y * y;
  1383. var sqz = z * z;
  1384. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1385. attitude = Math.asin(2 * test); // attitude
  1386. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1387. }
  1388. break;
  1389. default:
  1390. throw new Error("Euler order " + order + " not supported yet.");
  1391. }
  1392. result.y = heading;
  1393. result.z = attitude;
  1394. result.x = bank;
  1395. return this;
  1396. };
  1397. ;
  1398. Quaternion.prototype.toRotationMatrix = function (result) {
  1399. var xx = this.x * this.x;
  1400. var yy = this.y * this.y;
  1401. var zz = this.z * this.z;
  1402. var xy = this.x * this.y;
  1403. var zw = this.z * this.w;
  1404. var zx = this.z * this.x;
  1405. var yw = this.y * this.w;
  1406. var yz = this.y * this.z;
  1407. var xw = this.x * this.w;
  1408. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1409. result.m[1] = 2.0 * (xy + zw);
  1410. result.m[2] = 2.0 * (zx - yw);
  1411. result.m[3] = 0;
  1412. result.m[4] = 2.0 * (xy - zw);
  1413. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1414. result.m[6] = 2.0 * (yz + xw);
  1415. result.m[7] = 0;
  1416. result.m[8] = 2.0 * (zx + yw);
  1417. result.m[9] = 2.0 * (yz - xw);
  1418. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1419. result.m[11] = 0;
  1420. result.m[12] = 0;
  1421. result.m[13] = 0;
  1422. result.m[14] = 0;
  1423. result.m[15] = 1.0;
  1424. return this;
  1425. };
  1426. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1427. Quaternion.FromRotationMatrixToRef(matrix, this);
  1428. return this;
  1429. };
  1430. // Statics
  1431. Quaternion.FromRotationMatrix = function (matrix) {
  1432. var result = new Quaternion();
  1433. Quaternion.FromRotationMatrixToRef(matrix, result);
  1434. return result;
  1435. };
  1436. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1437. var data = matrix.m;
  1438. var m11 = data[0], m12 = data[4], m13 = data[8];
  1439. var m21 = data[1], m22 = data[5], m23 = data[9];
  1440. var m31 = data[2], m32 = data[6], m33 = data[10];
  1441. var trace = m11 + m22 + m33;
  1442. var s;
  1443. if (trace > 0) {
  1444. s = 0.5 / Math.sqrt(trace + 1.0);
  1445. result.w = 0.25 / s;
  1446. result.x = (m32 - m23) * s;
  1447. result.y = (m13 - m31) * s;
  1448. result.z = (m21 - m12) * s;
  1449. }
  1450. else if (m11 > m22 && m11 > m33) {
  1451. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1452. result.w = (m32 - m23) / s;
  1453. result.x = 0.25 * s;
  1454. result.y = (m12 + m21) / s;
  1455. result.z = (m13 + m31) / s;
  1456. }
  1457. else if (m22 > m33) {
  1458. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1459. result.w = (m13 - m31) / s;
  1460. result.x = (m12 + m21) / s;
  1461. result.y = 0.25 * s;
  1462. result.z = (m23 + m32) / s;
  1463. }
  1464. else {
  1465. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1466. result.w = (m21 - m12) / s;
  1467. result.x = (m13 + m31) / s;
  1468. result.y = (m23 + m32) / s;
  1469. result.z = 0.25 * s;
  1470. }
  1471. };
  1472. Quaternion.Inverse = function (q) {
  1473. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1474. };
  1475. Quaternion.Identity = function () {
  1476. return new Quaternion(0, 0, 0, 1);
  1477. };
  1478. Quaternion.RotationAxis = function (axis, angle) {
  1479. var result = new Quaternion();
  1480. var sin = Math.sin(angle / 2);
  1481. axis.normalize();
  1482. result.w = Math.cos(angle / 2);
  1483. result.x = axis.x * sin;
  1484. result.y = axis.y * sin;
  1485. result.z = axis.z * sin;
  1486. return result;
  1487. };
  1488. Quaternion.FromArray = function (array, offset) {
  1489. if (!offset) {
  1490. offset = 0;
  1491. }
  1492. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1493. };
  1494. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1495. var result = new Quaternion();
  1496. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1497. return result;
  1498. };
  1499. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1500. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1501. var halfRoll = roll * 0.5;
  1502. var halfPitch = pitch * 0.5;
  1503. var halfYaw = yaw * 0.5;
  1504. var sinRoll = Math.sin(halfRoll);
  1505. var cosRoll = Math.cos(halfRoll);
  1506. var sinPitch = Math.sin(halfPitch);
  1507. var cosPitch = Math.cos(halfPitch);
  1508. var sinYaw = Math.sin(halfYaw);
  1509. var cosYaw = Math.cos(halfYaw);
  1510. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1511. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1512. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1513. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1514. };
  1515. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1516. var result = new Quaternion();
  1517. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1518. return result;
  1519. };
  1520. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1521. // Produces a quaternion from Euler angles in the z-x-z orientation
  1522. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1523. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1524. var halfBeta = beta * 0.5;
  1525. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1526. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1527. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1528. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1529. };
  1530. Quaternion.Slerp = function (left, right, amount) {
  1531. var num2;
  1532. var num3;
  1533. var num = amount;
  1534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1535. var flag = false;
  1536. if (num4 < 0) {
  1537. flag = true;
  1538. num4 = -num4;
  1539. }
  1540. if (num4 > 0.999999) {
  1541. num3 = 1 - num;
  1542. num2 = flag ? -num : num;
  1543. }
  1544. else {
  1545. var num5 = Math.acos(num4);
  1546. var num6 = (1.0 / Math.sin(num5));
  1547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1549. }
  1550. 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));
  1551. };
  1552. return Quaternion;
  1553. }());
  1554. BABYLON.Quaternion = Quaternion;
  1555. var Matrix = (function () {
  1556. function Matrix() {
  1557. this.m = new Float32Array(16);
  1558. }
  1559. // Properties
  1560. Matrix.prototype.isIdentity = function () {
  1561. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1562. return false;
  1563. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1564. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1565. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1566. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1567. return false;
  1568. return true;
  1569. };
  1570. Matrix.prototype.determinant = function () {
  1571. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1572. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1573. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1574. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1575. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1576. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1577. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1578. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1579. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1580. };
  1581. // Methods
  1582. Matrix.prototype.toArray = function () {
  1583. return this.m;
  1584. };
  1585. Matrix.prototype.asArray = function () {
  1586. return this.toArray();
  1587. };
  1588. Matrix.prototype.invert = function () {
  1589. this.invertToRef(this);
  1590. return this;
  1591. };
  1592. Matrix.prototype.reset = function () {
  1593. for (var index = 0; index < 16; index++) {
  1594. this.m[index] = 0;
  1595. }
  1596. return this;
  1597. };
  1598. Matrix.prototype.add = function (other) {
  1599. var result = new Matrix();
  1600. this.addToRef(other, result);
  1601. return result;
  1602. };
  1603. Matrix.prototype.addToRef = function (other, result) {
  1604. for (var index = 0; index < 16; index++) {
  1605. result.m[index] = this.m[index] + other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.addToSelf = function (other) {
  1610. for (var index = 0; index < 16; index++) {
  1611. this.m[index] += other.m[index];
  1612. }
  1613. return this;
  1614. };
  1615. Matrix.prototype.invertToRef = function (other) {
  1616. var l1 = this.m[0];
  1617. var l2 = this.m[1];
  1618. var l3 = this.m[2];
  1619. var l4 = this.m[3];
  1620. var l5 = this.m[4];
  1621. var l6 = this.m[5];
  1622. var l7 = this.m[6];
  1623. var l8 = this.m[7];
  1624. var l9 = this.m[8];
  1625. var l10 = this.m[9];
  1626. var l11 = this.m[10];
  1627. var l12 = this.m[11];
  1628. var l13 = this.m[12];
  1629. var l14 = this.m[13];
  1630. var l15 = this.m[14];
  1631. var l16 = this.m[15];
  1632. var l17 = (l11 * l16) - (l12 * l15);
  1633. var l18 = (l10 * l16) - (l12 * l14);
  1634. var l19 = (l10 * l15) - (l11 * l14);
  1635. var l20 = (l9 * l16) - (l12 * l13);
  1636. var l21 = (l9 * l15) - (l11 * l13);
  1637. var l22 = (l9 * l14) - (l10 * l13);
  1638. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1639. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1640. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1641. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1642. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1643. var l28 = (l7 * l16) - (l8 * l15);
  1644. var l29 = (l6 * l16) - (l8 * l14);
  1645. var l30 = (l6 * l15) - (l7 * l14);
  1646. var l31 = (l5 * l16) - (l8 * l13);
  1647. var l32 = (l5 * l15) - (l7 * l13);
  1648. var l33 = (l5 * l14) - (l6 * l13);
  1649. var l34 = (l7 * l12) - (l8 * l11);
  1650. var l35 = (l6 * l12) - (l8 * l10);
  1651. var l36 = (l6 * l11) - (l7 * l10);
  1652. var l37 = (l5 * l12) - (l8 * l9);
  1653. var l38 = (l5 * l11) - (l7 * l9);
  1654. var l39 = (l5 * l10) - (l6 * l9);
  1655. other.m[0] = l23 * l27;
  1656. other.m[4] = l24 * l27;
  1657. other.m[8] = l25 * l27;
  1658. other.m[12] = l26 * l27;
  1659. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1660. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1661. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1662. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1663. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1664. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1665. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1666. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1667. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1668. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1669. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1670. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1671. return this;
  1672. };
  1673. Matrix.prototype.setTranslation = function (vector3) {
  1674. this.m[12] = vector3.x;
  1675. this.m[13] = vector3.y;
  1676. this.m[14] = vector3.z;
  1677. return this;
  1678. };
  1679. Matrix.prototype.multiply = function (other) {
  1680. var result = new Matrix();
  1681. this.multiplyToRef(other, result);
  1682. return result;
  1683. };
  1684. Matrix.prototype.copyFrom = function (other) {
  1685. for (var index = 0; index < 16; index++) {
  1686. this.m[index] = other.m[index];
  1687. }
  1688. return this;
  1689. };
  1690. Matrix.prototype.copyToArray = function (array, offset) {
  1691. if (offset === void 0) { offset = 0; }
  1692. for (var index = 0; index < 16; index++) {
  1693. array[offset + index] = this.m[index];
  1694. }
  1695. return this;
  1696. };
  1697. Matrix.prototype.multiplyToRef = function (other, result) {
  1698. this.multiplyToArray(other, result.m, 0);
  1699. return this;
  1700. };
  1701. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1702. var tm0 = this.m[0];
  1703. var tm1 = this.m[1];
  1704. var tm2 = this.m[2];
  1705. var tm3 = this.m[3];
  1706. var tm4 = this.m[4];
  1707. var tm5 = this.m[5];
  1708. var tm6 = this.m[6];
  1709. var tm7 = this.m[7];
  1710. var tm8 = this.m[8];
  1711. var tm9 = this.m[9];
  1712. var tm10 = this.m[10];
  1713. var tm11 = this.m[11];
  1714. var tm12 = this.m[12];
  1715. var tm13 = this.m[13];
  1716. var tm14 = this.m[14];
  1717. var tm15 = this.m[15];
  1718. var om0 = other.m[0];
  1719. var om1 = other.m[1];
  1720. var om2 = other.m[2];
  1721. var om3 = other.m[3];
  1722. var om4 = other.m[4];
  1723. var om5 = other.m[5];
  1724. var om6 = other.m[6];
  1725. var om7 = other.m[7];
  1726. var om8 = other.m[8];
  1727. var om9 = other.m[9];
  1728. var om10 = other.m[10];
  1729. var om11 = other.m[11];
  1730. var om12 = other.m[12];
  1731. var om13 = other.m[13];
  1732. var om14 = other.m[14];
  1733. var om15 = other.m[15];
  1734. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1735. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1736. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1737. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1738. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1739. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1740. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1741. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1742. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1743. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1744. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1745. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1746. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1747. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1748. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1749. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1750. return this;
  1751. };
  1752. Matrix.prototype.equals = function (value) {
  1753. return value &&
  1754. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1755. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1756. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1757. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1758. };
  1759. Matrix.prototype.clone = function () {
  1760. 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]);
  1761. };
  1762. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1763. translation.x = this.m[12];
  1764. translation.y = this.m[13];
  1765. translation.z = this.m[14];
  1766. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1767. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1768. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1769. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1770. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1771. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1772. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1773. rotation.x = 0;
  1774. rotation.y = 0;
  1775. rotation.z = 0;
  1776. rotation.w = 1;
  1777. return false;
  1778. }
  1779. 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);
  1780. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1781. return true;
  1782. };
  1783. // Statics
  1784. Matrix.FromArray = function (array, offset) {
  1785. var result = new Matrix();
  1786. if (!offset) {
  1787. offset = 0;
  1788. }
  1789. Matrix.FromArrayToRef(array, offset, result);
  1790. return result;
  1791. };
  1792. Matrix.FromArrayToRef = function (array, offset, result) {
  1793. for (var index = 0; index < 16; index++) {
  1794. result.m[index] = array[index + offset];
  1795. }
  1796. };
  1797. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = array[index + offset] * scale;
  1800. }
  1801. };
  1802. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1803. result.m[0] = initialM11;
  1804. result.m[1] = initialM12;
  1805. result.m[2] = initialM13;
  1806. result.m[3] = initialM14;
  1807. result.m[4] = initialM21;
  1808. result.m[5] = initialM22;
  1809. result.m[6] = initialM23;
  1810. result.m[7] = initialM24;
  1811. result.m[8] = initialM31;
  1812. result.m[9] = initialM32;
  1813. result.m[10] = initialM33;
  1814. result.m[11] = initialM34;
  1815. result.m[12] = initialM41;
  1816. result.m[13] = initialM42;
  1817. result.m[14] = initialM43;
  1818. result.m[15] = initialM44;
  1819. };
  1820. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1821. var result = new Matrix();
  1822. result.m[0] = initialM11;
  1823. result.m[1] = initialM12;
  1824. result.m[2] = initialM13;
  1825. result.m[3] = initialM14;
  1826. result.m[4] = initialM21;
  1827. result.m[5] = initialM22;
  1828. result.m[6] = initialM23;
  1829. result.m[7] = initialM24;
  1830. result.m[8] = initialM31;
  1831. result.m[9] = initialM32;
  1832. result.m[10] = initialM33;
  1833. result.m[11] = initialM34;
  1834. result.m[12] = initialM41;
  1835. result.m[13] = initialM42;
  1836. result.m[14] = initialM43;
  1837. result.m[15] = initialM44;
  1838. return result;
  1839. };
  1840. Matrix.Compose = function (scale, rotation, translation) {
  1841. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1842. var rotationMatrix = Matrix.Identity();
  1843. rotation.toRotationMatrix(rotationMatrix);
  1844. result = result.multiply(rotationMatrix);
  1845. result.setTranslation(translation);
  1846. return result;
  1847. };
  1848. Matrix.Identity = function () {
  1849. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1850. };
  1851. Matrix.IdentityToRef = function (result) {
  1852. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1853. };
  1854. Matrix.Zero = function () {
  1855. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1856. };
  1857. Matrix.RotationX = function (angle) {
  1858. var result = new Matrix();
  1859. Matrix.RotationXToRef(angle, result);
  1860. return result;
  1861. };
  1862. Matrix.Invert = function (source) {
  1863. var result = new Matrix();
  1864. source.invertToRef(result);
  1865. return result;
  1866. };
  1867. Matrix.RotationXToRef = function (angle, result) {
  1868. var s = Math.sin(angle);
  1869. var c = Math.cos(angle);
  1870. result.m[0] = 1.0;
  1871. result.m[15] = 1.0;
  1872. result.m[5] = c;
  1873. result.m[10] = c;
  1874. result.m[9] = -s;
  1875. result.m[6] = s;
  1876. result.m[1] = 0;
  1877. result.m[2] = 0;
  1878. result.m[3] = 0;
  1879. result.m[4] = 0;
  1880. result.m[7] = 0;
  1881. result.m[8] = 0;
  1882. result.m[11] = 0;
  1883. result.m[12] = 0;
  1884. result.m[13] = 0;
  1885. result.m[14] = 0;
  1886. };
  1887. Matrix.RotationY = function (angle) {
  1888. var result = new Matrix();
  1889. Matrix.RotationYToRef(angle, result);
  1890. return result;
  1891. };
  1892. Matrix.RotationYToRef = function (angle, result) {
  1893. var s = Math.sin(angle);
  1894. var c = Math.cos(angle);
  1895. result.m[5] = 1.0;
  1896. result.m[15] = 1.0;
  1897. result.m[0] = c;
  1898. result.m[2] = -s;
  1899. result.m[8] = s;
  1900. result.m[10] = c;
  1901. result.m[1] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[6] = 0;
  1905. result.m[7] = 0;
  1906. result.m[9] = 0;
  1907. result.m[11] = 0;
  1908. result.m[12] = 0;
  1909. result.m[13] = 0;
  1910. result.m[14] = 0;
  1911. };
  1912. Matrix.RotationZ = function (angle) {
  1913. var result = new Matrix();
  1914. Matrix.RotationZToRef(angle, result);
  1915. return result;
  1916. };
  1917. Matrix.RotationZToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[10] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[0] = c;
  1923. result.m[1] = s;
  1924. result.m[4] = -s;
  1925. result.m[5] = c;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[8] = 0;
  1931. result.m[9] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationAxis = function (axis, angle) {
  1938. var result = Matrix.Zero();
  1939. Matrix.RotationAxisToRef(axis, angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1943. var s = Math.sin(-angle);
  1944. var c = Math.cos(-angle);
  1945. var c1 = 1 - c;
  1946. axis.normalize();
  1947. result.m[0] = (axis.x * axis.x) * c1 + c;
  1948. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1949. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1950. result.m[3] = 0.0;
  1951. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1952. result.m[5] = (axis.y * axis.y) * c1 + c;
  1953. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1954. result.m[7] = 0.0;
  1955. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1956. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1957. result.m[10] = (axis.z * axis.z) * c1 + c;
  1958. result.m[11] = 0.0;
  1959. result.m[15] = 1.0;
  1960. };
  1961. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1962. var result = new Matrix();
  1963. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1967. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1968. this._tempQuaternion.toRotationMatrix(result);
  1969. };
  1970. Matrix.Scaling = function (x, y, z) {
  1971. var result = Matrix.Zero();
  1972. Matrix.ScalingToRef(x, y, z, result);
  1973. return result;
  1974. };
  1975. Matrix.ScalingToRef = function (x, y, z, result) {
  1976. result.m[0] = x;
  1977. result.m[1] = 0;
  1978. result.m[2] = 0;
  1979. result.m[3] = 0;
  1980. result.m[4] = 0;
  1981. result.m[5] = y;
  1982. result.m[6] = 0;
  1983. result.m[7] = 0;
  1984. result.m[8] = 0;
  1985. result.m[9] = 0;
  1986. result.m[10] = z;
  1987. result.m[11] = 0;
  1988. result.m[12] = 0;
  1989. result.m[13] = 0;
  1990. result.m[14] = 0;
  1991. result.m[15] = 1.0;
  1992. };
  1993. Matrix.Translation = function (x, y, z) {
  1994. var result = Matrix.Identity();
  1995. Matrix.TranslationToRef(x, y, z, result);
  1996. return result;
  1997. };
  1998. Matrix.TranslationToRef = function (x, y, z, result) {
  1999. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2000. };
  2001. Matrix.Lerp = function (startValue, endValue, gradient) {
  2002. var startScale = new Vector3(0, 0, 0);
  2003. var startRotation = new Quaternion();
  2004. var startTranslation = new Vector3(0, 0, 0);
  2005. startValue.decompose(startScale, startRotation, startTranslation);
  2006. var endScale = new Vector3(0, 0, 0);
  2007. var endRotation = new Quaternion();
  2008. var endTranslation = new Vector3(0, 0, 0);
  2009. endValue.decompose(endScale, endRotation, endTranslation);
  2010. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2011. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2012. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2013. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2014. };
  2015. Matrix.LookAtLH = function (eye, target, up) {
  2016. var result = Matrix.Zero();
  2017. Matrix.LookAtLHToRef(eye, target, up, result);
  2018. return result;
  2019. };
  2020. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2021. // Z axis
  2022. target.subtractToRef(eye, this._zAxis);
  2023. this._zAxis.normalize();
  2024. // X axis
  2025. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2026. if (this._xAxis.lengthSquared() === 0) {
  2027. this._xAxis.x = 1.0;
  2028. }
  2029. else {
  2030. this._xAxis.normalize();
  2031. }
  2032. // Y axis
  2033. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2034. this._yAxis.normalize();
  2035. // Eye angles
  2036. var ex = -Vector3.Dot(this._xAxis, eye);
  2037. var ey = -Vector3.Dot(this._yAxis, eye);
  2038. var ez = -Vector3.Dot(this._zAxis, eye);
  2039. 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);
  2040. };
  2041. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2042. var matrix = Matrix.Zero();
  2043. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2044. return matrix;
  2045. };
  2046. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2047. var hw = 2.0 / width;
  2048. var hh = 2.0 / height;
  2049. var id = 1.0 / (zfar - znear);
  2050. var nid = znear / (znear - zfar);
  2051. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2052. };
  2053. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2054. var matrix = Matrix.Zero();
  2055. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2056. return matrix;
  2057. };
  2058. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2059. result.m[0] = 2.0 / (right - left);
  2060. result.m[1] = result.m[2] = result.m[3] = 0;
  2061. result.m[5] = 2.0 / (top - bottom);
  2062. result.m[4] = result.m[6] = result.m[7] = 0;
  2063. result.m[10] = -1.0 / (znear - zfar);
  2064. result.m[8] = result.m[9] = result.m[11] = 0;
  2065. result.m[12] = (left + right) / (left - right);
  2066. result.m[13] = (top + bottom) / (bottom - top);
  2067. result.m[14] = znear / (znear - zfar);
  2068. result.m[15] = 1.0;
  2069. };
  2070. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2071. var matrix = Matrix.Zero();
  2072. matrix.m[0] = (2.0 * znear) / width;
  2073. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2074. matrix.m[5] = (2.0 * znear) / height;
  2075. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2076. matrix.m[10] = -zfar / (znear - zfar);
  2077. matrix.m[8] = matrix.m[9] = 0.0;
  2078. matrix.m[11] = 1.0;
  2079. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2080. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2081. return matrix;
  2082. };
  2083. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2084. var matrix = Matrix.Zero();
  2085. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2086. return matrix;
  2087. };
  2088. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2089. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2090. var tan = 1.0 / (Math.tan(fov * 0.5));
  2091. if (isVerticalFovFixed) {
  2092. result.m[0] = tan / aspect;
  2093. }
  2094. else {
  2095. result.m[0] = tan;
  2096. }
  2097. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2098. if (isVerticalFovFixed) {
  2099. result.m[5] = tan;
  2100. }
  2101. else {
  2102. result.m[5] = tan * aspect;
  2103. }
  2104. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2105. result.m[8] = result.m[9] = 0.0;
  2106. result.m[10] = -zfar / (znear - zfar);
  2107. result.m[11] = 1.0;
  2108. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2109. result.m[14] = (znear * zfar) / (znear - zfar);
  2110. };
  2111. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2112. var cw = viewport.width;
  2113. var ch = viewport.height;
  2114. var cx = viewport.x;
  2115. var cy = viewport.y;
  2116. 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);
  2117. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2118. };
  2119. Matrix.GetAsMatrix2x2 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1],
  2122. matrix.m[4], matrix.m[5]
  2123. ]);
  2124. };
  2125. Matrix.GetAsMatrix3x3 = function (matrix) {
  2126. return new Float32Array([
  2127. matrix.m[0], matrix.m[1], matrix.m[2],
  2128. matrix.m[4], matrix.m[5], matrix.m[6],
  2129. matrix.m[8], matrix.m[9], matrix.m[10]
  2130. ]);
  2131. };
  2132. Matrix.Transpose = function (matrix) {
  2133. var result = new Matrix();
  2134. result.m[0] = matrix.m[0];
  2135. result.m[1] = matrix.m[4];
  2136. result.m[2] = matrix.m[8];
  2137. result.m[3] = matrix.m[12];
  2138. result.m[4] = matrix.m[1];
  2139. result.m[5] = matrix.m[5];
  2140. result.m[6] = matrix.m[9];
  2141. result.m[7] = matrix.m[13];
  2142. result.m[8] = matrix.m[2];
  2143. result.m[9] = matrix.m[6];
  2144. result.m[10] = matrix.m[10];
  2145. result.m[11] = matrix.m[14];
  2146. result.m[12] = matrix.m[3];
  2147. result.m[13] = matrix.m[7];
  2148. result.m[14] = matrix.m[11];
  2149. result.m[15] = matrix.m[15];
  2150. return result;
  2151. };
  2152. Matrix.Reflection = function (plane) {
  2153. var matrix = new Matrix();
  2154. Matrix.ReflectionToRef(plane, matrix);
  2155. return matrix;
  2156. };
  2157. Matrix.ReflectionToRef = function (plane, result) {
  2158. plane.normalize();
  2159. var x = plane.normal.x;
  2160. var y = plane.normal.y;
  2161. var z = plane.normal.z;
  2162. var temp = -2 * x;
  2163. var temp2 = -2 * y;
  2164. var temp3 = -2 * z;
  2165. result.m[0] = (temp * x) + 1;
  2166. result.m[1] = temp2 * x;
  2167. result.m[2] = temp3 * x;
  2168. result.m[3] = 0.0;
  2169. result.m[4] = temp * y;
  2170. result.m[5] = (temp2 * y) + 1;
  2171. result.m[6] = temp3 * y;
  2172. result.m[7] = 0.0;
  2173. result.m[8] = temp * z;
  2174. result.m[9] = temp2 * z;
  2175. result.m[10] = (temp3 * z) + 1;
  2176. result.m[11] = 0.0;
  2177. result.m[12] = temp * plane.d;
  2178. result.m[13] = temp2 * plane.d;
  2179. result.m[14] = temp3 * plane.d;
  2180. result.m[15] = 1.0;
  2181. };
  2182. Matrix._tempQuaternion = new Quaternion();
  2183. Matrix._xAxis = Vector3.Zero();
  2184. Matrix._yAxis = Vector3.Zero();
  2185. Matrix._zAxis = Vector3.Zero();
  2186. return Matrix;
  2187. }());
  2188. BABYLON.Matrix = Matrix;
  2189. var Plane = (function () {
  2190. function Plane(a, b, c, d) {
  2191. this.normal = new Vector3(a, b, c);
  2192. this.d = d;
  2193. }
  2194. Plane.prototype.asArray = function () {
  2195. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2196. };
  2197. // Methods
  2198. Plane.prototype.clone = function () {
  2199. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2200. };
  2201. Plane.prototype.normalize = function () {
  2202. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2203. var magnitude = 0;
  2204. if (norm !== 0) {
  2205. magnitude = 1.0 / norm;
  2206. }
  2207. this.normal.x *= magnitude;
  2208. this.normal.y *= magnitude;
  2209. this.normal.z *= magnitude;
  2210. this.d *= magnitude;
  2211. return this;
  2212. };
  2213. Plane.prototype.transform = function (transformation) {
  2214. var transposedMatrix = Matrix.Transpose(transformation);
  2215. var x = this.normal.x;
  2216. var y = this.normal.y;
  2217. var z = this.normal.z;
  2218. var d = this.d;
  2219. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2220. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2221. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2222. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2223. return new Plane(normalX, normalY, normalZ, finalD);
  2224. };
  2225. Plane.prototype.dotCoordinate = function (point) {
  2226. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2227. };
  2228. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2229. var x1 = point2.x - point1.x;
  2230. var y1 = point2.y - point1.y;
  2231. var z1 = point2.z - point1.z;
  2232. var x2 = point3.x - point1.x;
  2233. var y2 = point3.y - point1.y;
  2234. var z2 = point3.z - point1.z;
  2235. var yz = (y1 * z2) - (z1 * y2);
  2236. var xz = (z1 * x2) - (x1 * z2);
  2237. var xy = (x1 * y2) - (y1 * x2);
  2238. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2239. var invPyth;
  2240. if (pyth !== 0) {
  2241. invPyth = 1.0 / pyth;
  2242. }
  2243. else {
  2244. invPyth = 0;
  2245. }
  2246. this.normal.x = yz * invPyth;
  2247. this.normal.y = xz * invPyth;
  2248. this.normal.z = xy * invPyth;
  2249. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2250. return this;
  2251. };
  2252. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2253. var dot = Vector3.Dot(this.normal, direction);
  2254. return (dot <= epsilon);
  2255. };
  2256. Plane.prototype.signedDistanceTo = function (point) {
  2257. return Vector3.Dot(point, this.normal) + this.d;
  2258. };
  2259. // Statics
  2260. Plane.FromArray = function (array) {
  2261. return new Plane(array[0], array[1], array[2], array[3]);
  2262. };
  2263. Plane.FromPoints = function (point1, point2, point3) {
  2264. var result = new Plane(0, 0, 0, 0);
  2265. result.copyFromPoints(point1, point2, point3);
  2266. return result;
  2267. };
  2268. Plane.FromPositionAndNormal = function (origin, normal) {
  2269. var result = new Plane(0, 0, 0, 0);
  2270. normal.normalize();
  2271. result.normal = normal;
  2272. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2273. return result;
  2274. };
  2275. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2276. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2277. return Vector3.Dot(point, normal) + d;
  2278. };
  2279. return Plane;
  2280. }());
  2281. BABYLON.Plane = Plane;
  2282. var Viewport = (function () {
  2283. function Viewport(x, y, width, height) {
  2284. this.x = x;
  2285. this.y = y;
  2286. this.width = width;
  2287. this.height = height;
  2288. }
  2289. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2290. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2291. };
  2292. return Viewport;
  2293. }());
  2294. BABYLON.Viewport = Viewport;
  2295. var Frustum = (function () {
  2296. function Frustum() {
  2297. }
  2298. Frustum.GetPlanes = function (transform) {
  2299. var frustumPlanes = [];
  2300. for (var index = 0; index < 6; index++) {
  2301. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2302. }
  2303. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2304. return frustumPlanes;
  2305. };
  2306. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2307. // Near
  2308. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2309. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2310. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2311. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2312. frustumPlanes[0].normalize();
  2313. // Far
  2314. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2315. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2316. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2317. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2318. frustumPlanes[1].normalize();
  2319. // Left
  2320. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2321. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2322. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2323. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2324. frustumPlanes[2].normalize();
  2325. // Right
  2326. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2327. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2328. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2329. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2330. frustumPlanes[3].normalize();
  2331. // Top
  2332. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2333. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2334. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2335. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2336. frustumPlanes[4].normalize();
  2337. // Bottom
  2338. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2339. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2340. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2341. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2342. frustumPlanes[5].normalize();
  2343. };
  2344. return Frustum;
  2345. }());
  2346. BABYLON.Frustum = Frustum;
  2347. (function (Space) {
  2348. Space[Space["LOCAL"] = 0] = "LOCAL";
  2349. Space[Space["WORLD"] = 1] = "WORLD";
  2350. })(BABYLON.Space || (BABYLON.Space = {}));
  2351. var Space = BABYLON.Space;
  2352. var Axis = (function () {
  2353. function Axis() {
  2354. }
  2355. Axis.X = new Vector3(1, 0, 0);
  2356. Axis.Y = new Vector3(0, 1, 0);
  2357. Axis.Z = new Vector3(0, 0, 1);
  2358. return Axis;
  2359. }());
  2360. BABYLON.Axis = Axis;
  2361. ;
  2362. var BezierCurve = (function () {
  2363. function BezierCurve() {
  2364. }
  2365. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2366. // Extract X (which is equal to time here)
  2367. var f0 = 1 - 3 * x2 + 3 * x1;
  2368. var f1 = 3 * x2 - 6 * x1;
  2369. var f2 = 3 * x1;
  2370. var refinedT = t;
  2371. for (var i = 0; i < 5; i++) {
  2372. var refinedT2 = refinedT * refinedT;
  2373. var refinedT3 = refinedT2 * refinedT;
  2374. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2375. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2376. refinedT -= (x - t) * slope;
  2377. refinedT = Math.min(1, Math.max(0, refinedT));
  2378. }
  2379. // Resolve cubic bezier for the given x
  2380. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2381. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2382. Math.pow(refinedT, 3);
  2383. };
  2384. return BezierCurve;
  2385. }());
  2386. BABYLON.BezierCurve = BezierCurve;
  2387. (function (Orientation) {
  2388. Orientation[Orientation["CW"] = 0] = "CW";
  2389. Orientation[Orientation["CCW"] = 1] = "CCW";
  2390. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2391. var Orientation = BABYLON.Orientation;
  2392. var Angle = (function () {
  2393. function Angle(radians) {
  2394. var _this = this;
  2395. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2396. this.radians = function () { return _this._radians; };
  2397. this._radians = radians;
  2398. if (this._radians < 0)
  2399. this._radians += (2 * Math.PI);
  2400. }
  2401. Angle.BetweenTwoPoints = function (a, b) {
  2402. var delta = b.subtract(a);
  2403. var theta = Math.atan2(delta.y, delta.x);
  2404. return new Angle(theta);
  2405. };
  2406. Angle.FromRadians = function (radians) {
  2407. return new Angle(radians);
  2408. };
  2409. Angle.FromDegrees = function (degrees) {
  2410. return new Angle(degrees * Math.PI / 180);
  2411. };
  2412. return Angle;
  2413. }());
  2414. BABYLON.Angle = Angle;
  2415. var Arc2 = (function () {
  2416. function Arc2(startPoint, midPoint, endPoint) {
  2417. this.startPoint = startPoint;
  2418. this.midPoint = midPoint;
  2419. this.endPoint = endPoint;
  2420. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2421. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2422. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2423. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2424. 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);
  2425. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2426. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2427. var a1 = this.startAngle.degrees();
  2428. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2429. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2430. // angles correction
  2431. if (a2 - a1 > +180.0)
  2432. a2 -= 360.0;
  2433. if (a2 - a1 < -180.0)
  2434. a2 += 360.0;
  2435. if (a3 - a2 > +180.0)
  2436. a3 -= 360.0;
  2437. if (a3 - a2 < -180.0)
  2438. a3 += 360.0;
  2439. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2440. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2441. }
  2442. return Arc2;
  2443. }());
  2444. BABYLON.Arc2 = Arc2;
  2445. var Path2 = (function () {
  2446. function Path2(x, y) {
  2447. this._points = new Array();
  2448. this._length = 0;
  2449. this.closed = false;
  2450. this._points.push(new Vector2(x, y));
  2451. }
  2452. Path2.prototype.addLineTo = function (x, y) {
  2453. if (closed) {
  2454. //Tools.Error("cannot add lines to closed paths");
  2455. return this;
  2456. }
  2457. var newPoint = new Vector2(x, y);
  2458. var previousPoint = this._points[this._points.length - 1];
  2459. this._points.push(newPoint);
  2460. this._length += newPoint.subtract(previousPoint).length();
  2461. return this;
  2462. };
  2463. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2464. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2465. if (closed) {
  2466. //Tools.Error("cannot add arcs to closed paths");
  2467. return this;
  2468. }
  2469. var startPoint = this._points[this._points.length - 1];
  2470. var midPoint = new Vector2(midX, midY);
  2471. var endPoint = new Vector2(endX, endY);
  2472. var arc = new Arc2(startPoint, midPoint, endPoint);
  2473. var increment = arc.angle.radians() / numberOfSegments;
  2474. if (arc.orientation === Orientation.CW)
  2475. increment *= -1;
  2476. var currentAngle = arc.startAngle.radians() + increment;
  2477. for (var i = 0; i < numberOfSegments; i++) {
  2478. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2479. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2480. this.addLineTo(x, y);
  2481. currentAngle += increment;
  2482. }
  2483. return this;
  2484. };
  2485. Path2.prototype.close = function () {
  2486. this.closed = true;
  2487. return this;
  2488. };
  2489. Path2.prototype.length = function () {
  2490. var result = this._length;
  2491. if (!this.closed) {
  2492. var lastPoint = this._points[this._points.length - 1];
  2493. var firstPoint = this._points[0];
  2494. result += (firstPoint.subtract(lastPoint).length());
  2495. }
  2496. return result;
  2497. };
  2498. Path2.prototype.getPoints = function () {
  2499. return this._points;
  2500. };
  2501. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2502. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2503. //Tools.Error("normalized length position should be between 0 and 1.");
  2504. return Vector2.Zero();
  2505. }
  2506. var lengthPosition = normalizedLengthPosition * this.length();
  2507. var previousOffset = 0;
  2508. for (var i = 0; i < this._points.length; i++) {
  2509. var j = (i + 1) % this._points.length;
  2510. var a = this._points[i];
  2511. var b = this._points[j];
  2512. var bToA = b.subtract(a);
  2513. var nextOffset = (bToA.length() + previousOffset);
  2514. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2515. var dir = bToA.normalize();
  2516. var localOffset = lengthPosition - previousOffset;
  2517. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2518. }
  2519. previousOffset = nextOffset;
  2520. }
  2521. //Tools.Error("internal error");
  2522. return Vector2.Zero();
  2523. };
  2524. Path2.StartingAt = function (x, y) {
  2525. return new Path2(x, y);
  2526. };
  2527. return Path2;
  2528. }());
  2529. BABYLON.Path2 = Path2;
  2530. var Path3D = (function () {
  2531. /**
  2532. * new Path3D(path, normal, raw)
  2533. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2534. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2535. * path : an array of Vector3, the curve axis of the Path3D
  2536. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2537. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2538. */
  2539. function Path3D(path, firstNormal, raw) {
  2540. this.path = path;
  2541. this._curve = new Array();
  2542. this._distances = new Array();
  2543. this._tangents = new Array();
  2544. this._normals = new Array();
  2545. this._binormals = new Array();
  2546. for (var p = 0; p < path.length; p++) {
  2547. this._curve[p] = path[p].clone(); // hard copy
  2548. }
  2549. this._raw = raw || false;
  2550. this._compute(firstNormal);
  2551. }
  2552. /**
  2553. * Returns the Path3D array of successive Vector3 designing its curve.
  2554. */
  2555. Path3D.prototype.getCurve = function () {
  2556. return this._curve;
  2557. };
  2558. /**
  2559. * Returns an array populated with tangent vectors on each Path3D curve point.
  2560. */
  2561. Path3D.prototype.getTangents = function () {
  2562. return this._tangents;
  2563. };
  2564. /**
  2565. * Returns an array populated with normal vectors on each Path3D curve point.
  2566. */
  2567. Path3D.prototype.getNormals = function () {
  2568. return this._normals;
  2569. };
  2570. /**
  2571. * Returns an array populated with binormal vectors on each Path3D curve point.
  2572. */
  2573. Path3D.prototype.getBinormals = function () {
  2574. return this._binormals;
  2575. };
  2576. /**
  2577. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2578. */
  2579. Path3D.prototype.getDistances = function () {
  2580. return this._distances;
  2581. };
  2582. /**
  2583. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2584. * Returns the same object updated.
  2585. */
  2586. Path3D.prototype.update = function (path, firstNormal) {
  2587. for (var p = 0; p < path.length; p++) {
  2588. this._curve[p].x = path[p].x;
  2589. this._curve[p].y = path[p].y;
  2590. this._curve[p].z = path[p].z;
  2591. }
  2592. this._compute(firstNormal);
  2593. return this;
  2594. };
  2595. // private function compute() : computes tangents, normals and binormals
  2596. Path3D.prototype._compute = function (firstNormal) {
  2597. var l = this._curve.length;
  2598. // first and last tangents
  2599. this._tangents[0] = this._getFirstNonNullVector(0);
  2600. if (!this._raw) {
  2601. this._tangents[0].normalize();
  2602. }
  2603. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2604. if (!this._raw) {
  2605. this._tangents[l - 1].normalize();
  2606. }
  2607. // normals and binormals at first point : arbitrary vector with _normalVector()
  2608. var tg0 = this._tangents[0];
  2609. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2610. this._normals[0] = pp0;
  2611. if (!this._raw) {
  2612. this._normals[0].normalize();
  2613. }
  2614. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2615. if (!this._raw) {
  2616. this._binormals[0].normalize();
  2617. }
  2618. this._distances[0] = 0;
  2619. // normals and binormals : next points
  2620. var prev; // previous vector (segment)
  2621. var cur; // current vector (segment)
  2622. var curTang; // current tangent
  2623. // previous normal
  2624. var prevBinor; // previous binormal
  2625. for (var i = 1; i < l; i++) {
  2626. // tangents
  2627. prev = this._getLastNonNullVector(i);
  2628. if (i < l - 1) {
  2629. cur = this._getFirstNonNullVector(i);
  2630. this._tangents[i] = prev.add(cur);
  2631. this._tangents[i].normalize();
  2632. }
  2633. this._distances[i] = this._distances[i - 1] + prev.length();
  2634. // normals and binormals
  2635. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2636. curTang = this._tangents[i];
  2637. prevBinor = this._binormals[i - 1];
  2638. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2639. if (!this._raw) {
  2640. this._normals[i].normalize();
  2641. }
  2642. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2643. if (!this._raw) {
  2644. this._binormals[i].normalize();
  2645. }
  2646. }
  2647. };
  2648. // private function getFirstNonNullVector(index)
  2649. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2650. Path3D.prototype._getFirstNonNullVector = function (index) {
  2651. var i = 1;
  2652. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2653. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2654. i++;
  2655. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2656. }
  2657. return nNVector;
  2658. };
  2659. // private function getLastNonNullVector(index)
  2660. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2661. Path3D.prototype._getLastNonNullVector = function (index) {
  2662. var i = 1;
  2663. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2664. while (nLVector.length() === 0 && index > i + 1) {
  2665. i++;
  2666. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2667. }
  2668. return nLVector;
  2669. };
  2670. // private function normalVector(v0, vt, va) :
  2671. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2672. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2673. Path3D.prototype._normalVector = function (v0, vt, va) {
  2674. var normal0;
  2675. if (va === undefined || va === null) {
  2676. var point;
  2677. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2678. point = new Vector3(0, -1, 0);
  2679. }
  2680. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2681. point = new Vector3(1, 0, 0);
  2682. }
  2683. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2684. point = new Vector3(0, 0, 1);
  2685. }
  2686. normal0 = Vector3.Cross(vt, point);
  2687. }
  2688. else {
  2689. normal0 = Vector3.Cross(vt, va);
  2690. Vector3.CrossToRef(normal0, vt, normal0);
  2691. }
  2692. normal0.normalize();
  2693. return normal0;
  2694. };
  2695. return Path3D;
  2696. }());
  2697. BABYLON.Path3D = Path3D;
  2698. var Curve3 = (function () {
  2699. /**
  2700. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2701. * A Curve3 is designed from a series of successive Vector3.
  2702. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2703. */
  2704. function Curve3(points) {
  2705. this._length = 0;
  2706. this._points = points;
  2707. this._length = this._computeLength(points);
  2708. }
  2709. /**
  2710. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2711. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2712. * @param v1 (Vector3) the control point
  2713. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2714. * @param nbPoints (integer) the wanted number of points in the curve
  2715. */
  2716. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2717. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2718. var bez = new Array();
  2719. var equation = function (t, val0, val1, val2) {
  2720. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2721. return res;
  2722. };
  2723. for (var i = 0; i <= nbPoints; i++) {
  2724. 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)));
  2725. }
  2726. return new Curve3(bez);
  2727. };
  2728. /**
  2729. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2730. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2731. * @param v1 (Vector3) the first control point
  2732. * @param v2 (Vector3) the second control point
  2733. * @param v3 (Vector3) the end point of the Cubic Bezier
  2734. * @param nbPoints (integer) the wanted number of points in the curve
  2735. */
  2736. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2737. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2738. var bez = new Array();
  2739. var equation = function (t, val0, val1, val2, val3) {
  2740. 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;
  2741. return res;
  2742. };
  2743. for (var i = 0; i <= nbPoints; i++) {
  2744. 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)));
  2745. }
  2746. return new Curve3(bez);
  2747. };
  2748. /**
  2749. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2750. * @param p1 (Vector3) the origin point of the Hermite Spline
  2751. * @param t1 (Vector3) the tangent vector at the origin point
  2752. * @param p2 (Vector3) the end point of the Hermite Spline
  2753. * @param t2 (Vector3) the tangent vector at the end point
  2754. * @param nbPoints (integer) the wanted number of points in the curve
  2755. */
  2756. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2757. var hermite = new Array();
  2758. var step = 1 / nbPoints;
  2759. for (var i = 0; i <= nbPoints; i++) {
  2760. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2761. }
  2762. return new Curve3(hermite);
  2763. };
  2764. /**
  2765. * Returns the Curve3 stored array of successive Vector3
  2766. */
  2767. Curve3.prototype.getPoints = function () {
  2768. return this._points;
  2769. };
  2770. /**
  2771. * Returns the computed length (float) of the curve.
  2772. */
  2773. Curve3.prototype.length = function () {
  2774. return this._length;
  2775. };
  2776. /**
  2777. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2778. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2779. * curveA and curveB keep unchanged.
  2780. */
  2781. Curve3.prototype.continue = function (curve) {
  2782. var lastPoint = this._points[this._points.length - 1];
  2783. var continuedPoints = this._points.slice();
  2784. var curvePoints = curve.getPoints();
  2785. for (var i = 1; i < curvePoints.length; i++) {
  2786. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2787. }
  2788. var continuedCurve = new Curve3(continuedPoints);
  2789. return continuedCurve;
  2790. };
  2791. Curve3.prototype._computeLength = function (path) {
  2792. var l = 0;
  2793. for (var i = 1; i < path.length; i++) {
  2794. l += (path[i].subtract(path[i - 1])).length();
  2795. }
  2796. return l;
  2797. };
  2798. return Curve3;
  2799. }());
  2800. BABYLON.Curve3 = Curve3;
  2801. // SphericalHarmonics
  2802. var SphericalHarmonics = (function () {
  2803. function SphericalHarmonics() {
  2804. this.L00 = Vector3.Zero();
  2805. this.L1_1 = Vector3.Zero();
  2806. this.L10 = Vector3.Zero();
  2807. this.L11 = Vector3.Zero();
  2808. this.L2_2 = Vector3.Zero();
  2809. this.L2_1 = Vector3.Zero();
  2810. this.L20 = Vector3.Zero();
  2811. this.L21 = Vector3.Zero();
  2812. this.L22 = Vector3.Zero();
  2813. }
  2814. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2815. var colorVector = new Vector3(color.r, color.g, color.b);
  2816. var c = colorVector.scale(deltaSolidAngle);
  2817. this.L00 = this.L00.add(c.scale(0.282095));
  2818. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2819. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2820. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2821. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2822. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2823. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2824. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2825. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2826. };
  2827. SphericalHarmonics.prototype.scale = function (scale) {
  2828. this.L00 = this.L00.scale(scale);
  2829. this.L1_1 = this.L1_1.scale(scale);
  2830. this.L10 = this.L10.scale(scale);
  2831. this.L11 = this.L11.scale(scale);
  2832. this.L2_2 = this.L2_2.scale(scale);
  2833. this.L2_1 = this.L2_1.scale(scale);
  2834. this.L20 = this.L20.scale(scale);
  2835. this.L21 = this.L21.scale(scale);
  2836. this.L22 = this.L22.scale(scale);
  2837. };
  2838. return SphericalHarmonics;
  2839. }());
  2840. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2841. // SphericalPolynomial
  2842. var SphericalPolynomial = (function () {
  2843. function SphericalPolynomial() {
  2844. this.x = Vector3.Zero();
  2845. this.y = Vector3.Zero();
  2846. this.z = Vector3.Zero();
  2847. this.xx = Vector3.Zero();
  2848. this.yy = Vector3.Zero();
  2849. this.zz = Vector3.Zero();
  2850. this.xy = Vector3.Zero();
  2851. this.yz = Vector3.Zero();
  2852. this.zx = Vector3.Zero();
  2853. }
  2854. SphericalPolynomial.prototype.addAmbient = function (color) {
  2855. var colorVector = new Vector3(color.r, color.g, color.b);
  2856. this.xx = this.xx.add(colorVector);
  2857. this.yy = this.yy.add(colorVector);
  2858. this.zz = this.zz.add(colorVector);
  2859. };
  2860. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2861. var result = new SphericalPolynomial();
  2862. result.x = harmonics.L11.scale(1.02333);
  2863. result.y = harmonics.L1_1.scale(1.02333);
  2864. result.z = harmonics.L10.scale(1.02333);
  2865. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2866. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2867. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2868. result.yz = harmonics.L2_1.scale(0.858086);
  2869. result.zx = harmonics.L21.scale(0.858086);
  2870. result.xy = harmonics.L2_2.scale(0.858086);
  2871. return result;
  2872. };
  2873. return SphericalPolynomial;
  2874. }());
  2875. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2876. // Vertex formats
  2877. var PositionNormalVertex = (function () {
  2878. function PositionNormalVertex(position, normal) {
  2879. if (position === void 0) { position = Vector3.Zero(); }
  2880. if (normal === void 0) { normal = Vector3.Up(); }
  2881. this.position = position;
  2882. this.normal = normal;
  2883. }
  2884. PositionNormalVertex.prototype.clone = function () {
  2885. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2886. };
  2887. return PositionNormalVertex;
  2888. }());
  2889. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2890. var PositionNormalTextureVertex = (function () {
  2891. function PositionNormalTextureVertex(position, normal, uv) {
  2892. if (position === void 0) { position = Vector3.Zero(); }
  2893. if (normal === void 0) { normal = Vector3.Up(); }
  2894. if (uv === void 0) { uv = Vector2.Zero(); }
  2895. this.position = position;
  2896. this.normal = normal;
  2897. this.uv = uv;
  2898. }
  2899. PositionNormalTextureVertex.prototype.clone = function () {
  2900. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2901. };
  2902. return PositionNormalTextureVertex;
  2903. }());
  2904. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2905. // Temporary pre-allocated objects for engine internal use
  2906. // usage in any internal function :
  2907. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2908. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2909. var Tmp = (function () {
  2910. function Tmp() {
  2911. }
  2912. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2913. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2914. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2915. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2916. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2917. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2918. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2919. Matrix.Zero(), Matrix.Zero(),
  2920. Matrix.Zero(), Matrix.Zero(),
  2921. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2922. return Tmp;
  2923. }());
  2924. BABYLON.Tmp = Tmp;
  2925. })(BABYLON || (BABYLON = {}));
  2926. var BABYLON;
  2927. (function (BABYLON) {
  2928. function generateSerializableMember(type, sourceName) {
  2929. return function (target, propertyKey) {
  2930. if (!target.__serializableMembers) {
  2931. target.__serializableMembers = {};
  2932. }
  2933. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2934. };
  2935. }
  2936. function serialize(sourceName) {
  2937. return generateSerializableMember(0, sourceName); // value member
  2938. }
  2939. BABYLON.serialize = serialize;
  2940. function serializeAsTexture(sourceName) {
  2941. return generateSerializableMember(1, sourceName); // texture member
  2942. }
  2943. BABYLON.serializeAsTexture = serializeAsTexture;
  2944. function serializeAsColor3(sourceName) {
  2945. return generateSerializableMember(2, sourceName); // color3 member
  2946. }
  2947. BABYLON.serializeAsColor3 = serializeAsColor3;
  2948. function serializeAsFresnelParameters(sourceName) {
  2949. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2950. }
  2951. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2952. function serializeAsVector2(sourceName) {
  2953. return generateSerializableMember(4, sourceName); // vector2 member
  2954. }
  2955. BABYLON.serializeAsVector2 = serializeAsVector2;
  2956. function serializeAsVector3(sourceName) {
  2957. return generateSerializableMember(5, sourceName); // vector3 member
  2958. }
  2959. BABYLON.serializeAsVector3 = serializeAsVector3;
  2960. function serializeAsMeshReference(sourceName) {
  2961. return generateSerializableMember(6, sourceName); // mesh reference member
  2962. }
  2963. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2964. var SerializationHelper = (function () {
  2965. function SerializationHelper() {
  2966. }
  2967. SerializationHelper.Serialize = function (entity, serializationObject) {
  2968. if (!serializationObject) {
  2969. serializationObject = {};
  2970. }
  2971. // Tags
  2972. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2973. // Properties
  2974. for (var property in entity.__serializableMembers) {
  2975. var propertyDescriptor = entity.__serializableMembers[property];
  2976. var targetPropertyName = propertyDescriptor.sourceName || property;
  2977. var propertyType = propertyDescriptor.type;
  2978. var sourceProperty = entity[property];
  2979. if (sourceProperty !== undefined && sourceProperty !== null) {
  2980. switch (propertyType) {
  2981. case 0:
  2982. serializationObject[targetPropertyName] = sourceProperty;
  2983. break;
  2984. case 1:
  2985. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2986. break;
  2987. case 2:
  2988. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2989. break;
  2990. case 3:
  2991. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2992. break;
  2993. case 4:
  2994. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2995. break;
  2996. case 5:
  2997. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2998. break;
  2999. case 6:
  3000. serializationObject[targetPropertyName] = sourceProperty.id;
  3001. break;
  3002. }
  3003. }
  3004. }
  3005. return serializationObject;
  3006. };
  3007. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3008. var destination = creationFunction();
  3009. // Tags
  3010. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3011. // Properties
  3012. for (var property in destination.__serializableMembers) {
  3013. var propertyDescriptor = destination.__serializableMembers[property];
  3014. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3015. var propertyType = propertyDescriptor.type;
  3016. if (sourceProperty !== undefined && sourceProperty !== null) {
  3017. switch (propertyType) {
  3018. case 0:
  3019. destination[property] = sourceProperty;
  3020. break;
  3021. case 1:
  3022. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3023. break;
  3024. case 2:
  3025. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3026. break;
  3027. case 3:
  3028. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3029. break;
  3030. case 4:
  3031. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3032. break;
  3033. case 5:
  3034. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3035. break;
  3036. case 6:
  3037. destination[property] = scene.getLastMeshByID(sourceProperty);
  3038. break;
  3039. }
  3040. }
  3041. }
  3042. return destination;
  3043. };
  3044. SerializationHelper.Clone = function (creationFunction, source) {
  3045. var destination = creationFunction();
  3046. // Tags
  3047. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3048. // Properties
  3049. for (var property in destination.__serializableMembers) {
  3050. var propertyDescriptor = destination.__serializableMembers[property];
  3051. var sourceProperty = source[property];
  3052. var propertyType = propertyDescriptor.type;
  3053. if (sourceProperty !== undefined && sourceProperty !== null) {
  3054. switch (propertyType) {
  3055. case 0: // Value
  3056. case 6:
  3057. destination[property] = sourceProperty;
  3058. break;
  3059. case 1: // Texture
  3060. case 2: // Color3
  3061. case 3: // FresnelParameters
  3062. case 4: // Vector2
  3063. case 5:
  3064. destination[property] = sourceProperty.clone();
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. return destination;
  3070. };
  3071. return SerializationHelper;
  3072. }());
  3073. BABYLON.SerializationHelper = SerializationHelper;
  3074. })(BABYLON || (BABYLON = {}));
  3075. var BABYLON;
  3076. (function (BABYLON) {
  3077. /**
  3078. * A class serves as a medium between the observable and its observers
  3079. */
  3080. var EventState = (function () {
  3081. /**
  3082. * If the callback of a given Observer set skipNextObervers to true the following observers will be ignored
  3083. */
  3084. function EventState(skipNextObervers) {
  3085. if (skipNextObervers === void 0) { skipNextObervers = false; }
  3086. this.skipNextObervers = skipNextObervers;
  3087. }
  3088. return EventState;
  3089. }());
  3090. BABYLON.EventState = EventState;
  3091. var Observer = (function () {
  3092. function Observer(callback) {
  3093. this.callback = callback;
  3094. }
  3095. return Observer;
  3096. }());
  3097. BABYLON.Observer = Observer;
  3098. var Observable = (function () {
  3099. function Observable() {
  3100. this._observers = new Array();
  3101. }
  3102. /**
  3103. * Create a new Observer with the specified callback
  3104. * @param callback the callback that will be executed for that Observer
  3105. * @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.
  3106. */
  3107. Observable.prototype.add = function (callback, insertFirst) {
  3108. if (insertFirst === void 0) { insertFirst = false; }
  3109. if (!callback) {
  3110. return null;
  3111. }
  3112. var observer = new Observer(callback);
  3113. if (insertFirst) {
  3114. this._observers.unshift(observer);
  3115. }
  3116. else {
  3117. this._observers.push(observer);
  3118. }
  3119. return observer;
  3120. };
  3121. /**
  3122. * Remove an Observer from the Observable object
  3123. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3124. */
  3125. Observable.prototype.remove = function (observer) {
  3126. var index = this._observers.indexOf(observer);
  3127. if (index !== -1) {
  3128. this._observers.splice(index, 1);
  3129. return true;
  3130. }
  3131. return false;
  3132. };
  3133. /**
  3134. * Remove a callback from the Observable object
  3135. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3136. */
  3137. Observable.prototype.removeCallback = function (callback) {
  3138. for (var index = 0; index < this._observers.length; index++) {
  3139. if (this._observers[index].callback === callback) {
  3140. this._observers.splice(index, 1);
  3141. return true;
  3142. }
  3143. }
  3144. return false;
  3145. };
  3146. /**
  3147. * Notify all Observers by calling their respective callback with the given data
  3148. * @param eventData
  3149. */
  3150. Observable.prototype.notifyObservers = function (eventData) {
  3151. var state = new EventState();
  3152. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3153. var obs = _a[_i];
  3154. obs.callback(eventData, state);
  3155. if (state.skipNextObervers) {
  3156. break;
  3157. }
  3158. }
  3159. };
  3160. /**
  3161. * Clear the list of observers
  3162. */
  3163. Observable.prototype.clear = function () {
  3164. this._observers = new Array();
  3165. };
  3166. /**
  3167. * Clone the current observable
  3168. */
  3169. Observable.prototype.clone = function () {
  3170. var result = new Observable();
  3171. result._observers = this._observers.slice(0);
  3172. return result;
  3173. };
  3174. return Observable;
  3175. }());
  3176. BABYLON.Observable = Observable;
  3177. })(BABYLON || (BABYLON = {}));
  3178. var BABYLON;
  3179. (function (BABYLON) {
  3180. var Database = (function () {
  3181. function Database(urlToScene, callbackManifestChecked) {
  3182. // Handling various flavors of prefixed version of IndexedDB
  3183. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3184. this.callbackManifestChecked = callbackManifestChecked;
  3185. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3186. this.db = null;
  3187. this.enableSceneOffline = false;
  3188. this.enableTexturesOffline = false;
  3189. this.manifestVersionFound = 0;
  3190. this.mustUpdateRessources = false;
  3191. this.hasReachedQuota = false;
  3192. if (!Database.IDBStorageEnabled) {
  3193. this.callbackManifestChecked(true);
  3194. }
  3195. else {
  3196. this.checkManifestFile();
  3197. }
  3198. }
  3199. Database.prototype.checkManifestFile = function () {
  3200. var _this = this;
  3201. function noManifestFile() {
  3202. that.enableSceneOffline = false;
  3203. that.enableTexturesOffline = false;
  3204. that.callbackManifestChecked(false);
  3205. }
  3206. var that = this;
  3207. var timeStampUsed = false;
  3208. var manifestURL = this.currentSceneUrl + ".manifest";
  3209. var xhr = new XMLHttpRequest();
  3210. if (navigator.onLine) {
  3211. // Adding a timestamp to by-pass browsers' cache
  3212. timeStampUsed = true;
  3213. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3214. }
  3215. xhr.open("GET", manifestURL, true);
  3216. xhr.addEventListener("load", function () {
  3217. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3218. try {
  3219. var manifestFile = JSON.parse(xhr.response);
  3220. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3221. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3222. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3223. _this.manifestVersionFound = manifestFile.version;
  3224. }
  3225. if (_this.callbackManifestChecked) {
  3226. _this.callbackManifestChecked(true);
  3227. }
  3228. }
  3229. catch (ex) {
  3230. noManifestFile();
  3231. }
  3232. }
  3233. else {
  3234. noManifestFile();
  3235. }
  3236. }, false);
  3237. xhr.addEventListener("error", function (event) {
  3238. if (timeStampUsed) {
  3239. timeStampUsed = false;
  3240. // Let's retry without the timeStamp
  3241. // It could fail when coupled with HTML5 Offline API
  3242. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3243. xhr.open("GET", retryManifestURL, true);
  3244. xhr.send();
  3245. }
  3246. else {
  3247. noManifestFile();
  3248. }
  3249. }, false);
  3250. try {
  3251. xhr.send();
  3252. }
  3253. catch (ex) {
  3254. BABYLON.Tools.Error("Error on XHR send request.");
  3255. that.callbackManifestChecked(false);
  3256. }
  3257. };
  3258. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3259. var _this = this;
  3260. function handleError() {
  3261. that.isSupported = false;
  3262. if (errorCallback)
  3263. errorCallback();
  3264. }
  3265. var that = this;
  3266. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3267. // Your browser doesn't support IndexedDB
  3268. this.isSupported = false;
  3269. if (errorCallback)
  3270. errorCallback();
  3271. }
  3272. else {
  3273. // If the DB hasn't been opened or created yet
  3274. if (!this.db) {
  3275. this.hasReachedQuota = false;
  3276. this.isSupported = true;
  3277. var request = this.idbFactory.open("babylonjs", 1);
  3278. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3279. request.onerror = function (event) {
  3280. handleError();
  3281. };
  3282. // executes when a version change transaction cannot complete due to other active transactions
  3283. request.onblocked = function (event) {
  3284. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3285. handleError();
  3286. };
  3287. // DB has been opened successfully
  3288. request.onsuccess = function (event) {
  3289. _this.db = request.result;
  3290. successCallback();
  3291. };
  3292. // Initialization of the DB. Creating Scenes & Textures stores
  3293. request.onupgradeneeded = function (event) {
  3294. _this.db = (event.target).result;
  3295. try {
  3296. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3297. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3298. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3299. }
  3300. catch (ex) {
  3301. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3302. handleError();
  3303. }
  3304. };
  3305. }
  3306. else {
  3307. if (successCallback)
  3308. successCallback();
  3309. }
  3310. }
  3311. };
  3312. Database.prototype.loadImageFromDB = function (url, image) {
  3313. var _this = this;
  3314. var completeURL = Database.ReturnFullUrlLocation(url);
  3315. var saveAndLoadImage = function () {
  3316. if (!_this.hasReachedQuota && _this.db !== null) {
  3317. // the texture is not yet in the DB, let's try to save it
  3318. _this._saveImageIntoDBAsync(completeURL, image);
  3319. }
  3320. else {
  3321. image.src = url;
  3322. }
  3323. };
  3324. if (!this.mustUpdateRessources) {
  3325. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3326. }
  3327. else {
  3328. saveAndLoadImage();
  3329. }
  3330. };
  3331. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3332. if (this.isSupported && this.db !== null) {
  3333. var texture;
  3334. var transaction = this.db.transaction(["textures"]);
  3335. transaction.onabort = function (event) {
  3336. image.src = url;
  3337. };
  3338. transaction.oncomplete = function (event) {
  3339. var blobTextureURL;
  3340. if (texture) {
  3341. var URL = window.URL || window.webkitURL;
  3342. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3343. image.onerror = function () {
  3344. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3345. image.src = url;
  3346. };
  3347. image.src = blobTextureURL;
  3348. }
  3349. else {
  3350. notInDBCallback();
  3351. }
  3352. };
  3353. var getRequest = transaction.objectStore("textures").get(url);
  3354. getRequest.onsuccess = function (event) {
  3355. texture = (event.target).result;
  3356. };
  3357. getRequest.onerror = function (event) {
  3358. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3359. image.src = url;
  3360. };
  3361. }
  3362. else {
  3363. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3364. image.src = url;
  3365. }
  3366. };
  3367. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3368. var _this = this;
  3369. if (this.isSupported) {
  3370. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3371. var generateBlobUrl = function () {
  3372. var blobTextureURL;
  3373. if (blob) {
  3374. var URL = window.URL || window.webkitURL;
  3375. try {
  3376. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3377. }
  3378. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3379. catch (ex) {
  3380. blobTextureURL = URL.createObjectURL(blob);
  3381. }
  3382. }
  3383. image.src = blobTextureURL;
  3384. };
  3385. if (Database.IsUASupportingBlobStorage) {
  3386. var xhr = new XMLHttpRequest(), blob;
  3387. xhr.open("GET", url, true);
  3388. xhr.responseType = "blob";
  3389. xhr.addEventListener("load", function () {
  3390. if (xhr.status === 200) {
  3391. // Blob as response (XHR2)
  3392. blob = xhr.response;
  3393. var transaction = _this.db.transaction(["textures"], "readwrite");
  3394. // the transaction could abort because of a QuotaExceededError error
  3395. transaction.onabort = function (event) {
  3396. try {
  3397. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3398. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3399. this.hasReachedQuota = true;
  3400. }
  3401. }
  3402. catch (ex) { }
  3403. generateBlobUrl();
  3404. };
  3405. transaction.oncomplete = function (event) {
  3406. generateBlobUrl();
  3407. };
  3408. var newTexture = { textureUrl: url, data: blob };
  3409. try {
  3410. // Put the blob into the dabase
  3411. var addRequest = transaction.objectStore("textures").put(newTexture);
  3412. addRequest.onsuccess = function (event) {
  3413. };
  3414. addRequest.onerror = function (event) {
  3415. generateBlobUrl();
  3416. };
  3417. }
  3418. catch (ex) {
  3419. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3420. if (ex.code === 25) {
  3421. Database.IsUASupportingBlobStorage = false;
  3422. }
  3423. image.src = url;
  3424. }
  3425. }
  3426. else {
  3427. image.src = url;
  3428. }
  3429. }, false);
  3430. xhr.addEventListener("error", function (event) {
  3431. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3432. image.src = url;
  3433. }, false);
  3434. xhr.send();
  3435. }
  3436. else {
  3437. image.src = url;
  3438. }
  3439. }
  3440. else {
  3441. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3442. image.src = url;
  3443. }
  3444. };
  3445. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3446. var _this = this;
  3447. var updateVersion = function (event) {
  3448. // the version is not yet in the DB or we need to update it
  3449. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3450. };
  3451. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3452. };
  3453. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3454. var _this = this;
  3455. if (this.isSupported) {
  3456. var version;
  3457. try {
  3458. var transaction = this.db.transaction(["versions"]);
  3459. transaction.oncomplete = function (event) {
  3460. if (version) {
  3461. // If the version in the JSON file is > than the version in DB
  3462. if (_this.manifestVersionFound > version.data) {
  3463. _this.mustUpdateRessources = true;
  3464. updateInDBCallback();
  3465. }
  3466. else {
  3467. callback(version.data);
  3468. }
  3469. }
  3470. else {
  3471. _this.mustUpdateRessources = true;
  3472. updateInDBCallback();
  3473. }
  3474. };
  3475. transaction.onabort = function (event) {
  3476. callback(-1);
  3477. };
  3478. var getRequest = transaction.objectStore("versions").get(url);
  3479. getRequest.onsuccess = function (event) {
  3480. version = (event.target).result;
  3481. };
  3482. getRequest.onerror = function (event) {
  3483. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3484. callback(-1);
  3485. };
  3486. }
  3487. catch (ex) {
  3488. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3489. callback(-1);
  3490. }
  3491. }
  3492. else {
  3493. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3494. callback(-1);
  3495. }
  3496. };
  3497. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3498. var _this = this;
  3499. if (this.isSupported && !this.hasReachedQuota) {
  3500. try {
  3501. // Open a transaction to the database
  3502. var transaction = this.db.transaction(["versions"], "readwrite");
  3503. // the transaction could abort because of a QuotaExceededError error
  3504. transaction.onabort = function (event) {
  3505. try {
  3506. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3507. _this.hasReachedQuota = true;
  3508. }
  3509. }
  3510. catch (ex) { }
  3511. callback(-1);
  3512. };
  3513. transaction.oncomplete = function (event) {
  3514. callback(_this.manifestVersionFound);
  3515. };
  3516. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3517. // Put the scene into the database
  3518. var addRequest = transaction.objectStore("versions").put(newVersion);
  3519. addRequest.onsuccess = function (event) {
  3520. };
  3521. addRequest.onerror = function (event) {
  3522. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3523. };
  3524. }
  3525. catch (ex) {
  3526. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3527. callback(-1);
  3528. }
  3529. }
  3530. else {
  3531. callback(-1);
  3532. }
  3533. };
  3534. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3535. var _this = this;
  3536. var completeUrl = Database.ReturnFullUrlLocation(url);
  3537. var saveAndLoadFile = function (event) {
  3538. // the scene is not yet in the DB, let's try to save it
  3539. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3540. };
  3541. this._checkVersionFromDB(completeUrl, function (version) {
  3542. if (version !== -1) {
  3543. if (!_this.mustUpdateRessources) {
  3544. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3545. }
  3546. else {
  3547. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3548. }
  3549. }
  3550. else {
  3551. errorCallback();
  3552. }
  3553. });
  3554. };
  3555. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3556. if (this.isSupported) {
  3557. var targetStore;
  3558. if (url.indexOf(".babylon") !== -1) {
  3559. targetStore = "scenes";
  3560. }
  3561. else {
  3562. targetStore = "textures";
  3563. }
  3564. var file;
  3565. var transaction = this.db.transaction([targetStore]);
  3566. transaction.oncomplete = function (event) {
  3567. if (file) {
  3568. callback(file.data);
  3569. }
  3570. else {
  3571. notInDBCallback();
  3572. }
  3573. };
  3574. transaction.onabort = function (event) {
  3575. notInDBCallback();
  3576. };
  3577. var getRequest = transaction.objectStore(targetStore).get(url);
  3578. getRequest.onsuccess = function (event) {
  3579. file = (event.target).result;
  3580. };
  3581. getRequest.onerror = function (event) {
  3582. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3583. notInDBCallback();
  3584. };
  3585. }
  3586. else {
  3587. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3588. callback();
  3589. }
  3590. };
  3591. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3592. var _this = this;
  3593. if (this.isSupported) {
  3594. var targetStore;
  3595. if (url.indexOf(".babylon") !== -1) {
  3596. targetStore = "scenes";
  3597. }
  3598. else {
  3599. targetStore = "textures";
  3600. }
  3601. // Create XHR
  3602. var xhr = new XMLHttpRequest(), fileData;
  3603. xhr.open("GET", url, true);
  3604. if (useArrayBuffer) {
  3605. xhr.responseType = "arraybuffer";
  3606. }
  3607. xhr.onprogress = progressCallback;
  3608. xhr.addEventListener("load", function () {
  3609. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3610. // Blob as response (XHR2)
  3611. //fileData = xhr.responseText;
  3612. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3613. if (!_this.hasReachedQuota) {
  3614. // Open a transaction to the database
  3615. var transaction = _this.db.transaction([targetStore], "readwrite");
  3616. // the transaction could abort because of a QuotaExceededError error
  3617. transaction.onabort = function (event) {
  3618. try {
  3619. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3620. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3621. this.hasReachedQuota = true;
  3622. }
  3623. }
  3624. catch (ex) { }
  3625. callback(fileData);
  3626. };
  3627. transaction.oncomplete = function (event) {
  3628. callback(fileData);
  3629. };
  3630. var newFile;
  3631. if (targetStore === "scenes") {
  3632. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3633. }
  3634. else {
  3635. newFile = { textureUrl: url, data: fileData };
  3636. }
  3637. try {
  3638. // Put the scene into the database
  3639. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3640. addRequest.onsuccess = function (event) {
  3641. };
  3642. addRequest.onerror = function (event) {
  3643. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3644. };
  3645. }
  3646. catch (ex) {
  3647. callback(fileData);
  3648. }
  3649. }
  3650. else {
  3651. callback(fileData);
  3652. }
  3653. }
  3654. else {
  3655. callback();
  3656. }
  3657. }, false);
  3658. xhr.addEventListener("error", function (event) {
  3659. BABYLON.Tools.Error("error on XHR request.");
  3660. callback();
  3661. }, false);
  3662. xhr.send();
  3663. }
  3664. else {
  3665. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3666. callback();
  3667. }
  3668. };
  3669. Database.IsUASupportingBlobStorage = true;
  3670. Database.IDBStorageEnabled = true;
  3671. Database.parseURL = function (url) {
  3672. var a = document.createElement('a');
  3673. a.href = url;
  3674. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3675. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3676. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3677. return absLocation;
  3678. };
  3679. Database.ReturnFullUrlLocation = function (url) {
  3680. if (url.indexOf("http:/") === -1) {
  3681. return (Database.parseURL(window.location.href) + url);
  3682. }
  3683. else {
  3684. return url;
  3685. }
  3686. };
  3687. return Database;
  3688. }());
  3689. BABYLON.Database = Database;
  3690. })(BABYLON || (BABYLON = {}));
  3691. var BABYLON;
  3692. (function (BABYLON) {
  3693. var Internals;
  3694. (function (Internals) {
  3695. /*
  3696. * Based on jsTGALoader - Javascript loader for TGA file
  3697. * By Vincent Thibault
  3698. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3699. */
  3700. var TGATools = (function () {
  3701. function TGATools() {
  3702. }
  3703. TGATools.GetTGAHeader = function (data) {
  3704. var offset = 0;
  3705. var header = {
  3706. id_length: data[offset++],
  3707. colormap_type: data[offset++],
  3708. image_type: data[offset++],
  3709. colormap_index: data[offset++] | data[offset++] << 8,
  3710. colormap_length: data[offset++] | data[offset++] << 8,
  3711. colormap_size: data[offset++],
  3712. origin: [
  3713. data[offset++] | data[offset++] << 8,
  3714. data[offset++] | data[offset++] << 8
  3715. ],
  3716. width: data[offset++] | data[offset++] << 8,
  3717. height: data[offset++] | data[offset++] << 8,
  3718. pixel_size: data[offset++],
  3719. flags: data[offset++]
  3720. };
  3721. return header;
  3722. };
  3723. TGATools.UploadContent = function (gl, data) {
  3724. // Not enough data to contain header ?
  3725. if (data.length < 19) {
  3726. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3727. return;
  3728. }
  3729. // Read Header
  3730. var offset = 18;
  3731. var header = TGATools.GetTGAHeader(data);
  3732. // Assume it's a valid Targa file.
  3733. if (header.id_length + offset > data.length) {
  3734. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3735. return;
  3736. }
  3737. // Skip not needed data
  3738. offset += header.id_length;
  3739. var use_rle = false;
  3740. var use_pal = false;
  3741. var use_rgb = false;
  3742. var use_grey = false;
  3743. // Get some informations.
  3744. switch (header.image_type) {
  3745. case TGATools._TYPE_RLE_INDEXED:
  3746. use_rle = true;
  3747. case TGATools._TYPE_INDEXED:
  3748. use_pal = true;
  3749. break;
  3750. case TGATools._TYPE_RLE_RGB:
  3751. use_rle = true;
  3752. case TGATools._TYPE_RGB:
  3753. use_rgb = true;
  3754. break;
  3755. case TGATools._TYPE_RLE_GREY:
  3756. use_rle = true;
  3757. case TGATools._TYPE_GREY:
  3758. use_grey = true;
  3759. break;
  3760. }
  3761. var pixel_data;
  3762. var numAlphaBits = header.flags & 0xf;
  3763. var pixel_size = header.pixel_size >> 3;
  3764. var pixel_total = header.width * header.height * pixel_size;
  3765. // Read palettes
  3766. var palettes;
  3767. if (use_pal) {
  3768. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3769. }
  3770. // Read LRE
  3771. if (use_rle) {
  3772. pixel_data = new Uint8Array(pixel_total);
  3773. var c, count, i;
  3774. var localOffset = 0;
  3775. var pixels = new Uint8Array(pixel_size);
  3776. while (offset < pixel_total && localOffset < pixel_total) {
  3777. c = data[offset++];
  3778. count = (c & 0x7f) + 1;
  3779. // RLE pixels
  3780. if (c & 0x80) {
  3781. // Bind pixel tmp array
  3782. for (i = 0; i < pixel_size; ++i) {
  3783. pixels[i] = data[offset++];
  3784. }
  3785. // Copy pixel array
  3786. for (i = 0; i < count; ++i) {
  3787. pixel_data.set(pixels, localOffset + i * pixel_size);
  3788. }
  3789. localOffset += pixel_size * count;
  3790. }
  3791. else {
  3792. count *= pixel_size;
  3793. for (i = 0; i < count; ++i) {
  3794. pixel_data[localOffset + i] = data[offset++];
  3795. }
  3796. localOffset += count;
  3797. }
  3798. }
  3799. }
  3800. else {
  3801. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3802. }
  3803. // Load to texture
  3804. var x_start, y_start, x_step, y_step, y_end, x_end;
  3805. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3806. default:
  3807. case TGATools._ORIGIN_UL:
  3808. x_start = 0;
  3809. x_step = 1;
  3810. x_end = header.width;
  3811. y_start = 0;
  3812. y_step = 1;
  3813. y_end = header.height;
  3814. break;
  3815. case TGATools._ORIGIN_BL:
  3816. x_start = 0;
  3817. x_step = 1;
  3818. x_end = header.width;
  3819. y_start = header.height - 1;
  3820. y_step = -1;
  3821. y_end = -1;
  3822. break;
  3823. case TGATools._ORIGIN_UR:
  3824. x_start = header.width - 1;
  3825. x_step = -1;
  3826. x_end = -1;
  3827. y_start = 0;
  3828. y_step = 1;
  3829. y_end = header.height;
  3830. break;
  3831. case TGATools._ORIGIN_BR:
  3832. x_start = header.width - 1;
  3833. x_step = -1;
  3834. x_end = -1;
  3835. y_start = header.height - 1;
  3836. y_step = -1;
  3837. y_end = -1;
  3838. break;
  3839. }
  3840. // Load the specify method
  3841. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3842. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3843. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3844. };
  3845. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3846. var image = pixel_data, colormap = palettes;
  3847. var width = header.width, height = header.height;
  3848. var color, i = 0, x, y;
  3849. var imageData = new Uint8Array(width * height * 4);
  3850. for (y = y_start; y !== y_end; y += y_step) {
  3851. for (x = x_start; x !== x_end; x += x_step, i++) {
  3852. color = image[i];
  3853. imageData[(x + width * y) * 4 + 3] = 255;
  3854. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3855. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3856. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3857. }
  3858. }
  3859. return imageData;
  3860. };
  3861. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3862. var image = pixel_data;
  3863. var width = header.width, height = header.height;
  3864. var color, i = 0, x, y;
  3865. var imageData = new Uint8Array(width * height * 4);
  3866. for (y = y_start; y !== y_end; y += y_step) {
  3867. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3868. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3869. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3870. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3871. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3872. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3873. }
  3874. }
  3875. return imageData;
  3876. };
  3877. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3878. var image = pixel_data;
  3879. var width = header.width, height = header.height;
  3880. var i = 0, x, y;
  3881. var imageData = new Uint8Array(width * height * 4);
  3882. for (y = y_start; y !== y_end; y += y_step) {
  3883. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3884. imageData[(x + width * y) * 4 + 3] = 255;
  3885. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3886. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3887. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3888. }
  3889. }
  3890. return imageData;
  3891. };
  3892. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3893. var image = pixel_data;
  3894. var width = header.width, height = header.height;
  3895. var i = 0, x, y;
  3896. var imageData = new Uint8Array(width * height * 4);
  3897. for (y = y_start; y !== y_end; y += y_step) {
  3898. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3899. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3900. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3901. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3902. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3903. }
  3904. }
  3905. return imageData;
  3906. };
  3907. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3908. var image = pixel_data;
  3909. var width = header.width, height = header.height;
  3910. var color, i = 0, x, y;
  3911. var imageData = new Uint8Array(width * height * 4);
  3912. for (y = y_start; y !== y_end; y += y_step) {
  3913. for (x = x_start; x !== x_end; x += x_step, i++) {
  3914. color = image[i];
  3915. imageData[(x + width * y) * 4 + 0] = color;
  3916. imageData[(x + width * y) * 4 + 1] = color;
  3917. imageData[(x + width * y) * 4 + 2] = color;
  3918. imageData[(x + width * y) * 4 + 3] = 255;
  3919. }
  3920. }
  3921. return imageData;
  3922. };
  3923. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3924. var image = pixel_data;
  3925. var width = header.width, height = header.height;
  3926. var i = 0, x, y;
  3927. var imageData = new Uint8Array(width * height * 4);
  3928. for (y = y_start; y !== y_end; y += y_step) {
  3929. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3930. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3931. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3932. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3933. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3934. }
  3935. }
  3936. return imageData;
  3937. };
  3938. TGATools._TYPE_NO_DATA = 0;
  3939. TGATools._TYPE_INDEXED = 1;
  3940. TGATools._TYPE_RGB = 2;
  3941. TGATools._TYPE_GREY = 3;
  3942. TGATools._TYPE_RLE_INDEXED = 9;
  3943. TGATools._TYPE_RLE_RGB = 10;
  3944. TGATools._TYPE_RLE_GREY = 11;
  3945. TGATools._ORIGIN_MASK = 0x30;
  3946. TGATools._ORIGIN_SHIFT = 0x04;
  3947. TGATools._ORIGIN_BL = 0x00;
  3948. TGATools._ORIGIN_BR = 0x01;
  3949. TGATools._ORIGIN_UL = 0x02;
  3950. TGATools._ORIGIN_UR = 0x03;
  3951. return TGATools;
  3952. }());
  3953. Internals.TGATools = TGATools;
  3954. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3955. })(BABYLON || (BABYLON = {}));
  3956. var BABYLON;
  3957. (function (BABYLON) {
  3958. var SmartArray = (function () {
  3959. function SmartArray(capacity) {
  3960. this.length = 0;
  3961. this._duplicateId = 0;
  3962. this.data = new Array(capacity);
  3963. this._id = SmartArray._GlobalId++;
  3964. }
  3965. SmartArray.prototype.push = function (value) {
  3966. this.data[this.length++] = value;
  3967. if (this.length > this.data.length) {
  3968. this.data.length *= 2;
  3969. }
  3970. if (!value.__smartArrayFlags) {
  3971. value.__smartArrayFlags = {};
  3972. }
  3973. value.__smartArrayFlags[this._id] = this._duplicateId;
  3974. };
  3975. SmartArray.prototype.pushNoDuplicate = function (value) {
  3976. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3977. return;
  3978. }
  3979. this.push(value);
  3980. };
  3981. SmartArray.prototype.sort = function (compareFn) {
  3982. this.data.sort(compareFn);
  3983. };
  3984. SmartArray.prototype.reset = function () {
  3985. this.length = 0;
  3986. this._duplicateId++;
  3987. };
  3988. SmartArray.prototype.concat = function (array) {
  3989. if (array.length === 0) {
  3990. return;
  3991. }
  3992. if (this.length + array.length > this.data.length) {
  3993. this.data.length = (this.length + array.length) * 2;
  3994. }
  3995. for (var index = 0; index < array.length; index++) {
  3996. this.data[this.length++] = (array.data || array)[index];
  3997. }
  3998. };
  3999. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4000. if (array.length === 0) {
  4001. return;
  4002. }
  4003. if (this.length + array.length > this.data.length) {
  4004. this.data.length = (this.length + array.length) * 2;
  4005. }
  4006. for (var index = 0; index < array.length; index++) {
  4007. var item = (array.data || array)[index];
  4008. this.pushNoDuplicate(item);
  4009. }
  4010. };
  4011. SmartArray.prototype.indexOf = function (value) {
  4012. var position = this.data.indexOf(value);
  4013. if (position >= this.length) {
  4014. return -1;
  4015. }
  4016. return position;
  4017. };
  4018. // Statics
  4019. SmartArray._GlobalId = 0;
  4020. return SmartArray;
  4021. }());
  4022. BABYLON.SmartArray = SmartArray;
  4023. })(BABYLON || (BABYLON = {}));
  4024. var BABYLON;
  4025. (function (BABYLON) {
  4026. var SmartCollection = (function () {
  4027. function SmartCollection(capacity) {
  4028. if (capacity === void 0) { capacity = 10; }
  4029. this.count = 0;
  4030. this._initialCapacity = capacity;
  4031. this.items = {};
  4032. this._keys = new Array(this._initialCapacity);
  4033. }
  4034. SmartCollection.prototype.add = function (key, item) {
  4035. if (this.items[key] != undefined) {
  4036. return -1;
  4037. }
  4038. this.items[key] = item;
  4039. //literal keys are always strings, but we keep source type of key in _keys array
  4040. this._keys[this.count++] = key;
  4041. if (this.count > this._keys.length) {
  4042. this._keys.length *= 2;
  4043. }
  4044. return this.count;
  4045. };
  4046. SmartCollection.prototype.remove = function (key) {
  4047. if (this.items[key] == undefined) {
  4048. return -1;
  4049. }
  4050. return this.removeItemOfIndex(this.indexOf(key));
  4051. };
  4052. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4053. if (index < this.count && index > -1) {
  4054. delete this.items[this._keys[index]];
  4055. //here, shifting by hand is better optimised than .splice
  4056. while (index < this.count) {
  4057. this._keys[index] = this._keys[index + 1];
  4058. index++;
  4059. }
  4060. }
  4061. else {
  4062. return -1;
  4063. }
  4064. return --this.count;
  4065. };
  4066. SmartCollection.prototype.indexOf = function (key) {
  4067. for (var i = 0; i !== this.count; i++) {
  4068. if (this._keys[i] === key) {
  4069. return i;
  4070. }
  4071. }
  4072. return -1;
  4073. };
  4074. SmartCollection.prototype.item = function (key) {
  4075. return this.items[key];
  4076. };
  4077. SmartCollection.prototype.getAllKeys = function () {
  4078. if (this.count > 0) {
  4079. var keys = new Array(this.count);
  4080. for (var i = 0; i < this.count; i++) {
  4081. keys[i] = this._keys[i];
  4082. }
  4083. return keys;
  4084. }
  4085. else {
  4086. return undefined;
  4087. }
  4088. };
  4089. SmartCollection.prototype.getKeyByIndex = function (index) {
  4090. if (index < this.count && index > -1) {
  4091. return this._keys[index];
  4092. }
  4093. else {
  4094. return undefined;
  4095. }
  4096. };
  4097. SmartCollection.prototype.getItemByIndex = function (index) {
  4098. if (index < this.count && index > -1) {
  4099. return this.items[this._keys[index]];
  4100. }
  4101. else {
  4102. return undefined;
  4103. }
  4104. };
  4105. SmartCollection.prototype.empty = function () {
  4106. if (this.count > 0) {
  4107. this.count = 0;
  4108. this.items = {};
  4109. this._keys = new Array(this._initialCapacity);
  4110. }
  4111. };
  4112. SmartCollection.prototype.forEach = function (block) {
  4113. var key;
  4114. for (key in this.items) {
  4115. if (this.items.hasOwnProperty(key)) {
  4116. block(this.items[key]);
  4117. }
  4118. }
  4119. };
  4120. return SmartCollection;
  4121. }());
  4122. BABYLON.SmartCollection = SmartCollection;
  4123. })(BABYLON || (BABYLON = {}));
  4124. var BABYLON;
  4125. (function (BABYLON) {
  4126. // Screenshots
  4127. var screenshotCanvas;
  4128. var cloneValue = function (source, destinationObject) {
  4129. if (!source)
  4130. return null;
  4131. if (source instanceof BABYLON.Mesh) {
  4132. return null;
  4133. }
  4134. if (source instanceof BABYLON.SubMesh) {
  4135. return source.clone(destinationObject);
  4136. }
  4137. else if (source.clone) {
  4138. return source.clone();
  4139. }
  4140. return null;
  4141. };
  4142. var Tools = (function () {
  4143. function Tools() {
  4144. }
  4145. Tools.Instantiate = function (className) {
  4146. var arr = className.split(".");
  4147. var fn = (window || this);
  4148. for (var i = 0, len = arr.length; i < len; i++) {
  4149. fn = fn[arr[i]];
  4150. }
  4151. if (typeof fn !== "function") {
  4152. return null;
  4153. }
  4154. return fn;
  4155. };
  4156. Tools.SetImmediate = function (action) {
  4157. if (window.setImmediate) {
  4158. window.setImmediate(action);
  4159. }
  4160. else {
  4161. setTimeout(action, 1);
  4162. }
  4163. };
  4164. Tools.IsExponentOfTwo = function (value) {
  4165. var count = 1;
  4166. do {
  4167. count *= 2;
  4168. } while (count < value);
  4169. return count === value;
  4170. };
  4171. Tools.GetExponentOfTwo = function (value, max) {
  4172. var count = 1;
  4173. do {
  4174. count *= 2;
  4175. } while (count < value);
  4176. if (count > max)
  4177. count = max;
  4178. return count;
  4179. };
  4180. Tools.GetFilename = function (path) {
  4181. var index = path.lastIndexOf("/");
  4182. if (index < 0)
  4183. return path;
  4184. return path.substring(index + 1);
  4185. };
  4186. Tools.GetDOMTextContent = function (element) {
  4187. var result = "";
  4188. var child = element.firstChild;
  4189. while (child) {
  4190. if (child.nodeType === 3) {
  4191. result += child.textContent;
  4192. }
  4193. child = child.nextSibling;
  4194. }
  4195. return result;
  4196. };
  4197. Tools.ToDegrees = function (angle) {
  4198. return angle * 180 / Math.PI;
  4199. };
  4200. Tools.ToRadians = function (angle) {
  4201. return angle * Math.PI / 180;
  4202. };
  4203. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4204. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4205. var output = "";
  4206. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4207. var i = 0;
  4208. var bytes = new Uint8Array(buffer);
  4209. while (i < bytes.length) {
  4210. chr1 = bytes[i++];
  4211. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4212. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4213. enc1 = chr1 >> 2;
  4214. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4215. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4216. enc4 = chr3 & 63;
  4217. if (isNaN(chr2)) {
  4218. enc3 = enc4 = 64;
  4219. }
  4220. else if (isNaN(chr3)) {
  4221. enc4 = 64;
  4222. }
  4223. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4224. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4225. }
  4226. return "data:image/png;base64," + output;
  4227. };
  4228. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4229. if (bias === void 0) { bias = null; }
  4230. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4231. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4232. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4233. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4234. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4235. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4236. }
  4237. if (bias) {
  4238. minimum.x -= minimum.x * bias.x + bias.y;
  4239. minimum.y -= minimum.y * bias.x + bias.y;
  4240. minimum.z -= minimum.z * bias.x + bias.y;
  4241. maximum.x += maximum.x * bias.x + bias.y;
  4242. maximum.y += maximum.y * bias.x + bias.y;
  4243. maximum.z += maximum.z * bias.x + bias.y;
  4244. }
  4245. return {
  4246. minimum: minimum,
  4247. maximum: maximum
  4248. };
  4249. };
  4250. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4251. if (bias === void 0) { bias = null; }
  4252. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4253. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4254. for (var index = start; index < start + count; index++) {
  4255. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4256. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4257. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4258. }
  4259. if (bias) {
  4260. minimum.x -= minimum.x * bias.x + bias.y;
  4261. minimum.y -= minimum.y * bias.x + bias.y;
  4262. minimum.z -= minimum.z * bias.x + bias.y;
  4263. maximum.x += maximum.x * bias.x + bias.y;
  4264. maximum.y += maximum.y * bias.x + bias.y;
  4265. maximum.z += maximum.z * bias.x + bias.y;
  4266. }
  4267. return {
  4268. minimum: minimum,
  4269. maximum: maximum
  4270. };
  4271. };
  4272. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4273. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4274. return undefined;
  4275. return Array.isArray(obj) ? obj : [obj];
  4276. };
  4277. // Misc.
  4278. Tools.GetPointerPrefix = function () {
  4279. var eventPrefix = "pointer";
  4280. // Check if pointer events are supported
  4281. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4282. eventPrefix = "mouse";
  4283. }
  4284. return eventPrefix;
  4285. };
  4286. Tools.QueueNewFrame = function (func) {
  4287. if (window.requestAnimationFrame)
  4288. window.requestAnimationFrame(func);
  4289. else if (window.msRequestAnimationFrame)
  4290. window.msRequestAnimationFrame(func);
  4291. else if (window.webkitRequestAnimationFrame)
  4292. window.webkitRequestAnimationFrame(func);
  4293. else if (window.mozRequestAnimationFrame)
  4294. window.mozRequestAnimationFrame(func);
  4295. else if (window.oRequestAnimationFrame)
  4296. window.oRequestAnimationFrame(func);
  4297. else {
  4298. window.setTimeout(func, 16);
  4299. }
  4300. };
  4301. Tools.RequestFullscreen = function (element) {
  4302. if (element.requestFullscreen)
  4303. element.requestFullscreen();
  4304. else if (element.msRequestFullscreen)
  4305. element.msRequestFullscreen();
  4306. else if (element.webkitRequestFullscreen)
  4307. element.webkitRequestFullscreen();
  4308. else if (element.mozRequestFullScreen)
  4309. element.mozRequestFullScreen();
  4310. };
  4311. Tools.ExitFullscreen = function () {
  4312. if (document.exitFullscreen) {
  4313. document.exitFullscreen();
  4314. }
  4315. else if (document.mozCancelFullScreen) {
  4316. document.mozCancelFullScreen();
  4317. }
  4318. else if (document.webkitCancelFullScreen) {
  4319. document.webkitCancelFullScreen();
  4320. }
  4321. else if (document.msCancelFullScreen) {
  4322. document.msCancelFullScreen();
  4323. }
  4324. };
  4325. // External files
  4326. Tools.CleanUrl = function (url) {
  4327. url = url.replace(/#/mg, "%23");
  4328. return url;
  4329. };
  4330. Tools.LoadImage = function (url, onload, onerror, database) {
  4331. if (url instanceof ArrayBuffer) {
  4332. url = Tools.EncodeArrayBufferTobase64(url);
  4333. }
  4334. url = Tools.CleanUrl(url);
  4335. var img = new Image();
  4336. if (url.substr(0, 5) !== "data:") {
  4337. if (Tools.CorsBehavior) {
  4338. switch (typeof (Tools.CorsBehavior)) {
  4339. case "function":
  4340. var result = Tools.CorsBehavior(url);
  4341. if (result) {
  4342. img.crossOrigin = result;
  4343. }
  4344. break;
  4345. case "string":
  4346. default:
  4347. img.crossOrigin = Tools.CorsBehavior;
  4348. break;
  4349. }
  4350. }
  4351. }
  4352. img.onload = function () {
  4353. onload(img);
  4354. };
  4355. img.onerror = function (err) {
  4356. Tools.Error("Error while trying to load texture: " + url);
  4357. if (Tools.UseFallbackTexture) {
  4358. 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";
  4359. onload(img);
  4360. }
  4361. else {
  4362. onerror();
  4363. }
  4364. };
  4365. var noIndexedDB = function () {
  4366. img.src = url;
  4367. };
  4368. var loadFromIndexedDB = function () {
  4369. database.loadImageFromDB(url, img);
  4370. };
  4371. //ANY database to do!
  4372. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4373. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4374. }
  4375. else {
  4376. if (url.indexOf("file:") === -1) {
  4377. noIndexedDB();
  4378. }
  4379. else {
  4380. try {
  4381. var textureName = url.substring(5);
  4382. var blobURL;
  4383. try {
  4384. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4385. }
  4386. catch (ex) {
  4387. // Chrome doesn't support oneTimeOnly parameter
  4388. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4389. }
  4390. img.src = blobURL;
  4391. }
  4392. catch (e) {
  4393. img.src = null;
  4394. }
  4395. }
  4396. }
  4397. return img;
  4398. };
  4399. //ANY
  4400. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4401. url = Tools.CleanUrl(url);
  4402. var noIndexedDB = function () {
  4403. var request = new XMLHttpRequest();
  4404. var loadUrl = Tools.BaseUrl + url;
  4405. request.open('GET', loadUrl, true);
  4406. if (useArrayBuffer) {
  4407. request.responseType = "arraybuffer";
  4408. }
  4409. request.onprogress = progressCallBack;
  4410. request.onreadystatechange = function () {
  4411. if (request.readyState === 4) {
  4412. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4413. callback(!useArrayBuffer ? request.responseText : request.response);
  4414. }
  4415. else {
  4416. if (onError) {
  4417. onError();
  4418. }
  4419. else {
  4420. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4421. }
  4422. }
  4423. }
  4424. };
  4425. request.send(null);
  4426. };
  4427. var loadFromIndexedDB = function () {
  4428. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4429. };
  4430. if (url.indexOf("file:") !== -1) {
  4431. var fileName = url.substring(5).toLowerCase();
  4432. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4433. }
  4434. else {
  4435. // Caching all files
  4436. if (database && database.enableSceneOffline) {
  4437. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4438. }
  4439. else {
  4440. noIndexedDB();
  4441. }
  4442. }
  4443. };
  4444. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4445. var reader = new FileReader();
  4446. reader.onload = function (e) {
  4447. //target doesn't have result from ts 1.3
  4448. callback(e.target['result']);
  4449. };
  4450. reader.onprogress = progressCallback;
  4451. reader.readAsDataURL(fileToLoad);
  4452. };
  4453. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4454. var reader = new FileReader();
  4455. reader.onerror = function (e) {
  4456. Tools.Log("Error while reading file: " + fileToLoad.name);
  4457. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4458. };
  4459. reader.onload = function (e) {
  4460. //target doesn't have result from ts 1.3
  4461. callback(e.target['result']);
  4462. };
  4463. reader.onprogress = progressCallBack;
  4464. if (!useArrayBuffer) {
  4465. // Asynchronous read
  4466. reader.readAsText(fileToLoad);
  4467. }
  4468. else {
  4469. reader.readAsArrayBuffer(fileToLoad);
  4470. }
  4471. };
  4472. //returns a downloadable url to a file content.
  4473. Tools.FileAsURL = function (content) {
  4474. var fileBlob = new Blob([content]);
  4475. var url = window.URL || window.webkitURL;
  4476. var link = url.createObjectURL(fileBlob);
  4477. return link;
  4478. };
  4479. // Misc.
  4480. Tools.Format = function (value, decimals) {
  4481. if (decimals === void 0) { decimals = 2; }
  4482. return value.toFixed(decimals);
  4483. };
  4484. Tools.CheckExtends = function (v, min, max) {
  4485. if (v.x < min.x)
  4486. min.x = v.x;
  4487. if (v.y < min.y)
  4488. min.y = v.y;
  4489. if (v.z < min.z)
  4490. min.z = v.z;
  4491. if (v.x > max.x)
  4492. max.x = v.x;
  4493. if (v.y > max.y)
  4494. max.y = v.y;
  4495. if (v.z > max.z)
  4496. max.z = v.z;
  4497. };
  4498. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4499. for (var prop in source) {
  4500. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4501. continue;
  4502. }
  4503. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4504. continue;
  4505. }
  4506. var sourceValue = source[prop];
  4507. var typeOfSourceValue = typeof sourceValue;
  4508. if (typeOfSourceValue === "function") {
  4509. continue;
  4510. }
  4511. if (typeOfSourceValue === "object") {
  4512. if (sourceValue instanceof Array) {
  4513. destination[prop] = [];
  4514. if (sourceValue.length > 0) {
  4515. if (typeof sourceValue[0] == "object") {
  4516. for (var index = 0; index < sourceValue.length; index++) {
  4517. var clonedValue = cloneValue(sourceValue[index], destination);
  4518. if (destination[prop].indexOf(clonedValue) === -1) {
  4519. destination[prop].push(clonedValue);
  4520. }
  4521. }
  4522. }
  4523. else {
  4524. destination[prop] = sourceValue.slice(0);
  4525. }
  4526. }
  4527. }
  4528. else {
  4529. destination[prop] = cloneValue(sourceValue, destination);
  4530. }
  4531. }
  4532. else {
  4533. destination[prop] = sourceValue;
  4534. }
  4535. }
  4536. };
  4537. Tools.IsEmpty = function (obj) {
  4538. for (var i in obj) {
  4539. return false;
  4540. }
  4541. return true;
  4542. };
  4543. Tools.RegisterTopRootEvents = function (events) {
  4544. for (var index = 0; index < events.length; index++) {
  4545. var event = events[index];
  4546. window.addEventListener(event.name, event.handler, false);
  4547. try {
  4548. if (window.parent) {
  4549. window.parent.addEventListener(event.name, event.handler, false);
  4550. }
  4551. }
  4552. catch (e) {
  4553. }
  4554. }
  4555. };
  4556. Tools.UnregisterTopRootEvents = function (events) {
  4557. for (var index = 0; index < events.length; index++) {
  4558. var event = events[index];
  4559. window.removeEventListener(event.name, event.handler);
  4560. try {
  4561. if (window.parent) {
  4562. window.parent.removeEventListener(event.name, event.handler);
  4563. }
  4564. }
  4565. catch (e) {
  4566. }
  4567. }
  4568. };
  4569. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4570. // Read the contents of the framebuffer
  4571. var numberOfChannelsByLine = width * 4;
  4572. var halfHeight = height / 2;
  4573. //Reading datas from WebGL
  4574. var data = engine.readPixels(0, 0, width, height);
  4575. //To flip image on Y axis.
  4576. for (var i = 0; i < halfHeight; i++) {
  4577. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4578. var currentCell = j + i * numberOfChannelsByLine;
  4579. var targetLine = height - i - 1;
  4580. var targetCell = j + targetLine * numberOfChannelsByLine;
  4581. var temp = data[currentCell];
  4582. data[currentCell] = data[targetCell];
  4583. data[targetCell] = temp;
  4584. }
  4585. }
  4586. // Create a 2D canvas to store the result
  4587. if (!screenshotCanvas) {
  4588. screenshotCanvas = document.createElement('canvas');
  4589. }
  4590. screenshotCanvas.width = width;
  4591. screenshotCanvas.height = height;
  4592. var context = screenshotCanvas.getContext('2d');
  4593. // Copy the pixels to a 2D canvas
  4594. var imageData = context.createImageData(width, height);
  4595. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4596. var castData = imageData.data;
  4597. castData.set(data);
  4598. context.putImageData(imageData, 0, 0);
  4599. var base64Image = screenshotCanvas.toDataURL();
  4600. if (successCallback) {
  4601. successCallback(base64Image);
  4602. }
  4603. else {
  4604. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4605. if (("download" in document.createElement("a"))) {
  4606. var a = window.document.createElement("a");
  4607. a.href = base64Image;
  4608. var date = new Date();
  4609. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4610. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4611. window.document.body.appendChild(a);
  4612. a.addEventListener("click", function () {
  4613. a.parentElement.removeChild(a);
  4614. });
  4615. a.click();
  4616. }
  4617. else {
  4618. var newWindow = window.open("");
  4619. var img = newWindow.document.createElement("img");
  4620. img.src = base64Image;
  4621. newWindow.document.body.appendChild(img);
  4622. }
  4623. }
  4624. };
  4625. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4626. var width;
  4627. var height;
  4628. //If a precision value is specified
  4629. if (size.precision) {
  4630. width = Math.round(engine.getRenderWidth() * size.precision);
  4631. height = Math.round(width / engine.getAspectRatio(camera));
  4632. size = { width: width, height: height };
  4633. }
  4634. else if (size.width && size.height) {
  4635. width = size.width;
  4636. height = size.height;
  4637. }
  4638. else if (size.width && !size.height) {
  4639. width = size.width;
  4640. height = Math.round(width / engine.getAspectRatio(camera));
  4641. size = { width: width, height: height };
  4642. }
  4643. else if (size.height && !size.width) {
  4644. height = size.height;
  4645. width = Math.round(height * engine.getAspectRatio(camera));
  4646. size = { width: width, height: height };
  4647. }
  4648. else if (!isNaN(size)) {
  4649. height = size;
  4650. width = size;
  4651. }
  4652. else {
  4653. Tools.Error("Invalid 'size' parameter !");
  4654. return;
  4655. }
  4656. var scene = camera.getScene();
  4657. var previousCamera = null;
  4658. if (scene.activeCamera !== camera) {
  4659. previousCamera = scene.activeCamera;
  4660. scene.activeCamera = camera;
  4661. }
  4662. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4663. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4664. texture.renderList = scene.meshes;
  4665. texture.onAfterRender = function () {
  4666. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4667. };
  4668. scene.incrementRenderId();
  4669. texture.render(true);
  4670. texture.dispose();
  4671. if (previousCamera) {
  4672. scene.activeCamera = previousCamera;
  4673. }
  4674. camera.getProjectionMatrix(true); // Force cache refresh;
  4675. };
  4676. // XHR response validator for local file scenario
  4677. Tools.ValidateXHRData = function (xhr, dataType) {
  4678. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4679. if (dataType === void 0) { dataType = 7; }
  4680. try {
  4681. if (dataType & 1) {
  4682. if (xhr.responseText && xhr.responseText.length > 0) {
  4683. return true;
  4684. }
  4685. else if (dataType === 1) {
  4686. return false;
  4687. }
  4688. }
  4689. if (dataType & 2) {
  4690. // Check header width and height since there is no "TGA" magic number
  4691. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4692. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4693. return true;
  4694. }
  4695. else if (dataType === 2) {
  4696. return false;
  4697. }
  4698. }
  4699. if (dataType & 4) {
  4700. // Check for the "DDS" magic number
  4701. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4702. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4703. return true;
  4704. }
  4705. else {
  4706. return false;
  4707. }
  4708. }
  4709. }
  4710. catch (e) {
  4711. }
  4712. return false;
  4713. };
  4714. Object.defineProperty(Tools, "NoneLogLevel", {
  4715. get: function () {
  4716. return Tools._NoneLogLevel;
  4717. },
  4718. enumerable: true,
  4719. configurable: true
  4720. });
  4721. Object.defineProperty(Tools, "MessageLogLevel", {
  4722. get: function () {
  4723. return Tools._MessageLogLevel;
  4724. },
  4725. enumerable: true,
  4726. configurable: true
  4727. });
  4728. Object.defineProperty(Tools, "WarningLogLevel", {
  4729. get: function () {
  4730. return Tools._WarningLogLevel;
  4731. },
  4732. enumerable: true,
  4733. configurable: true
  4734. });
  4735. Object.defineProperty(Tools, "ErrorLogLevel", {
  4736. get: function () {
  4737. return Tools._ErrorLogLevel;
  4738. },
  4739. enumerable: true,
  4740. configurable: true
  4741. });
  4742. Object.defineProperty(Tools, "AllLogLevel", {
  4743. get: function () {
  4744. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. Tools._AddLogEntry = function (entry) {
  4750. Tools._LogCache = entry + Tools._LogCache;
  4751. if (Tools.OnNewCacheEntry) {
  4752. Tools.OnNewCacheEntry(entry);
  4753. }
  4754. };
  4755. Tools._FormatMessage = function (message) {
  4756. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4757. var date = new Date();
  4758. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4759. };
  4760. Tools._LogDisabled = function (message) {
  4761. // nothing to do
  4762. };
  4763. Tools._LogEnabled = function (message) {
  4764. var formattedMessage = Tools._FormatMessage(message);
  4765. console.log("BJS - " + formattedMessage);
  4766. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4767. Tools._AddLogEntry(entry);
  4768. };
  4769. Tools._WarnDisabled = function (message) {
  4770. // nothing to do
  4771. };
  4772. Tools._WarnEnabled = function (message) {
  4773. var formattedMessage = Tools._FormatMessage(message);
  4774. console.warn("BJS - " + formattedMessage);
  4775. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4776. Tools._AddLogEntry(entry);
  4777. };
  4778. Tools._ErrorDisabled = function (message) {
  4779. // nothing to do
  4780. };
  4781. Tools._ErrorEnabled = function (message) {
  4782. Tools.errorsCount++;
  4783. var formattedMessage = Tools._FormatMessage(message);
  4784. console.error("BJS - " + formattedMessage);
  4785. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4786. Tools._AddLogEntry(entry);
  4787. };
  4788. Object.defineProperty(Tools, "LogCache", {
  4789. get: function () {
  4790. return Tools._LogCache;
  4791. },
  4792. enumerable: true,
  4793. configurable: true
  4794. });
  4795. Tools.ClearLogCache = function () {
  4796. Tools._LogCache = "";
  4797. Tools.errorsCount = 0;
  4798. };
  4799. Object.defineProperty(Tools, "LogLevels", {
  4800. set: function (level) {
  4801. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4802. Tools.Log = Tools._LogEnabled;
  4803. }
  4804. else {
  4805. Tools.Log = Tools._LogDisabled;
  4806. }
  4807. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4808. Tools.Warn = Tools._WarnEnabled;
  4809. }
  4810. else {
  4811. Tools.Warn = Tools._WarnDisabled;
  4812. }
  4813. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4814. Tools.Error = Tools._ErrorEnabled;
  4815. }
  4816. else {
  4817. Tools.Error = Tools._ErrorDisabled;
  4818. }
  4819. },
  4820. enumerable: true,
  4821. configurable: true
  4822. });
  4823. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4824. get: function () {
  4825. return Tools._PerformanceNoneLogLevel;
  4826. },
  4827. enumerable: true,
  4828. configurable: true
  4829. });
  4830. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4831. get: function () {
  4832. return Tools._PerformanceUserMarkLogLevel;
  4833. },
  4834. enumerable: true,
  4835. configurable: true
  4836. });
  4837. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4838. get: function () {
  4839. return Tools._PerformanceConsoleLogLevel;
  4840. },
  4841. enumerable: true,
  4842. configurable: true
  4843. });
  4844. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4845. set: function (level) {
  4846. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4847. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4848. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4849. return;
  4850. }
  4851. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4852. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4853. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4854. return;
  4855. }
  4856. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4857. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4858. },
  4859. enumerable: true,
  4860. configurable: true
  4861. });
  4862. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4863. };
  4864. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4865. };
  4866. Tools._StartUserMark = function (counterName, condition) {
  4867. if (condition === void 0) { condition = true; }
  4868. if (!condition || !Tools._performance.mark) {
  4869. return;
  4870. }
  4871. Tools._performance.mark(counterName + "-Begin");
  4872. };
  4873. Tools._EndUserMark = function (counterName, condition) {
  4874. if (condition === void 0) { condition = true; }
  4875. if (!condition || !Tools._performance.mark) {
  4876. return;
  4877. }
  4878. Tools._performance.mark(counterName + "-End");
  4879. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4880. };
  4881. Tools._StartPerformanceConsole = function (counterName, condition) {
  4882. if (condition === void 0) { condition = true; }
  4883. if (!condition) {
  4884. return;
  4885. }
  4886. Tools._StartUserMark(counterName, condition);
  4887. if (console.time) {
  4888. console.time(counterName);
  4889. }
  4890. };
  4891. Tools._EndPerformanceConsole = function (counterName, condition) {
  4892. if (condition === void 0) { condition = true; }
  4893. if (!condition) {
  4894. return;
  4895. }
  4896. Tools._EndUserMark(counterName, condition);
  4897. if (console.time) {
  4898. console.timeEnd(counterName);
  4899. }
  4900. };
  4901. Object.defineProperty(Tools, "Now", {
  4902. get: function () {
  4903. if (window.performance && window.performance.now) {
  4904. return window.performance.now();
  4905. }
  4906. return new Date().getTime();
  4907. },
  4908. enumerable: true,
  4909. configurable: true
  4910. });
  4911. Tools.BaseUrl = "";
  4912. Tools.CorsBehavior = "anonymous";
  4913. Tools.UseFallbackTexture = true;
  4914. // Logs
  4915. Tools._NoneLogLevel = 0;
  4916. Tools._MessageLogLevel = 1;
  4917. Tools._WarningLogLevel = 2;
  4918. Tools._ErrorLogLevel = 4;
  4919. Tools._LogCache = "";
  4920. Tools.errorsCount = 0;
  4921. Tools.Log = Tools._LogEnabled;
  4922. Tools.Warn = Tools._WarnEnabled;
  4923. Tools.Error = Tools._ErrorEnabled;
  4924. // Performances
  4925. Tools._PerformanceNoneLogLevel = 0;
  4926. Tools._PerformanceUserMarkLogLevel = 1;
  4927. Tools._PerformanceConsoleLogLevel = 2;
  4928. Tools._performance = window.performance;
  4929. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4930. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4931. return Tools;
  4932. }());
  4933. BABYLON.Tools = Tools;
  4934. /**
  4935. * An implementation of a loop for asynchronous functions.
  4936. */
  4937. var AsyncLoop = (function () {
  4938. /**
  4939. * Constroctor.
  4940. * @param iterations the number of iterations.
  4941. * @param _fn the function to run each iteration
  4942. * @param _successCallback the callback that will be called upon succesful execution
  4943. * @param offset starting offset.
  4944. */
  4945. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4946. if (offset === void 0) { offset = 0; }
  4947. this.iterations = iterations;
  4948. this._fn = _fn;
  4949. this._successCallback = _successCallback;
  4950. this.index = offset - 1;
  4951. this._done = false;
  4952. }
  4953. /**
  4954. * Execute the next iteration. Must be called after the last iteration was finished.
  4955. */
  4956. AsyncLoop.prototype.executeNext = function () {
  4957. if (!this._done) {
  4958. if (this.index + 1 < this.iterations) {
  4959. ++this.index;
  4960. this._fn(this);
  4961. }
  4962. else {
  4963. this.breakLoop();
  4964. }
  4965. }
  4966. };
  4967. /**
  4968. * Break the loop and run the success callback.
  4969. */
  4970. AsyncLoop.prototype.breakLoop = function () {
  4971. this._done = true;
  4972. this._successCallback();
  4973. };
  4974. /**
  4975. * Helper function
  4976. */
  4977. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4978. if (offset === void 0) { offset = 0; }
  4979. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4980. loop.executeNext();
  4981. return loop;
  4982. };
  4983. /**
  4984. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4985. * @param iterations total number of iterations
  4986. * @param syncedIterations number of synchronous iterations in each async iteration.
  4987. * @param fn the function to call each iteration.
  4988. * @param callback a success call back that will be called when iterating stops.
  4989. * @param breakFunction a break condition (optional)
  4990. * @param timeout timeout settings for the setTimeout function. default - 0.
  4991. * @constructor
  4992. */
  4993. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4994. if (timeout === void 0) { timeout = 0; }
  4995. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4996. if (breakFunction && breakFunction())
  4997. loop.breakLoop();
  4998. else {
  4999. setTimeout(function () {
  5000. for (var i = 0; i < syncedIterations; ++i) {
  5001. var iteration = (loop.index * syncedIterations) + i;
  5002. if (iteration >= iterations)
  5003. break;
  5004. fn(iteration);
  5005. if (breakFunction && breakFunction()) {
  5006. loop.breakLoop();
  5007. break;
  5008. }
  5009. }
  5010. loop.executeNext();
  5011. }, timeout);
  5012. }
  5013. }, callback);
  5014. };
  5015. return AsyncLoop;
  5016. }());
  5017. BABYLON.AsyncLoop = AsyncLoop;
  5018. })(BABYLON || (BABYLON = {}));
  5019. var BABYLON;
  5020. (function (BABYLON) {
  5021. var Internals;
  5022. (function (Internals) {
  5023. var _AlphaState = (function () {
  5024. function _AlphaState() {
  5025. this._isAlphaBlendDirty = false;
  5026. this._isBlendFunctionParametersDirty = false;
  5027. this._alphaBlend = false;
  5028. this._blendFunctionParameters = new Array(4);
  5029. }
  5030. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5031. get: function () {
  5032. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5033. },
  5034. enumerable: true,
  5035. configurable: true
  5036. });
  5037. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5038. get: function () {
  5039. return this._alphaBlend;
  5040. },
  5041. set: function (value) {
  5042. if (this._alphaBlend === value) {
  5043. return;
  5044. }
  5045. this._alphaBlend = value;
  5046. this._isAlphaBlendDirty = true;
  5047. },
  5048. enumerable: true,
  5049. configurable: true
  5050. });
  5051. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5052. if (this._blendFunctionParameters[0] === value0 &&
  5053. this._blendFunctionParameters[1] === value1 &&
  5054. this._blendFunctionParameters[2] === value2 &&
  5055. this._blendFunctionParameters[3] === value3) {
  5056. return;
  5057. }
  5058. this._blendFunctionParameters[0] = value0;
  5059. this._blendFunctionParameters[1] = value1;
  5060. this._blendFunctionParameters[2] = value2;
  5061. this._blendFunctionParameters[3] = value3;
  5062. this._isBlendFunctionParametersDirty = true;
  5063. };
  5064. _AlphaState.prototype.reset = function () {
  5065. this._alphaBlend = false;
  5066. this._blendFunctionParameters[0] = null;
  5067. this._blendFunctionParameters[1] = null;
  5068. this._blendFunctionParameters[2] = null;
  5069. this._blendFunctionParameters[3] = null;
  5070. this._isAlphaBlendDirty = true;
  5071. this._isBlendFunctionParametersDirty = false;
  5072. };
  5073. _AlphaState.prototype.apply = function (gl) {
  5074. if (!this.isDirty) {
  5075. return;
  5076. }
  5077. // Alpha blend
  5078. if (this._isAlphaBlendDirty) {
  5079. if (this._alphaBlend) {
  5080. gl.enable(gl.BLEND);
  5081. }
  5082. else {
  5083. gl.disable(gl.BLEND);
  5084. }
  5085. this._isAlphaBlendDirty = false;
  5086. }
  5087. // Alpha function
  5088. if (this._isBlendFunctionParametersDirty) {
  5089. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5090. this._isBlendFunctionParametersDirty = false;
  5091. }
  5092. };
  5093. return _AlphaState;
  5094. }());
  5095. Internals._AlphaState = _AlphaState;
  5096. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5097. })(BABYLON || (BABYLON = {}));
  5098. var BABYLON;
  5099. (function (BABYLON) {
  5100. var Internals;
  5101. (function (Internals) {
  5102. var _DepthCullingState = (function () {
  5103. function _DepthCullingState() {
  5104. this._isDepthTestDirty = false;
  5105. this._isDepthMaskDirty = false;
  5106. this._isDepthFuncDirty = false;
  5107. this._isCullFaceDirty = false;
  5108. this._isCullDirty = false;
  5109. this._isZOffsetDirty = false;
  5110. }
  5111. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5112. get: function () {
  5113. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5114. },
  5115. enumerable: true,
  5116. configurable: true
  5117. });
  5118. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5119. get: function () {
  5120. return this._zOffset;
  5121. },
  5122. set: function (value) {
  5123. if (this._zOffset === value) {
  5124. return;
  5125. }
  5126. this._zOffset = value;
  5127. this._isZOffsetDirty = true;
  5128. },
  5129. enumerable: true,
  5130. configurable: true
  5131. });
  5132. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5133. get: function () {
  5134. return this._cullFace;
  5135. },
  5136. set: function (value) {
  5137. if (this._cullFace === value) {
  5138. return;
  5139. }
  5140. this._cullFace = value;
  5141. this._isCullFaceDirty = true;
  5142. },
  5143. enumerable: true,
  5144. configurable: true
  5145. });
  5146. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5147. get: function () {
  5148. return this._cull;
  5149. },
  5150. set: function (value) {
  5151. if (this._cull === value) {
  5152. return;
  5153. }
  5154. this._cull = value;
  5155. this._isCullDirty = true;
  5156. },
  5157. enumerable: true,
  5158. configurable: true
  5159. });
  5160. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5161. get: function () {
  5162. return this._depthFunc;
  5163. },
  5164. set: function (value) {
  5165. if (this._depthFunc === value) {
  5166. return;
  5167. }
  5168. this._depthFunc = value;
  5169. this._isDepthFuncDirty = true;
  5170. },
  5171. enumerable: true,
  5172. configurable: true
  5173. });
  5174. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5175. get: function () {
  5176. return this._depthMask;
  5177. },
  5178. set: function (value) {
  5179. if (this._depthMask === value) {
  5180. return;
  5181. }
  5182. this._depthMask = value;
  5183. this._isDepthMaskDirty = true;
  5184. },
  5185. enumerable: true,
  5186. configurable: true
  5187. });
  5188. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5189. get: function () {
  5190. return this._depthTest;
  5191. },
  5192. set: function (value) {
  5193. if (this._depthTest === value) {
  5194. return;
  5195. }
  5196. this._depthTest = value;
  5197. this._isDepthTestDirty = true;
  5198. },
  5199. enumerable: true,
  5200. configurable: true
  5201. });
  5202. _DepthCullingState.prototype.reset = function () {
  5203. this._depthMask = true;
  5204. this._depthTest = true;
  5205. this._depthFunc = null;
  5206. this._cull = null;
  5207. this._cullFace = null;
  5208. this._zOffset = 0;
  5209. this._isDepthTestDirty = true;
  5210. this._isDepthMaskDirty = true;
  5211. this._isDepthFuncDirty = false;
  5212. this._isCullFaceDirty = false;
  5213. this._isCullDirty = false;
  5214. this._isZOffsetDirty = false;
  5215. };
  5216. _DepthCullingState.prototype.apply = function (gl) {
  5217. if (!this.isDirty) {
  5218. return;
  5219. }
  5220. // Cull
  5221. if (this._isCullDirty) {
  5222. if (this.cull) {
  5223. gl.enable(gl.CULL_FACE);
  5224. }
  5225. else {
  5226. gl.disable(gl.CULL_FACE);
  5227. }
  5228. this._isCullDirty = false;
  5229. }
  5230. // Cull face
  5231. if (this._isCullFaceDirty) {
  5232. gl.cullFace(this.cullFace);
  5233. this._isCullFaceDirty = false;
  5234. }
  5235. // Depth mask
  5236. if (this._isDepthMaskDirty) {
  5237. gl.depthMask(this.depthMask);
  5238. this._isDepthMaskDirty = false;
  5239. }
  5240. // Depth test
  5241. if (this._isDepthTestDirty) {
  5242. if (this.depthTest) {
  5243. gl.enable(gl.DEPTH_TEST);
  5244. }
  5245. else {
  5246. gl.disable(gl.DEPTH_TEST);
  5247. }
  5248. this._isDepthTestDirty = false;
  5249. }
  5250. // Depth func
  5251. if (this._isDepthFuncDirty) {
  5252. gl.depthFunc(this.depthFunc);
  5253. this._isDepthFuncDirty = false;
  5254. }
  5255. // zOffset
  5256. if (this._isZOffsetDirty) {
  5257. if (this.zOffset) {
  5258. gl.enable(gl.POLYGON_OFFSET_FILL);
  5259. gl.polygonOffset(this.zOffset, 0);
  5260. }
  5261. else {
  5262. gl.disable(gl.POLYGON_OFFSET_FILL);
  5263. }
  5264. this._isZOffsetDirty = false;
  5265. }
  5266. };
  5267. return _DepthCullingState;
  5268. }());
  5269. Internals._DepthCullingState = _DepthCullingState;
  5270. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5271. })(BABYLON || (BABYLON = {}));
  5272. var BABYLON;
  5273. (function (BABYLON) {
  5274. var compileShader = function (gl, source, type, defines) {
  5275. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5276. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5277. gl.compileShader(shader);
  5278. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5279. throw new Error(gl.getShaderInfoLog(shader));
  5280. }
  5281. return shader;
  5282. };
  5283. var getWebGLTextureType = function (gl, type) {
  5284. var textureType = gl.UNSIGNED_BYTE;
  5285. if (type === Engine.TEXTURETYPE_FLOAT)
  5286. textureType = gl.FLOAT;
  5287. return textureType;
  5288. };
  5289. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5290. var magFilter = gl.NEAREST;
  5291. var minFilter = gl.NEAREST;
  5292. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5293. magFilter = gl.LINEAR;
  5294. if (generateMipMaps) {
  5295. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5296. }
  5297. else {
  5298. minFilter = gl.LINEAR;
  5299. }
  5300. }
  5301. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5302. magFilter = gl.LINEAR;
  5303. if (generateMipMaps) {
  5304. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5305. }
  5306. else {
  5307. minFilter = gl.LINEAR;
  5308. }
  5309. }
  5310. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5311. magFilter = gl.NEAREST;
  5312. if (generateMipMaps) {
  5313. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5314. }
  5315. else {
  5316. minFilter = gl.NEAREST;
  5317. }
  5318. }
  5319. return {
  5320. min: minFilter,
  5321. mag: magFilter
  5322. };
  5323. };
  5324. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5325. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5326. var engine = scene.getEngine();
  5327. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5328. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5329. gl.bindTexture(gl.TEXTURE_2D, texture);
  5330. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5331. texture._baseWidth = width;
  5332. texture._baseHeight = height;
  5333. texture._width = potWidth;
  5334. texture._height = potHeight;
  5335. texture.isReady = true;
  5336. processFunction(potWidth, potHeight);
  5337. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5340. if (!noMipmap && !isCompressed) {
  5341. gl.generateMipmap(gl.TEXTURE_2D);
  5342. }
  5343. gl.bindTexture(gl.TEXTURE_2D, null);
  5344. engine.resetTextureCache();
  5345. scene._removePendingData(texture);
  5346. if (onLoad) {
  5347. onLoad();
  5348. }
  5349. };
  5350. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5351. var img;
  5352. var onload = function () {
  5353. loadedImages[index] = img;
  5354. loadedImages._internalCount++;
  5355. scene._removePendingData(img);
  5356. if (loadedImages._internalCount === 6) {
  5357. onfinish(loadedImages);
  5358. }
  5359. };
  5360. var onerror = function () {
  5361. scene._removePendingData(img);
  5362. };
  5363. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5364. scene._addPendingData(img);
  5365. };
  5366. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5367. var loadedImages = [];
  5368. loadedImages._internalCount = 0;
  5369. for (var index = 0; index < 6; index++) {
  5370. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5371. }
  5372. };
  5373. var EngineCapabilities = (function () {
  5374. function EngineCapabilities() {
  5375. }
  5376. return EngineCapabilities;
  5377. }());
  5378. BABYLON.EngineCapabilities = EngineCapabilities;
  5379. /**
  5380. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5381. */
  5382. var Engine = (function () {
  5383. /**
  5384. * @constructor
  5385. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5386. * @param {boolean} [antialias] - enable antialias
  5387. * @param options - further options to be sent to the getContext function
  5388. */
  5389. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5390. var _this = this;
  5391. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5392. // Public members
  5393. this.isFullscreen = false;
  5394. this.isPointerLock = false;
  5395. this.cullBackFaces = true;
  5396. this.renderEvenInBackground = true;
  5397. // To enable/disable IDB support and avoid XHR on .manifest
  5398. this.enableOfflineSupport = true;
  5399. this.scenes = new Array();
  5400. this._windowIsBackground = false;
  5401. this._webGLVersion = "1.0";
  5402. this._drawCalls = 0;
  5403. this._renderingQueueLaunched = false;
  5404. this._activeRenderLoops = [];
  5405. // FPS
  5406. this.fpsRange = 60;
  5407. this.previousFramesDuration = [];
  5408. this.fps = 60;
  5409. this.deltaTime = 0;
  5410. // States
  5411. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5412. this._alphaState = new BABYLON.Internals._AlphaState();
  5413. this._alphaMode = Engine.ALPHA_DISABLE;
  5414. // Cache
  5415. this._loadedTexturesCache = new Array();
  5416. this._maxTextureChannels = 16;
  5417. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5418. this._compiledEffects = {};
  5419. this._uintIndicesCurrentlySet = false;
  5420. this._renderingCanvas = canvas;
  5421. options = options || {};
  5422. options.antialias = antialias;
  5423. if (options.preserveDrawingBuffer === undefined) {
  5424. options.preserveDrawingBuffer = false;
  5425. }
  5426. // GL
  5427. //try {
  5428. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5429. // if (this._gl) {
  5430. // this._webGLVersion = "2.0";
  5431. // }
  5432. //} catch (e) {
  5433. // // Do nothing
  5434. //}
  5435. if (!this._gl) {
  5436. try {
  5437. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5438. }
  5439. catch (e) {
  5440. throw new Error("WebGL not supported");
  5441. }
  5442. }
  5443. if (!this._gl) {
  5444. throw new Error("WebGL not supported");
  5445. }
  5446. this._onBlur = function () {
  5447. _this._windowIsBackground = true;
  5448. };
  5449. this._onFocus = function () {
  5450. _this._windowIsBackground = false;
  5451. };
  5452. window.addEventListener("blur", this._onBlur);
  5453. window.addEventListener("focus", this._onFocus);
  5454. // Viewport
  5455. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5456. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5457. this.resize();
  5458. // Caps
  5459. this._caps = new EngineCapabilities();
  5460. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5461. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5462. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5463. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5464. // Infos
  5465. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5466. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5467. if (rendererInfo != null) {
  5468. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5469. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5470. }
  5471. if (!this._glVendor) {
  5472. this._glVendor = "Unknown vendor";
  5473. }
  5474. if (!this._glRenderer) {
  5475. this._glRenderer = "Unknown renderer";
  5476. }
  5477. // Extensions
  5478. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5479. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5480. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5481. 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');
  5482. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5483. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5484. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5485. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5486. this._caps.highPrecisionShaderSupported = true;
  5487. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5488. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5489. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5490. if (this._gl.getShaderPrecisionFormat) {
  5491. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5492. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5493. }
  5494. // Depth buffer
  5495. this.setDepthBuffer(true);
  5496. this.setDepthFunctionToLessOrEqual();
  5497. this.setDepthWrite(true);
  5498. // Fullscreen
  5499. this._onFullscreenChange = function () {
  5500. if (document.fullscreen !== undefined) {
  5501. _this.isFullscreen = document.fullscreen;
  5502. }
  5503. else if (document.mozFullScreen !== undefined) {
  5504. _this.isFullscreen = document.mozFullScreen;
  5505. }
  5506. else if (document.webkitIsFullScreen !== undefined) {
  5507. _this.isFullscreen = document.webkitIsFullScreen;
  5508. }
  5509. else if (document.msIsFullScreen !== undefined) {
  5510. _this.isFullscreen = document.msIsFullScreen;
  5511. }
  5512. // Pointer lock
  5513. if (_this.isFullscreen && _this._pointerLockRequested) {
  5514. canvas.requestPointerLock = canvas.requestPointerLock ||
  5515. canvas.msRequestPointerLock ||
  5516. canvas.mozRequestPointerLock ||
  5517. canvas.webkitRequestPointerLock;
  5518. if (canvas.requestPointerLock) {
  5519. canvas.requestPointerLock();
  5520. }
  5521. }
  5522. };
  5523. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5524. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5525. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5526. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5527. // Pointer lock
  5528. this._onPointerLockChange = function () {
  5529. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5530. document.webkitPointerLockElement === canvas ||
  5531. document.msPointerLockElement === canvas ||
  5532. document.pointerLockElement === canvas);
  5533. };
  5534. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5535. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5536. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5537. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5538. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5539. Engine.audioEngine = new BABYLON.AudioEngine();
  5540. }
  5541. //default loading screen
  5542. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5543. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5544. }
  5545. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5546. get: function () {
  5547. return Engine._ALPHA_DISABLE;
  5548. },
  5549. enumerable: true,
  5550. configurable: true
  5551. });
  5552. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5553. get: function () {
  5554. return Engine._ALPHA_ONEONE;
  5555. },
  5556. enumerable: true,
  5557. configurable: true
  5558. });
  5559. Object.defineProperty(Engine, "ALPHA_ADD", {
  5560. get: function () {
  5561. return Engine._ALPHA_ADD;
  5562. },
  5563. enumerable: true,
  5564. configurable: true
  5565. });
  5566. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5567. get: function () {
  5568. return Engine._ALPHA_COMBINE;
  5569. },
  5570. enumerable: true,
  5571. configurable: true
  5572. });
  5573. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5574. get: function () {
  5575. return Engine._ALPHA_SUBTRACT;
  5576. },
  5577. enumerable: true,
  5578. configurable: true
  5579. });
  5580. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5581. get: function () {
  5582. return Engine._ALPHA_MULTIPLY;
  5583. },
  5584. enumerable: true,
  5585. configurable: true
  5586. });
  5587. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5588. get: function () {
  5589. return Engine._ALPHA_MAXIMIZED;
  5590. },
  5591. enumerable: true,
  5592. configurable: true
  5593. });
  5594. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5595. get: function () {
  5596. return Engine._DELAYLOADSTATE_NONE;
  5597. },
  5598. enumerable: true,
  5599. configurable: true
  5600. });
  5601. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5602. get: function () {
  5603. return Engine._DELAYLOADSTATE_LOADED;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5609. get: function () {
  5610. return Engine._DELAYLOADSTATE_LOADING;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5616. get: function () {
  5617. return Engine._DELAYLOADSTATE_NOTLOADED;
  5618. },
  5619. enumerable: true,
  5620. configurable: true
  5621. });
  5622. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5623. get: function () {
  5624. return Engine._TEXTUREFORMAT_ALPHA;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5630. get: function () {
  5631. return Engine._TEXTUREFORMAT_LUMINANCE;
  5632. },
  5633. enumerable: true,
  5634. configurable: true
  5635. });
  5636. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5637. get: function () {
  5638. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5644. get: function () {
  5645. return Engine._TEXTUREFORMAT_RGB;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5651. get: function () {
  5652. return Engine._TEXTUREFORMAT_RGBA;
  5653. },
  5654. enumerable: true,
  5655. configurable: true
  5656. });
  5657. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5658. get: function () {
  5659. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5665. get: function () {
  5666. return Engine._TEXTURETYPE_FLOAT;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(Engine, "Version", {
  5672. get: function () {
  5673. return "2.4.0-alpha";
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5679. get: function () {
  5680. return this._webGLVersion;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Engine.prototype._prepareWorkingCanvas = function () {
  5686. if (this._workingCanvas) {
  5687. return;
  5688. }
  5689. this._workingCanvas = document.createElement("canvas");
  5690. this._workingContext = this._workingCanvas.getContext("2d");
  5691. };
  5692. Engine.prototype.resetTextureCache = function () {
  5693. for (var index = 0; index < this._maxTextureChannels; index++) {
  5694. this._activeTexturesCache[index] = null;
  5695. }
  5696. };
  5697. Engine.prototype.getGlInfo = function () {
  5698. return {
  5699. vendor: this._glVendor,
  5700. renderer: this._glRenderer,
  5701. version: this._glVersion
  5702. };
  5703. };
  5704. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5705. if (useScreen === void 0) { useScreen = false; }
  5706. var viewport = camera.viewport;
  5707. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5708. };
  5709. Engine.prototype.getRenderWidth = function (useScreen) {
  5710. if (useScreen === void 0) { useScreen = false; }
  5711. if (!useScreen && this._currentRenderTarget) {
  5712. return this._currentRenderTarget._width;
  5713. }
  5714. return this._renderingCanvas.width;
  5715. };
  5716. Engine.prototype.getRenderHeight = function (useScreen) {
  5717. if (useScreen === void 0) { useScreen = false; }
  5718. if (!useScreen && this._currentRenderTarget) {
  5719. return this._currentRenderTarget._height;
  5720. }
  5721. return this._renderingCanvas.height;
  5722. };
  5723. Engine.prototype.getRenderingCanvas = function () {
  5724. return this._renderingCanvas;
  5725. };
  5726. Engine.prototype.getRenderingCanvasClientRect = function () {
  5727. return this._renderingCanvas.getBoundingClientRect();
  5728. };
  5729. Engine.prototype.setHardwareScalingLevel = function (level) {
  5730. this._hardwareScalingLevel = level;
  5731. this.resize();
  5732. };
  5733. Engine.prototype.getHardwareScalingLevel = function () {
  5734. return this._hardwareScalingLevel;
  5735. };
  5736. Engine.prototype.getLoadedTexturesCache = function () {
  5737. return this._loadedTexturesCache;
  5738. };
  5739. Engine.prototype.getCaps = function () {
  5740. return this._caps;
  5741. };
  5742. Object.defineProperty(Engine.prototype, "drawCalls", {
  5743. get: function () {
  5744. return this._drawCalls;
  5745. },
  5746. enumerable: true,
  5747. configurable: true
  5748. });
  5749. // Methods
  5750. Engine.prototype.resetDrawCalls = function () {
  5751. this._drawCalls = 0;
  5752. };
  5753. Engine.prototype.setDepthFunctionToGreater = function () {
  5754. this._depthCullingState.depthFunc = this._gl.GREATER;
  5755. };
  5756. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5757. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5758. };
  5759. Engine.prototype.setDepthFunctionToLess = function () {
  5760. this._depthCullingState.depthFunc = this._gl.LESS;
  5761. };
  5762. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5763. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5764. };
  5765. /**
  5766. * stop executing a render loop function and remove it from the execution array
  5767. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5768. */
  5769. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5770. if (!renderFunction) {
  5771. this._activeRenderLoops = [];
  5772. return;
  5773. }
  5774. var index = this._activeRenderLoops.indexOf(renderFunction);
  5775. if (index >= 0) {
  5776. this._activeRenderLoops.splice(index, 1);
  5777. }
  5778. };
  5779. Engine.prototype._renderLoop = function () {
  5780. var shouldRender = true;
  5781. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5782. shouldRender = false;
  5783. }
  5784. if (shouldRender) {
  5785. // Start new frame
  5786. this.beginFrame();
  5787. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5788. var renderFunction = this._activeRenderLoops[index];
  5789. renderFunction();
  5790. }
  5791. // Present
  5792. this.endFrame();
  5793. }
  5794. if (this._activeRenderLoops.length > 0) {
  5795. // Register new frame
  5796. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5797. }
  5798. else {
  5799. this._renderingQueueLaunched = false;
  5800. }
  5801. };
  5802. /**
  5803. * Register and execute a render loop. The engine can have more than one render function.
  5804. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5805. * @example
  5806. * engine.runRenderLoop(function () {
  5807. * scene.render()
  5808. * })
  5809. */
  5810. Engine.prototype.runRenderLoop = function (renderFunction) {
  5811. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5812. return;
  5813. }
  5814. this._activeRenderLoops.push(renderFunction);
  5815. if (!this._renderingQueueLaunched) {
  5816. this._renderingQueueLaunched = true;
  5817. this._bindedRenderFunction = this._renderLoop.bind(this);
  5818. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5819. }
  5820. };
  5821. /**
  5822. * Toggle full screen mode.
  5823. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5824. */
  5825. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5826. if (this.isFullscreen) {
  5827. BABYLON.Tools.ExitFullscreen();
  5828. }
  5829. else {
  5830. this._pointerLockRequested = requestPointerLock;
  5831. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5832. }
  5833. };
  5834. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5835. this.applyStates();
  5836. if (backBuffer) {
  5837. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5838. }
  5839. if (depthStencil && this._depthCullingState.depthMask) {
  5840. this._gl.clearDepth(1.0);
  5841. }
  5842. var mode = 0;
  5843. if (backBuffer) {
  5844. mode |= this._gl.COLOR_BUFFER_BIT;
  5845. }
  5846. if (depthStencil && this._depthCullingState.depthMask) {
  5847. mode |= this._gl.DEPTH_BUFFER_BIT;
  5848. }
  5849. this._gl.clear(mode);
  5850. };
  5851. /**
  5852. * Set the WebGL's viewport
  5853. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5854. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5855. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5856. */
  5857. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5858. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5859. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5860. var x = viewport.x || 0;
  5861. var y = viewport.y || 0;
  5862. this._cachedViewport = viewport;
  5863. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5864. };
  5865. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5866. this._cachedViewport = null;
  5867. this._gl.viewport(x, y, width, height);
  5868. };
  5869. Engine.prototype.beginFrame = function () {
  5870. this._measureFps();
  5871. };
  5872. Engine.prototype.endFrame = function () {
  5873. //this.flushFramebuffer();
  5874. };
  5875. /**
  5876. * resize the view according to the canvas' size.
  5877. * @example
  5878. * window.addEventListener("resize", function () {
  5879. * engine.resize();
  5880. * });
  5881. */
  5882. Engine.prototype.resize = function () {
  5883. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5884. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5885. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5886. for (var index = 0; index < this.scenes.length; index++) {
  5887. var scene = this.scenes[index];
  5888. if (scene.debugLayer.isVisible()) {
  5889. scene.debugLayer._syncPositions();
  5890. }
  5891. }
  5892. };
  5893. /**
  5894. * force a specific size of the canvas
  5895. * @param {number} width - the new canvas' width
  5896. * @param {number} height - the new canvas' height
  5897. */
  5898. Engine.prototype.setSize = function (width, height) {
  5899. this._renderingCanvas.width = width;
  5900. this._renderingCanvas.height = height;
  5901. for (var index = 0; index < this.scenes.length; index++) {
  5902. var scene = this.scenes[index];
  5903. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5904. var cam = scene.cameras[camIndex];
  5905. cam._currentRenderId = 0;
  5906. }
  5907. }
  5908. };
  5909. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5910. this._currentRenderTarget = texture;
  5911. var gl = this._gl;
  5912. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5913. if (texture.isCube) {
  5914. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5915. }
  5916. else {
  5917. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5918. }
  5919. this._gl.viewport(0, 0, texture._width, texture._height);
  5920. this.wipeCaches();
  5921. };
  5922. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5923. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5924. this._currentRenderTarget = null;
  5925. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5926. var gl = this._gl;
  5927. gl.bindTexture(gl.TEXTURE_2D, texture);
  5928. gl.generateMipmap(gl.TEXTURE_2D);
  5929. gl.bindTexture(gl.TEXTURE_2D, null);
  5930. }
  5931. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5932. };
  5933. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5934. if (texture.generateMipMaps) {
  5935. var gl = this._gl;
  5936. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5937. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5938. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5939. }
  5940. };
  5941. Engine.prototype.flushFramebuffer = function () {
  5942. this._gl.flush();
  5943. };
  5944. Engine.prototype.restoreDefaultFramebuffer = function () {
  5945. this._currentRenderTarget = null;
  5946. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5947. this.setViewport(this._cachedViewport);
  5948. this.wipeCaches();
  5949. };
  5950. // VBOs
  5951. Engine.prototype._resetVertexBufferBinding = function () {
  5952. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5953. this._cachedVertexBuffers = null;
  5954. };
  5955. Engine.prototype.createVertexBuffer = function (vertices) {
  5956. var vbo = this._gl.createBuffer();
  5957. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5958. if (vertices instanceof Float32Array) {
  5959. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5960. }
  5961. else {
  5962. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5963. }
  5964. this._resetVertexBufferBinding();
  5965. vbo.references = 1;
  5966. return vbo;
  5967. };
  5968. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5969. var vbo = this._gl.createBuffer();
  5970. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5971. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5972. this._resetVertexBufferBinding();
  5973. vbo.references = 1;
  5974. return vbo;
  5975. };
  5976. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5977. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5978. if (offset === undefined) {
  5979. offset = 0;
  5980. }
  5981. if (vertices instanceof Float32Array) {
  5982. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5983. }
  5984. else {
  5985. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5986. }
  5987. this._resetVertexBufferBinding();
  5988. };
  5989. Engine.prototype._resetIndexBufferBinding = function () {
  5990. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5991. this._cachedIndexBuffer = null;
  5992. };
  5993. Engine.prototype.createIndexBuffer = function (indices) {
  5994. var vbo = this._gl.createBuffer();
  5995. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5996. // Check for 32 bits indices
  5997. var arrayBuffer;
  5998. var need32Bits = false;
  5999. if (this._caps.uintIndices) {
  6000. for (var index = 0; index < indices.length; index++) {
  6001. if (indices[index] > 65535) {
  6002. need32Bits = true;
  6003. break;
  6004. }
  6005. }
  6006. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6007. }
  6008. else {
  6009. arrayBuffer = new Uint16Array(indices);
  6010. }
  6011. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6012. this._resetIndexBufferBinding();
  6013. vbo.references = 1;
  6014. vbo.is32Bits = need32Bits;
  6015. return vbo;
  6016. };
  6017. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6018. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6019. this._cachedVertexBuffers = vertexBuffer;
  6020. this._cachedEffectForVertexBuffers = effect;
  6021. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6022. var offset = 0;
  6023. for (var index = 0; index < vertexDeclaration.length; index++) {
  6024. var order = effect.getAttributeLocation(index);
  6025. if (order >= 0) {
  6026. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6027. }
  6028. offset += vertexDeclaration[index] * 4;
  6029. }
  6030. }
  6031. if (this._cachedIndexBuffer !== indexBuffer) {
  6032. this._cachedIndexBuffer = indexBuffer;
  6033. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6034. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6035. }
  6036. };
  6037. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6038. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6039. this._cachedVertexBuffers = vertexBuffers;
  6040. this._cachedEffectForVertexBuffers = effect;
  6041. var attributes = effect.getAttributesNames();
  6042. for (var index = 0; index < attributes.length; index++) {
  6043. var order = effect.getAttributeLocation(index);
  6044. if (order >= 0) {
  6045. var vertexBuffer = vertexBuffers[attributes[index]];
  6046. if (!vertexBuffer) {
  6047. continue;
  6048. }
  6049. var stride = vertexBuffer.getStrideSize();
  6050. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6051. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6052. }
  6053. }
  6054. }
  6055. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6056. this._cachedIndexBuffer = indexBuffer;
  6057. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6058. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6059. }
  6060. };
  6061. Engine.prototype._releaseBuffer = function (buffer) {
  6062. buffer.references--;
  6063. if (buffer.references === 0) {
  6064. this._gl.deleteBuffer(buffer);
  6065. return true;
  6066. }
  6067. return false;
  6068. };
  6069. Engine.prototype.createInstancesBuffer = function (capacity) {
  6070. var buffer = this._gl.createBuffer();
  6071. buffer.capacity = capacity;
  6072. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6073. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6074. return buffer;
  6075. };
  6076. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6077. this._gl.deleteBuffer(buffer);
  6078. };
  6079. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6080. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6081. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6082. for (var index = 0; index < 4; index++) {
  6083. var offsetLocation = offsetLocations[index];
  6084. this._gl.enableVertexAttribArray(offsetLocation);
  6085. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6086. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6087. }
  6088. };
  6089. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6090. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6091. for (var index = 0; index < 4; index++) {
  6092. var offsetLocation = offsetLocations[index];
  6093. this._gl.disableVertexAttribArray(offsetLocation);
  6094. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6095. }
  6096. };
  6097. Engine.prototype.applyStates = function () {
  6098. this._depthCullingState.apply(this._gl);
  6099. this._alphaState.apply(this._gl);
  6100. };
  6101. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6102. // Apply states
  6103. this.applyStates();
  6104. this._drawCalls++;
  6105. // Render
  6106. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6107. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6108. if (instancesCount) {
  6109. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6110. return;
  6111. }
  6112. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6113. };
  6114. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6115. // Apply states
  6116. this.applyStates();
  6117. this._drawCalls++;
  6118. if (instancesCount) {
  6119. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6120. return;
  6121. }
  6122. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6123. };
  6124. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6125. // Apply states
  6126. this.applyStates();
  6127. this._drawCalls++;
  6128. if (instancesCount) {
  6129. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6130. return;
  6131. }
  6132. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6133. };
  6134. // Shaders
  6135. Engine.prototype._releaseEffect = function (effect) {
  6136. if (this._compiledEffects[effect._key]) {
  6137. delete this._compiledEffects[effect._key];
  6138. if (effect.getProgram()) {
  6139. this._gl.deleteProgram(effect.getProgram());
  6140. }
  6141. }
  6142. };
  6143. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6144. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6145. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6146. var name = vertex + "+" + fragment + "@" + defines;
  6147. if (this._compiledEffects[name]) {
  6148. return this._compiledEffects[name];
  6149. }
  6150. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6151. effect._key = name;
  6152. this._compiledEffects[name] = effect;
  6153. return effect;
  6154. };
  6155. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6156. if (uniformsNames === void 0) { uniformsNames = []; }
  6157. if (samplers === void 0) { samplers = []; }
  6158. if (defines === void 0) { defines = ""; }
  6159. return this.createEffect({
  6160. vertex: "particles",
  6161. fragmentElement: fragmentName
  6162. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6163. };
  6164. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6165. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6166. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6167. var shaderProgram = this._gl.createProgram();
  6168. this._gl.attachShader(shaderProgram, vertexShader);
  6169. this._gl.attachShader(shaderProgram, fragmentShader);
  6170. this._gl.linkProgram(shaderProgram);
  6171. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6172. if (!linked) {
  6173. var error = this._gl.getProgramInfoLog(shaderProgram);
  6174. if (error) {
  6175. throw new Error(error);
  6176. }
  6177. }
  6178. this._gl.deleteShader(vertexShader);
  6179. this._gl.deleteShader(fragmentShader);
  6180. return shaderProgram;
  6181. };
  6182. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6183. var results = [];
  6184. for (var index = 0; index < uniformsNames.length; index++) {
  6185. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6186. }
  6187. return results;
  6188. };
  6189. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6190. var results = [];
  6191. for (var index = 0; index < attributesNames.length; index++) {
  6192. try {
  6193. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6194. }
  6195. catch (e) {
  6196. results.push(-1);
  6197. }
  6198. }
  6199. return results;
  6200. };
  6201. Engine.prototype.enableEffect = function (effect) {
  6202. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6203. if (effect && effect.onBind) {
  6204. effect.onBind(effect);
  6205. }
  6206. return;
  6207. }
  6208. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6209. // Use program
  6210. this._gl.useProgram(effect.getProgram());
  6211. for (var i in this._vertexAttribArrays) {
  6212. //make sure this is a number)
  6213. var iAsNumber = +i;
  6214. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6215. continue;
  6216. }
  6217. this._vertexAttribArrays[iAsNumber] = false;
  6218. this._gl.disableVertexAttribArray(iAsNumber);
  6219. }
  6220. var attributesCount = effect.getAttributesCount();
  6221. for (var index = 0; index < attributesCount; index++) {
  6222. // Attributes
  6223. var order = effect.getAttributeLocation(index);
  6224. if (order >= 0) {
  6225. this._vertexAttribArrays[order] = true;
  6226. this._gl.enableVertexAttribArray(order);
  6227. }
  6228. }
  6229. this._currentEffect = effect;
  6230. if (effect.onBind) {
  6231. effect.onBind(effect);
  6232. }
  6233. };
  6234. Engine.prototype.setArray = function (uniform, array) {
  6235. if (!uniform)
  6236. return;
  6237. this._gl.uniform1fv(uniform, array);
  6238. };
  6239. Engine.prototype.setArray2 = function (uniform, array) {
  6240. if (!uniform || array.length % 2 !== 0)
  6241. return;
  6242. this._gl.uniform2fv(uniform, array);
  6243. };
  6244. Engine.prototype.setArray3 = function (uniform, array) {
  6245. if (!uniform || array.length % 3 !== 0)
  6246. return;
  6247. this._gl.uniform3fv(uniform, array);
  6248. };
  6249. Engine.prototype.setArray4 = function (uniform, array) {
  6250. if (!uniform || array.length % 4 !== 0)
  6251. return;
  6252. this._gl.uniform4fv(uniform, array);
  6253. };
  6254. Engine.prototype.setMatrices = function (uniform, matrices) {
  6255. if (!uniform)
  6256. return;
  6257. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6258. };
  6259. Engine.prototype.setMatrix = function (uniform, matrix) {
  6260. if (!uniform)
  6261. return;
  6262. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6263. };
  6264. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6265. if (!uniform)
  6266. return;
  6267. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6268. };
  6269. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6270. if (!uniform)
  6271. return;
  6272. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6273. };
  6274. Engine.prototype.setFloat = function (uniform, value) {
  6275. if (!uniform)
  6276. return;
  6277. this._gl.uniform1f(uniform, value);
  6278. };
  6279. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6280. if (!uniform)
  6281. return;
  6282. this._gl.uniform2f(uniform, x, y);
  6283. };
  6284. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6285. if (!uniform)
  6286. return;
  6287. this._gl.uniform3f(uniform, x, y, z);
  6288. };
  6289. Engine.prototype.setBool = function (uniform, bool) {
  6290. if (!uniform)
  6291. return;
  6292. this._gl.uniform1i(uniform, bool);
  6293. };
  6294. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6295. if (!uniform)
  6296. return;
  6297. this._gl.uniform4f(uniform, x, y, z, w);
  6298. };
  6299. Engine.prototype.setColor3 = function (uniform, color3) {
  6300. if (!uniform)
  6301. return;
  6302. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6303. };
  6304. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6305. if (!uniform)
  6306. return;
  6307. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6308. };
  6309. // States
  6310. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6311. if (zOffset === void 0) { zOffset = 0; }
  6312. if (reverseSide === void 0) { reverseSide = false; }
  6313. // Culling
  6314. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6315. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6316. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6317. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6318. if (culling) {
  6319. this._depthCullingState.cullFace = cullFace;
  6320. this._depthCullingState.cull = true;
  6321. }
  6322. else {
  6323. this._depthCullingState.cull = false;
  6324. }
  6325. }
  6326. // Z offset
  6327. this._depthCullingState.zOffset = zOffset;
  6328. };
  6329. Engine.prototype.setDepthBuffer = function (enable) {
  6330. this._depthCullingState.depthTest = enable;
  6331. };
  6332. Engine.prototype.getDepthWrite = function () {
  6333. return this._depthCullingState.depthMask;
  6334. };
  6335. Engine.prototype.setDepthWrite = function (enable) {
  6336. this._depthCullingState.depthMask = enable;
  6337. };
  6338. Engine.prototype.setColorWrite = function (enable) {
  6339. this._gl.colorMask(enable, enable, enable, enable);
  6340. };
  6341. Engine.prototype.setAlphaMode = function (mode) {
  6342. if (this._alphaMode === mode) {
  6343. return;
  6344. }
  6345. switch (mode) {
  6346. case Engine.ALPHA_DISABLE:
  6347. this.setDepthWrite(true);
  6348. this._alphaState.alphaBlend = false;
  6349. break;
  6350. case Engine.ALPHA_COMBINE:
  6351. this.setDepthWrite(false);
  6352. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6353. this._alphaState.alphaBlend = true;
  6354. break;
  6355. case Engine.ALPHA_ONEONE:
  6356. this.setDepthWrite(false);
  6357. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6358. this._alphaState.alphaBlend = true;
  6359. break;
  6360. case Engine.ALPHA_ADD:
  6361. this.setDepthWrite(false);
  6362. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6363. this._alphaState.alphaBlend = true;
  6364. break;
  6365. case Engine.ALPHA_SUBTRACT:
  6366. this.setDepthWrite(false);
  6367. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6368. this._alphaState.alphaBlend = true;
  6369. break;
  6370. case Engine.ALPHA_MULTIPLY:
  6371. this.setDepthWrite(false);
  6372. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6373. this._alphaState.alphaBlend = true;
  6374. break;
  6375. case Engine.ALPHA_MAXIMIZED:
  6376. this.setDepthWrite(false);
  6377. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6378. this._alphaState.alphaBlend = true;
  6379. break;
  6380. }
  6381. this._alphaMode = mode;
  6382. };
  6383. Engine.prototype.getAlphaMode = function () {
  6384. return this._alphaMode;
  6385. };
  6386. Engine.prototype.setAlphaTesting = function (enable) {
  6387. this._alphaTest = enable;
  6388. };
  6389. Engine.prototype.getAlphaTesting = function () {
  6390. return this._alphaTest;
  6391. };
  6392. // Textures
  6393. Engine.prototype.wipeCaches = function () {
  6394. this.resetTextureCache();
  6395. this._currentEffect = null;
  6396. this._depthCullingState.reset();
  6397. this._alphaState.reset();
  6398. this._cachedVertexBuffers = null;
  6399. this._cachedIndexBuffer = null;
  6400. this._cachedEffectForVertexBuffers = null;
  6401. };
  6402. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6403. var gl = this._gl;
  6404. gl.bindTexture(gl.TEXTURE_2D, texture);
  6405. var magFilter = gl.NEAREST;
  6406. var minFilter = gl.NEAREST;
  6407. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6408. magFilter = gl.LINEAR;
  6409. minFilter = gl.LINEAR;
  6410. }
  6411. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6412. magFilter = gl.LINEAR;
  6413. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6414. }
  6415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6417. gl.bindTexture(gl.TEXTURE_2D, null);
  6418. texture.samplingMode = samplingMode;
  6419. };
  6420. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6421. var _this = this;
  6422. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6423. if (onLoad === void 0) { onLoad = null; }
  6424. if (onError === void 0) { onError = null; }
  6425. if (buffer === void 0) { buffer = null; }
  6426. var texture = this._gl.createTexture();
  6427. var extension;
  6428. var fromData = false;
  6429. if (url.substr(0, 5) === "data:") {
  6430. fromData = true;
  6431. }
  6432. if (!fromData)
  6433. extension = url.substr(url.length - 4, 4).toLowerCase();
  6434. else {
  6435. var oldUrl = url;
  6436. fromData = oldUrl.split(':');
  6437. url = oldUrl;
  6438. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6439. }
  6440. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6441. var isTGA = (extension === ".tga");
  6442. scene._addPendingData(texture);
  6443. texture.url = url;
  6444. texture.noMipmap = noMipmap;
  6445. texture.references = 1;
  6446. texture.samplingMode = samplingMode;
  6447. this._loadedTexturesCache.push(texture);
  6448. var onerror = function () {
  6449. scene._removePendingData(texture);
  6450. if (onError) {
  6451. onError();
  6452. }
  6453. };
  6454. var callback;
  6455. if (isTGA) {
  6456. callback = function (arrayBuffer) {
  6457. var data = new Uint8Array(arrayBuffer);
  6458. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6459. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6460. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6461. }, onLoad, samplingMode);
  6462. };
  6463. if (!(fromData instanceof Array))
  6464. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6465. callback(arrayBuffer);
  6466. }, onerror, scene.database, true);
  6467. else
  6468. callback(buffer);
  6469. }
  6470. else if (isDDS) {
  6471. callback = function (data) {
  6472. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6473. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6474. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6475. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6476. }, onLoad, samplingMode);
  6477. };
  6478. if (!(fromData instanceof Array))
  6479. BABYLON.Tools.LoadFile(url, function (data) {
  6480. callback(data);
  6481. }, onerror, scene.database, true);
  6482. else
  6483. callback(buffer);
  6484. }
  6485. else {
  6486. var onload = function (img) {
  6487. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6488. var isPot = (img.width === potWidth && img.height === potHeight);
  6489. if (!isPot) {
  6490. _this._prepareWorkingCanvas();
  6491. _this._workingCanvas.width = potWidth;
  6492. _this._workingCanvas.height = potHeight;
  6493. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6494. _this._workingContext.imageSmoothingEnabled = false;
  6495. _this._workingContext.mozImageSmoothingEnabled = false;
  6496. _this._workingContext.oImageSmoothingEnabled = false;
  6497. _this._workingContext.webkitImageSmoothingEnabled = false;
  6498. _this._workingContext.msImageSmoothingEnabled = false;
  6499. }
  6500. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6501. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6502. _this._workingContext.imageSmoothingEnabled = true;
  6503. _this._workingContext.mozImageSmoothingEnabled = true;
  6504. _this._workingContext.oImageSmoothingEnabled = true;
  6505. _this._workingContext.webkitImageSmoothingEnabled = true;
  6506. _this._workingContext.msImageSmoothingEnabled = true;
  6507. }
  6508. }
  6509. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6510. }, onLoad, samplingMode);
  6511. };
  6512. if (!(fromData instanceof Array))
  6513. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6514. else
  6515. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6516. }
  6517. return texture;
  6518. };
  6519. Engine.prototype._getInternalFormat = function (format) {
  6520. var internalFormat = this._gl.RGBA;
  6521. switch (format) {
  6522. case Engine.TEXTUREFORMAT_ALPHA:
  6523. internalFormat = this._gl.ALPHA;
  6524. break;
  6525. case Engine.TEXTUREFORMAT_LUMINANCE:
  6526. internalFormat = this._gl.LUMINANCE;
  6527. break;
  6528. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6529. internalFormat = this._gl.LUMINANCE_ALPHA;
  6530. break;
  6531. case Engine.TEXTUREFORMAT_RGB:
  6532. internalFormat = this._gl.RGB;
  6533. break;
  6534. case Engine.TEXTUREFORMAT_RGBA:
  6535. internalFormat = this._gl.RGBA;
  6536. break;
  6537. }
  6538. return internalFormat;
  6539. };
  6540. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6541. if (compression === void 0) { compression = null; }
  6542. var internalFormat = this._getInternalFormat(format);
  6543. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6544. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6545. if (compression) {
  6546. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6547. }
  6548. else {
  6549. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6550. }
  6551. if (texture.generateMipMaps) {
  6552. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6553. }
  6554. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6555. this.resetTextureCache();
  6556. texture.isReady = true;
  6557. };
  6558. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6559. if (compression === void 0) { compression = null; }
  6560. var texture = this._gl.createTexture();
  6561. texture._baseWidth = width;
  6562. texture._baseHeight = height;
  6563. texture._width = width;
  6564. texture._height = height;
  6565. texture.references = 1;
  6566. this.updateRawTexture(texture, data, format, invertY, compression);
  6567. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6568. // Filters
  6569. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6570. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6571. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6572. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6573. texture.samplingMode = samplingMode;
  6574. this._loadedTexturesCache.push(texture);
  6575. return texture;
  6576. };
  6577. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6578. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6579. var texture = this._gl.createTexture();
  6580. texture._baseWidth = width;
  6581. texture._baseHeight = height;
  6582. if (forceExponantOfTwo) {
  6583. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6584. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6585. }
  6586. this.resetTextureCache();
  6587. texture._width = width;
  6588. texture._height = height;
  6589. texture.isReady = false;
  6590. texture.generateMipMaps = generateMipMaps;
  6591. texture.references = 1;
  6592. texture.samplingMode = samplingMode;
  6593. this.updateTextureSamplingMode(samplingMode, texture);
  6594. this._loadedTexturesCache.push(texture);
  6595. return texture;
  6596. };
  6597. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6598. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6599. if (texture.isCube) {
  6600. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6601. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6602. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6603. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6604. }
  6605. else {
  6606. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6607. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6609. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6610. }
  6611. };
  6612. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6613. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6614. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6615. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6616. if (texture.generateMipMaps) {
  6617. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6618. }
  6619. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6620. this.resetTextureCache();
  6621. texture.isReady = true;
  6622. };
  6623. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6624. if (texture._isDisabled) {
  6625. return;
  6626. }
  6627. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6628. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6629. try {
  6630. // Testing video texture support
  6631. if (this._videoTextureSupported === undefined) {
  6632. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6633. if (this._gl.getError() !== 0) {
  6634. this._videoTextureSupported = false;
  6635. }
  6636. else {
  6637. this._videoTextureSupported = true;
  6638. }
  6639. }
  6640. // Copy video through the current working canvas if video texture is not supported
  6641. if (!this._videoTextureSupported) {
  6642. if (!texture._workingCanvas) {
  6643. texture._workingCanvas = document.createElement("canvas");
  6644. texture._workingContext = texture._workingCanvas.getContext("2d");
  6645. texture._workingCanvas.width = texture._width;
  6646. texture._workingCanvas.height = texture._height;
  6647. }
  6648. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6649. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6650. }
  6651. else {
  6652. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6653. }
  6654. if (texture.generateMipMaps) {
  6655. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6656. }
  6657. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6658. this.resetTextureCache();
  6659. texture.isReady = true;
  6660. }
  6661. catch (ex) {
  6662. // Something unexpected
  6663. // Let's disable the texture
  6664. texture._isDisabled = true;
  6665. }
  6666. };
  6667. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6668. // old version had a "generateMipMaps" arg instead of options.
  6669. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6670. // in the same way, generateDepthBuffer is defaulted to true
  6671. var generateMipMaps = false;
  6672. var generateDepthBuffer = true;
  6673. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6674. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6675. if (options !== undefined) {
  6676. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6677. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6678. type = options.type === undefined ? type : options.type;
  6679. if (options.samplingMode !== undefined) {
  6680. samplingMode = options.samplingMode;
  6681. }
  6682. if (type === Engine.TEXTURETYPE_FLOAT) {
  6683. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6684. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6685. }
  6686. }
  6687. var gl = this._gl;
  6688. var texture = gl.createTexture();
  6689. gl.bindTexture(gl.TEXTURE_2D, texture);
  6690. var width = size.width || size;
  6691. var height = size.height || size;
  6692. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6693. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6694. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6695. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6696. }
  6697. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6698. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6699. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6700. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6701. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6702. var depthBuffer;
  6703. // Create the depth buffer
  6704. if (generateDepthBuffer) {
  6705. depthBuffer = gl.createRenderbuffer();
  6706. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6707. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6708. }
  6709. // Create the framebuffer
  6710. var framebuffer = gl.createFramebuffer();
  6711. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6712. if (generateDepthBuffer) {
  6713. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6714. }
  6715. if (generateMipMaps) {
  6716. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6717. }
  6718. // Unbind
  6719. gl.bindTexture(gl.TEXTURE_2D, null);
  6720. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6721. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6722. texture._framebuffer = framebuffer;
  6723. if (generateDepthBuffer) {
  6724. texture._depthBuffer = depthBuffer;
  6725. }
  6726. texture._width = width;
  6727. texture._height = height;
  6728. texture.isReady = true;
  6729. texture.generateMipMaps = generateMipMaps;
  6730. texture.references = 1;
  6731. texture.samplingMode = samplingMode;
  6732. this.resetTextureCache();
  6733. this._loadedTexturesCache.push(texture);
  6734. return texture;
  6735. };
  6736. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6737. var gl = this._gl;
  6738. var texture = gl.createTexture();
  6739. var generateMipMaps = true;
  6740. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6741. if (options !== undefined) {
  6742. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6743. if (options.samplingMode !== undefined) {
  6744. samplingMode = options.samplingMode;
  6745. }
  6746. }
  6747. texture.isCube = true;
  6748. texture.references = 1;
  6749. texture.generateMipMaps = generateMipMaps;
  6750. texture.references = 1;
  6751. texture.samplingMode = samplingMode;
  6752. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6753. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6754. for (var face = 0; face < 6; face++) {
  6755. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6756. }
  6757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6761. // Create the depth buffer
  6762. var depthBuffer = gl.createRenderbuffer();
  6763. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6764. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6765. // Create the framebuffer
  6766. var framebuffer = gl.createFramebuffer();
  6767. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6768. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6769. // Mipmaps
  6770. if (texture.generateMipMaps) {
  6771. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6772. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6773. }
  6774. // Unbind
  6775. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6776. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6777. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6778. texture._framebuffer = framebuffer;
  6779. texture._depthBuffer = depthBuffer;
  6780. this.resetTextureCache();
  6781. texture._width = size;
  6782. texture._height = size;
  6783. texture.isReady = true;
  6784. return texture;
  6785. };
  6786. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6787. var _this = this;
  6788. var gl = this._gl;
  6789. var texture = gl.createTexture();
  6790. texture.isCube = true;
  6791. texture.url = rootUrl;
  6792. texture.references = 1;
  6793. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6794. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6795. if (isDDS) {
  6796. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6797. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6798. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6799. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6800. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6801. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6802. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6803. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6804. }
  6805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6809. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6810. _this.resetTextureCache();
  6811. texture._width = info.width;
  6812. texture._height = info.height;
  6813. texture.isReady = true;
  6814. }, null, null, true);
  6815. }
  6816. else {
  6817. cascadeLoad(rootUrl, scene, function (imgs) {
  6818. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6819. var height = width;
  6820. _this._prepareWorkingCanvas();
  6821. _this._workingCanvas.width = width;
  6822. _this._workingCanvas.height = height;
  6823. var faces = [
  6824. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6825. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6826. ];
  6827. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6829. for (var index = 0; index < faces.length; index++) {
  6830. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6831. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6832. }
  6833. if (!noMipmap) {
  6834. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6835. }
  6836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6840. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6841. _this.resetTextureCache();
  6842. texture._width = width;
  6843. texture._height = height;
  6844. texture.isReady = true;
  6845. }, files);
  6846. }
  6847. return texture;
  6848. };
  6849. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6850. var _this = this;
  6851. var gl = this._gl;
  6852. var texture = gl.createTexture();
  6853. scene._addPendingData(texture);
  6854. texture.isCube = true;
  6855. texture.references = 1;
  6856. texture.url = url;
  6857. var internalFormat = this._getInternalFormat(format);
  6858. var textureType = gl.UNSIGNED_BYTE;
  6859. if (type === Engine.TEXTURETYPE_FLOAT) {
  6860. textureType = gl.FLOAT;
  6861. }
  6862. var width = size;
  6863. var height = width;
  6864. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6865. texture._width = width;
  6866. texture._height = height;
  6867. var onerror = function () {
  6868. scene._removePendingData(texture);
  6869. };
  6870. var internalCallback = function (data) {
  6871. var rgbeDataArrays = callback(data);
  6872. var facesIndex = [
  6873. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6874. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6875. ];
  6876. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6877. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6878. if (!noMipmap && isPot) {
  6879. if (mipmmapGenerator) {
  6880. var arrayTemp = [];
  6881. // Data are known to be in +X +Y +Z -X -Y -Z
  6882. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6883. arrayTemp.push(rgbeDataArrays[0]); // +X
  6884. arrayTemp.push(rgbeDataArrays[3]); // -X
  6885. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6886. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6887. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6888. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6889. var mipData = mipmmapGenerator(arrayTemp);
  6890. for (var level = 0; level < mipData.length; level++) {
  6891. var mipSize = width >> level;
  6892. // mipData is order in +X -X +Y -Y +Z -Z
  6893. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6894. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6895. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6896. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6897. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6898. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6899. }
  6900. }
  6901. else {
  6902. // Data are known to be in +X +Y +Z -X -Y -Z
  6903. for (var index = 0; index < facesIndex.length; index++) {
  6904. var faceData = rgbeDataArrays[index];
  6905. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6906. }
  6907. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6908. }
  6909. }
  6910. else {
  6911. noMipmap = true;
  6912. }
  6913. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6914. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6916. }
  6917. else {
  6918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6920. }
  6921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6923. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6924. texture.isReady = true;
  6925. _this.resetTextureCache();
  6926. scene._removePendingData(texture);
  6927. };
  6928. BABYLON.Tools.LoadFile(url, function (data) {
  6929. internalCallback(data);
  6930. }, onerror, scene.database, true);
  6931. return texture;
  6932. };
  6933. ;
  6934. Engine.prototype._releaseTexture = function (texture) {
  6935. var gl = this._gl;
  6936. if (texture._framebuffer) {
  6937. gl.deleteFramebuffer(texture._framebuffer);
  6938. }
  6939. if (texture._depthBuffer) {
  6940. gl.deleteRenderbuffer(texture._depthBuffer);
  6941. }
  6942. gl.deleteTexture(texture);
  6943. // Unbind channels
  6944. this.unbindAllTextures();
  6945. var index = this._loadedTexturesCache.indexOf(texture);
  6946. if (index !== -1) {
  6947. this._loadedTexturesCache.splice(index, 1);
  6948. }
  6949. };
  6950. Engine.prototype.bindSamplers = function (effect) {
  6951. this._gl.useProgram(effect.getProgram());
  6952. var samplers = effect.getSamplers();
  6953. for (var index = 0; index < samplers.length; index++) {
  6954. var uniform = effect.getUniform(samplers[index]);
  6955. this._gl.uniform1i(uniform, index);
  6956. }
  6957. this._currentEffect = null;
  6958. };
  6959. Engine.prototype._bindTexture = function (channel, texture) {
  6960. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6961. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6962. this._activeTexturesCache[channel] = null;
  6963. };
  6964. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6965. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6966. };
  6967. Engine.prototype.unbindAllTextures = function () {
  6968. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6969. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6970. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6971. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6972. this._activeTexturesCache[channel] = null;
  6973. }
  6974. };
  6975. Engine.prototype.setTexture = function (channel, texture) {
  6976. if (channel < 0) {
  6977. return;
  6978. }
  6979. // Not ready?
  6980. if (!texture || !texture.isReady()) {
  6981. if (this._activeTexturesCache[channel] != null) {
  6982. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6983. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6984. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6985. this._activeTexturesCache[channel] = null;
  6986. }
  6987. return;
  6988. }
  6989. // Video
  6990. var alreadyActivated = false;
  6991. if (texture instanceof BABYLON.VideoTexture) {
  6992. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6993. alreadyActivated = true;
  6994. texture.update();
  6995. }
  6996. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6997. texture.delayLoad();
  6998. return;
  6999. }
  7000. if (this._activeTexturesCache[channel] === texture) {
  7001. return;
  7002. }
  7003. this._activeTexturesCache[channel] = texture;
  7004. var internalTexture = texture.getInternalTexture();
  7005. if (!alreadyActivated) {
  7006. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7007. }
  7008. if (internalTexture.isCube) {
  7009. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7010. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7011. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7012. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7013. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7014. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7015. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7016. }
  7017. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7018. }
  7019. else {
  7020. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7021. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7022. internalTexture._cachedWrapU = texture.wrapU;
  7023. switch (texture.wrapU) {
  7024. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7025. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7026. break;
  7027. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7029. break;
  7030. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7031. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7032. break;
  7033. }
  7034. }
  7035. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7036. internalTexture._cachedWrapV = texture.wrapV;
  7037. switch (texture.wrapV) {
  7038. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7039. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7040. break;
  7041. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7042. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7043. break;
  7044. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7045. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7046. break;
  7047. }
  7048. }
  7049. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7050. }
  7051. };
  7052. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7053. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7054. var value = texture.anisotropicFilteringLevel;
  7055. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7056. value = 1;
  7057. }
  7058. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7059. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7060. texture._cachedAnisotropicFilteringLevel = value;
  7061. }
  7062. };
  7063. Engine.prototype.readPixels = function (x, y, width, height) {
  7064. var data = new Uint8Array(height * width * 4);
  7065. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7066. return data;
  7067. };
  7068. Engine.prototype.releaseInternalTexture = function (texture) {
  7069. if (!texture) {
  7070. return;
  7071. }
  7072. texture.references--;
  7073. // Final reference ?
  7074. if (texture.references === 0) {
  7075. var texturesCache = this.getLoadedTexturesCache();
  7076. var index = texturesCache.indexOf(texture);
  7077. if (index > -1) {
  7078. texturesCache.splice(index, 1);
  7079. }
  7080. this._releaseTexture(texture);
  7081. }
  7082. };
  7083. // Dispose
  7084. Engine.prototype.dispose = function () {
  7085. this.hideLoadingUI();
  7086. this.stopRenderLoop();
  7087. // Release scenes
  7088. while (this.scenes.length) {
  7089. this.scenes[0].dispose();
  7090. }
  7091. // Release audio engine
  7092. Engine.audioEngine.dispose();
  7093. // Release effects
  7094. for (var name in this._compiledEffects) {
  7095. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7096. }
  7097. // Unbind
  7098. for (var i in this._vertexAttribArrays) {
  7099. //making sure this is a string
  7100. var iAsNumber = +i;
  7101. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7102. continue;
  7103. }
  7104. this._gl.disableVertexAttribArray(iAsNumber);
  7105. }
  7106. this._gl = null;
  7107. // Events
  7108. window.removeEventListener("blur", this._onBlur);
  7109. window.removeEventListener("focus", this._onFocus);
  7110. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7111. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7112. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7113. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7114. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7115. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7116. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7117. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7118. };
  7119. // Loading screen
  7120. Engine.prototype.displayLoadingUI = function () {
  7121. this._loadingScreen.displayLoadingUI();
  7122. };
  7123. Engine.prototype.hideLoadingUI = function () {
  7124. this._loadingScreen.hideLoadingUI();
  7125. };
  7126. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7127. get: function () {
  7128. return this._loadingScreen;
  7129. },
  7130. set: function (loadingScreen) {
  7131. this._loadingScreen = loadingScreen;
  7132. },
  7133. enumerable: true,
  7134. configurable: true
  7135. });
  7136. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7137. set: function (text) {
  7138. this._loadingScreen.loadingUIText = text;
  7139. },
  7140. enumerable: true,
  7141. configurable: true
  7142. });
  7143. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7144. set: function (color) {
  7145. this._loadingScreen.loadingUIBackgroundColor = color;
  7146. },
  7147. enumerable: true,
  7148. configurable: true
  7149. });
  7150. // FPS
  7151. Engine.prototype.getFps = function () {
  7152. return this.fps;
  7153. };
  7154. Engine.prototype.getDeltaTime = function () {
  7155. return this.deltaTime;
  7156. };
  7157. Engine.prototype._measureFps = function () {
  7158. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7159. var length = this.previousFramesDuration.length;
  7160. if (length >= 2) {
  7161. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7162. }
  7163. if (length >= this.fpsRange) {
  7164. if (length > this.fpsRange) {
  7165. this.previousFramesDuration.splice(0, 1);
  7166. length = this.previousFramesDuration.length;
  7167. }
  7168. var sum = 0;
  7169. for (var id = 0; id < length - 1; id++) {
  7170. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7171. }
  7172. this.fps = 1000.0 / (sum / (length - 1));
  7173. }
  7174. };
  7175. // Statics
  7176. Engine.isSupported = function () {
  7177. try {
  7178. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7179. if (navigator.isCocoonJS) {
  7180. return true;
  7181. }
  7182. var tempcanvas = document.createElement("canvas");
  7183. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7184. return gl != null && !!window.WebGLRenderingContext;
  7185. }
  7186. catch (e) {
  7187. return false;
  7188. }
  7189. };
  7190. // Const statics
  7191. Engine._ALPHA_DISABLE = 0;
  7192. Engine._ALPHA_ADD = 1;
  7193. Engine._ALPHA_COMBINE = 2;
  7194. Engine._ALPHA_SUBTRACT = 3;
  7195. Engine._ALPHA_MULTIPLY = 4;
  7196. Engine._ALPHA_MAXIMIZED = 5;
  7197. Engine._ALPHA_ONEONE = 6;
  7198. Engine._DELAYLOADSTATE_NONE = 0;
  7199. Engine._DELAYLOADSTATE_LOADED = 1;
  7200. Engine._DELAYLOADSTATE_LOADING = 2;
  7201. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7202. Engine._TEXTUREFORMAT_ALPHA = 0;
  7203. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7204. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7205. Engine._TEXTUREFORMAT_RGB = 4;
  7206. Engine._TEXTUREFORMAT_RGBA = 5;
  7207. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7208. Engine._TEXTURETYPE_FLOAT = 1;
  7209. // Updatable statics so stick with vars here
  7210. Engine.CollisionsEpsilon = 0.001;
  7211. Engine.CodeRepository = "src/";
  7212. Engine.ShadersRepository = "src/Shaders/";
  7213. return Engine;
  7214. }());
  7215. BABYLON.Engine = Engine;
  7216. })(BABYLON || (BABYLON = {}));
  7217. var BABYLON;
  7218. (function (BABYLON) {
  7219. /**
  7220. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7221. */
  7222. var Node = (function () {
  7223. /**
  7224. * @constructor
  7225. * @param {string} name - the name and id to be given to this node
  7226. * @param {BABYLON.Scene} the scene this node will be added to
  7227. */
  7228. function Node(name, scene) {
  7229. this.state = "";
  7230. this.animations = new Array();
  7231. this._ranges = {};
  7232. this._childrenFlag = -1;
  7233. this._isEnabled = true;
  7234. this._isReady = true;
  7235. this._currentRenderId = -1;
  7236. this._parentRenderId = -1;
  7237. this.name = name;
  7238. this.id = name;
  7239. this._scene = scene;
  7240. this._initCache();
  7241. }
  7242. Object.defineProperty(Node.prototype, "parent", {
  7243. get: function () {
  7244. return this._parentNode;
  7245. },
  7246. set: function (parent) {
  7247. if (this._parentNode === parent) {
  7248. return;
  7249. }
  7250. if (this._parentNode) {
  7251. var index = this._parentNode._children.indexOf(this);
  7252. if (index !== -1) {
  7253. this._parentNode._children.splice(index, 1);
  7254. }
  7255. }
  7256. this._parentNode = parent;
  7257. if (this._parentNode) {
  7258. if (!this._parentNode._children) {
  7259. this._parentNode._children = new Array();
  7260. }
  7261. this._parentNode._children.push(this);
  7262. }
  7263. },
  7264. enumerable: true,
  7265. configurable: true
  7266. });
  7267. Node.prototype.getScene = function () {
  7268. return this._scene;
  7269. };
  7270. Node.prototype.getEngine = function () {
  7271. return this._scene.getEngine();
  7272. };
  7273. // override it in derived class
  7274. Node.prototype.getWorldMatrix = function () {
  7275. return BABYLON.Matrix.Identity();
  7276. };
  7277. // override it in derived class if you add new variables to the cache
  7278. // and call the parent class method
  7279. Node.prototype._initCache = function () {
  7280. this._cache = {};
  7281. this._cache.parent = undefined;
  7282. };
  7283. Node.prototype.updateCache = function (force) {
  7284. if (!force && this.isSynchronized())
  7285. return;
  7286. this._cache.parent = this.parent;
  7287. this._updateCache();
  7288. };
  7289. // override it in derived class if you add new variables to the cache
  7290. // and call the parent class method if !ignoreParentClass
  7291. Node.prototype._updateCache = function (ignoreParentClass) {
  7292. };
  7293. // override it in derived class if you add new variables to the cache
  7294. Node.prototype._isSynchronized = function () {
  7295. return true;
  7296. };
  7297. Node.prototype._markSyncedWithParent = function () {
  7298. this._parentRenderId = this.parent._currentRenderId;
  7299. };
  7300. Node.prototype.isSynchronizedWithParent = function () {
  7301. if (!this.parent) {
  7302. return true;
  7303. }
  7304. if (this._parentRenderId !== this.parent._currentRenderId) {
  7305. return false;
  7306. }
  7307. return this.parent.isSynchronized();
  7308. };
  7309. Node.prototype.isSynchronized = function (updateCache) {
  7310. var check = this.hasNewParent();
  7311. check = check || !this.isSynchronizedWithParent();
  7312. check = check || !this._isSynchronized();
  7313. if (updateCache)
  7314. this.updateCache(true);
  7315. return !check;
  7316. };
  7317. Node.prototype.hasNewParent = function (update) {
  7318. if (this._cache.parent === this.parent)
  7319. return false;
  7320. if (update)
  7321. this._cache.parent = this.parent;
  7322. return true;
  7323. };
  7324. /**
  7325. * Is this node ready to be used/rendered
  7326. * @return {boolean} is it ready
  7327. */
  7328. Node.prototype.isReady = function () {
  7329. return this._isReady;
  7330. };
  7331. /**
  7332. * Is this node enabled.
  7333. * If the node has a parent and is enabled, the parent will be inspected as well.
  7334. * @return {boolean} whether this node (and its parent) is enabled.
  7335. * @see setEnabled
  7336. */
  7337. Node.prototype.isEnabled = function () {
  7338. if (!this._isEnabled) {
  7339. return false;
  7340. }
  7341. if (this.parent) {
  7342. return this.parent.isEnabled();
  7343. }
  7344. return true;
  7345. };
  7346. /**
  7347. * Set the enabled state of this node.
  7348. * @param {boolean} value - the new enabled state
  7349. * @see isEnabled
  7350. */
  7351. Node.prototype.setEnabled = function (value) {
  7352. this._isEnabled = value;
  7353. };
  7354. /**
  7355. * Is this node a descendant of the given node.
  7356. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7357. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7358. * @see parent
  7359. */
  7360. Node.prototype.isDescendantOf = function (ancestor) {
  7361. if (this.parent) {
  7362. if (this.parent === ancestor) {
  7363. return true;
  7364. }
  7365. return this.parent.isDescendantOf(ancestor);
  7366. }
  7367. return false;
  7368. };
  7369. /**
  7370. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7371. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7372. * @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.
  7373. * @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.
  7374. */
  7375. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7376. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7377. if (!this._children) {
  7378. return;
  7379. }
  7380. for (var index = 0; index < this._children.length; index++) {
  7381. var item = this._children[index];
  7382. if (!predicate || predicate(item)) {
  7383. results.push(item);
  7384. }
  7385. if (!directDescendantsOnly) {
  7386. item._getDescendants(results, false, predicate);
  7387. }
  7388. }
  7389. };
  7390. /**
  7391. * Will return all nodes that have this node as ascendant.
  7392. * @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.
  7393. * @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.
  7394. * @return {BABYLON.Node[]} all children nodes of all types.
  7395. */
  7396. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7397. var results = [];
  7398. this._getDescendants(results, directDescendantsOnly, predicate);
  7399. return results;
  7400. };
  7401. /**
  7402. * @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.
  7403. * @Deprecated, legacy support.
  7404. * use getDecendants instead.
  7405. */
  7406. Node.prototype.getChildren = function (predicate) {
  7407. return this.getDescendants(true, predicate);
  7408. };
  7409. /**
  7410. * Get all child-meshes of this node.
  7411. */
  7412. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7413. var results = [];
  7414. this._getDescendants(results, directDecendantsOnly, function (node) {
  7415. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7416. });
  7417. return results;
  7418. };
  7419. Node.prototype._setReady = function (state) {
  7420. if (state === this._isReady) {
  7421. return;
  7422. }
  7423. if (!state) {
  7424. this._isReady = false;
  7425. return;
  7426. }
  7427. this._isReady = true;
  7428. if (this.onReady) {
  7429. this.onReady(this);
  7430. }
  7431. };
  7432. Node.prototype.getAnimationByName = function (name) {
  7433. for (var i = 0; i < this.animations.length; i++) {
  7434. var animation = this.animations[i];
  7435. if (animation.name === name) {
  7436. return animation;
  7437. }
  7438. }
  7439. return null;
  7440. };
  7441. Node.prototype.createAnimationRange = function (name, from, to) {
  7442. // check name not already in use
  7443. if (!this._ranges[name]) {
  7444. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7445. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7446. if (this.animations[i]) {
  7447. this.animations[i].createRange(name, from, to);
  7448. }
  7449. }
  7450. }
  7451. };
  7452. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7453. if (deleteFrames === void 0) { deleteFrames = true; }
  7454. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7455. if (this.animations[i]) {
  7456. this.animations[i].deleteRange(name, deleteFrames);
  7457. }
  7458. }
  7459. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7460. };
  7461. Node.prototype.getAnimationRange = function (name) {
  7462. return this._ranges[name];
  7463. };
  7464. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7465. var range = this.getAnimationRange(name);
  7466. if (!range) {
  7467. return null;
  7468. }
  7469. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7470. };
  7471. Node.prototype.serializeAnimationRanges = function () {
  7472. var serializationRanges = [];
  7473. for (var name in this._ranges) {
  7474. var range = {};
  7475. range.name = name;
  7476. range.from = this._ranges[name].from;
  7477. range.to = this._ranges[name].to;
  7478. serializationRanges.push(range);
  7479. }
  7480. return serializationRanges;
  7481. };
  7482. Node.prototype.dispose = function () {
  7483. this.parent = null;
  7484. };
  7485. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7486. if (parsedNode.ranges) {
  7487. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7488. var data = parsedNode.ranges[index];
  7489. node.createAnimationRange(data.name, data.from, data.to);
  7490. }
  7491. }
  7492. };
  7493. __decorate([
  7494. BABYLON.serialize()
  7495. ], Node.prototype, "name", void 0);
  7496. __decorate([
  7497. BABYLON.serialize()
  7498. ], Node.prototype, "id", void 0);
  7499. __decorate([
  7500. BABYLON.serialize()
  7501. ], Node.prototype, "uniqueId", void 0);
  7502. __decorate([
  7503. BABYLON.serialize()
  7504. ], Node.prototype, "state", void 0);
  7505. return Node;
  7506. }());
  7507. BABYLON.Node = Node;
  7508. })(BABYLON || (BABYLON = {}));
  7509. var BABYLON;
  7510. (function (BABYLON) {
  7511. var FilesInput = (function () {
  7512. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7513. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7514. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7515. this._engine = p_engine;
  7516. this._canvas = p_canvas;
  7517. this._currentScene = p_scene;
  7518. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7519. this._progressCallback = p_progressCallback;
  7520. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7521. this._textureLoadingCallback = p_textureLoadingCallback;
  7522. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7523. }
  7524. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7525. var _this = this;
  7526. if (p_elementToMonitor) {
  7527. this._elementToMonitor = p_elementToMonitor;
  7528. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7529. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7530. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7531. }
  7532. };
  7533. FilesInput.prototype.renderFunction = function () {
  7534. if (this._additionnalRenderLoopLogicCallback) {
  7535. this._additionnalRenderLoopLogicCallback();
  7536. }
  7537. if (this._currentScene) {
  7538. if (this._textureLoadingCallback) {
  7539. var remaining = this._currentScene.getWaitingItemsCount();
  7540. if (remaining > 0) {
  7541. this._textureLoadingCallback(remaining);
  7542. }
  7543. }
  7544. this._currentScene.render();
  7545. }
  7546. };
  7547. FilesInput.prototype.drag = function (e) {
  7548. e.stopPropagation();
  7549. e.preventDefault();
  7550. };
  7551. FilesInput.prototype.drop = function (eventDrop) {
  7552. eventDrop.stopPropagation();
  7553. eventDrop.preventDefault();
  7554. this.loadFiles(eventDrop);
  7555. };
  7556. FilesInput.prototype.loadFiles = function (event) {
  7557. if (this._startingProcessingFilesCallback)
  7558. this._startingProcessingFilesCallback();
  7559. // Handling data transfer via drag'n'drop
  7560. if (event && event.dataTransfer && event.dataTransfer.files) {
  7561. this._filesToLoad = event.dataTransfer.files;
  7562. }
  7563. // Handling files from input files
  7564. if (event && event.target && event.target.files) {
  7565. this._filesToLoad = event.target.files;
  7566. }
  7567. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7568. for (var i = 0; i < this._filesToLoad.length; i++) {
  7569. switch (this._filesToLoad[i].type) {
  7570. case "image/jpeg":
  7571. case "image/png":
  7572. case "image/bmp":
  7573. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7574. break;
  7575. case "image/targa":
  7576. case "image/vnd.ms-dds":
  7577. case "audio/wav":
  7578. case "audio/x-wav":
  7579. case "audio/mp3":
  7580. case "audio/mpeg":
  7581. case "audio/mpeg3":
  7582. case "audio/x-mpeg-3":
  7583. case "audio/ogg":
  7584. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7585. break;
  7586. default:
  7587. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7588. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7589. }
  7590. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7591. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7592. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7593. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7594. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7595. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7596. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7597. this._sceneFileToLoad = this._filesToLoad[i];
  7598. }
  7599. break;
  7600. }
  7601. }
  7602. this.reload();
  7603. }
  7604. };
  7605. FilesInput.prototype.reload = function () {
  7606. var _this = this;
  7607. var that = this;
  7608. // If a ".babylon" file has been provided
  7609. if (this._sceneFileToLoad) {
  7610. if (this._currentScene) {
  7611. if (BABYLON.Tools.errorsCount > 0) {
  7612. BABYLON.Tools.ClearLogCache();
  7613. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7614. }
  7615. this._engine.stopRenderLoop();
  7616. this._currentScene.dispose();
  7617. }
  7618. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7619. that._currentScene = newScene;
  7620. // Wait for textures and shaders to be ready
  7621. that._currentScene.executeWhenReady(function () {
  7622. // Attach camera to canvas inputs
  7623. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7624. that._currentScene.createDefaultCameraOrLight();
  7625. }
  7626. that._currentScene.activeCamera.attachControl(that._canvas);
  7627. if (that._sceneLoadedCallback) {
  7628. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7629. }
  7630. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7631. });
  7632. }, function (progress) {
  7633. if (_this._progressCallback) {
  7634. _this._progressCallback(progress);
  7635. }
  7636. });
  7637. }
  7638. else {
  7639. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7640. }
  7641. };
  7642. FilesInput.FilesTextures = new Array();
  7643. FilesInput.FilesToLoad = new Array();
  7644. return FilesInput;
  7645. }());
  7646. BABYLON.FilesInput = FilesInput;
  7647. })(BABYLON || (BABYLON = {}));
  7648. var BABYLON;
  7649. (function (BABYLON) {
  7650. var IntersectionInfo = (function () {
  7651. function IntersectionInfo(bu, bv, distance) {
  7652. this.bu = bu;
  7653. this.bv = bv;
  7654. this.distance = distance;
  7655. this.faceId = 0;
  7656. this.subMeshId = 0;
  7657. }
  7658. return IntersectionInfo;
  7659. }());
  7660. BABYLON.IntersectionInfo = IntersectionInfo;
  7661. var PickingInfo = (function () {
  7662. function PickingInfo() {
  7663. this.hit = false;
  7664. this.distance = 0;
  7665. this.pickedPoint = null;
  7666. this.pickedMesh = null;
  7667. this.bu = 0;
  7668. this.bv = 0;
  7669. this.faceId = -1;
  7670. this.subMeshId = 0;
  7671. this.pickedSprite = null;
  7672. }
  7673. // Methods
  7674. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7675. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7676. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7677. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7678. return null;
  7679. }
  7680. var indices = this.pickedMesh.getIndices();
  7681. var result;
  7682. if (useVerticesNormals) {
  7683. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7684. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7685. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7686. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7687. normal0 = normal0.scale(this.bu);
  7688. normal1 = normal1.scale(this.bv);
  7689. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7690. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7691. }
  7692. else {
  7693. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7694. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7695. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7696. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7697. var p1p2 = vertex1.subtract(vertex2);
  7698. var p3p2 = vertex3.subtract(vertex2);
  7699. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7700. }
  7701. if (useWorldCoordinates) {
  7702. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7703. }
  7704. return BABYLON.Vector3.Normalize(result);
  7705. };
  7706. PickingInfo.prototype.getTextureCoordinates = function () {
  7707. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7708. return null;
  7709. }
  7710. var indices = this.pickedMesh.getIndices();
  7711. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7712. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7713. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7714. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7715. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7716. uv1 = uv1.scale(this.bu);
  7717. uv2 = uv2.scale(this.bv);
  7718. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7719. };
  7720. return PickingInfo;
  7721. }());
  7722. BABYLON.PickingInfo = PickingInfo;
  7723. })(BABYLON || (BABYLON = {}));
  7724. var BABYLON;
  7725. (function (BABYLON) {
  7726. var BoundingSphere = (function () {
  7727. function BoundingSphere(minimum, maximum) {
  7728. this.minimum = minimum;
  7729. this.maximum = maximum;
  7730. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7731. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7732. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7733. this.radius = distance * 0.5;
  7734. this.centerWorld = BABYLON.Vector3.Zero();
  7735. this._update(BABYLON.Matrix.Identity());
  7736. }
  7737. // Methods
  7738. BoundingSphere.prototype._update = function (world) {
  7739. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7740. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7741. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7742. };
  7743. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7744. for (var i = 0; i < 6; i++) {
  7745. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7746. return false;
  7747. }
  7748. return true;
  7749. };
  7750. BoundingSphere.prototype.intersectsPoint = function (point) {
  7751. var x = this.centerWorld.x - point.x;
  7752. var y = this.centerWorld.y - point.y;
  7753. var z = this.centerWorld.z - point.z;
  7754. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7755. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7756. return false;
  7757. return true;
  7758. };
  7759. // Statics
  7760. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7761. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7762. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7763. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7764. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7765. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7766. return false;
  7767. return true;
  7768. };
  7769. return BoundingSphere;
  7770. }());
  7771. BABYLON.BoundingSphere = BoundingSphere;
  7772. })(BABYLON || (BABYLON = {}));
  7773. var BABYLON;
  7774. (function (BABYLON) {
  7775. var BoundingBox = (function () {
  7776. function BoundingBox(minimum, maximum) {
  7777. this.minimum = minimum;
  7778. this.maximum = maximum;
  7779. this.vectors = new Array();
  7780. this.vectorsWorld = new Array();
  7781. // Bounding vectors
  7782. this.vectors.push(this.minimum.clone());
  7783. this.vectors.push(this.maximum.clone());
  7784. this.vectors.push(this.minimum.clone());
  7785. this.vectors[2].x = this.maximum.x;
  7786. this.vectors.push(this.minimum.clone());
  7787. this.vectors[3].y = this.maximum.y;
  7788. this.vectors.push(this.minimum.clone());
  7789. this.vectors[4].z = this.maximum.z;
  7790. this.vectors.push(this.maximum.clone());
  7791. this.vectors[5].z = this.minimum.z;
  7792. this.vectors.push(this.maximum.clone());
  7793. this.vectors[6].x = this.minimum.x;
  7794. this.vectors.push(this.maximum.clone());
  7795. this.vectors[7].y = this.minimum.y;
  7796. // OBB
  7797. this.center = this.maximum.add(this.minimum).scale(0.5);
  7798. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7799. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7800. // World
  7801. for (var index = 0; index < this.vectors.length; index++) {
  7802. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7803. }
  7804. this.minimumWorld = BABYLON.Vector3.Zero();
  7805. this.maximumWorld = BABYLON.Vector3.Zero();
  7806. this._update(BABYLON.Matrix.Identity());
  7807. }
  7808. // Methods
  7809. BoundingBox.prototype.getWorldMatrix = function () {
  7810. return this._worldMatrix;
  7811. };
  7812. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7813. this._worldMatrix.copyFrom(matrix);
  7814. return this;
  7815. };
  7816. BoundingBox.prototype._update = function (world) {
  7817. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7818. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7819. for (var index = 0; index < this.vectors.length; index++) {
  7820. var v = this.vectorsWorld[index];
  7821. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7822. if (v.x < this.minimumWorld.x)
  7823. this.minimumWorld.x = v.x;
  7824. if (v.y < this.minimumWorld.y)
  7825. this.minimumWorld.y = v.y;
  7826. if (v.z < this.minimumWorld.z)
  7827. this.minimumWorld.z = v.z;
  7828. if (v.x > this.maximumWorld.x)
  7829. this.maximumWorld.x = v.x;
  7830. if (v.y > this.maximumWorld.y)
  7831. this.maximumWorld.y = v.y;
  7832. if (v.z > this.maximumWorld.z)
  7833. this.maximumWorld.z = v.z;
  7834. }
  7835. // OBB
  7836. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7837. this.center.scaleInPlace(0.5);
  7838. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7839. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7840. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7841. this._worldMatrix = world;
  7842. };
  7843. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7844. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7845. };
  7846. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7847. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7848. };
  7849. BoundingBox.prototype.intersectsPoint = function (point) {
  7850. var delta = -BABYLON.Epsilon;
  7851. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7852. return false;
  7853. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7854. return false;
  7855. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7856. return false;
  7857. return true;
  7858. };
  7859. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7860. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7861. };
  7862. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7863. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7864. return false;
  7865. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7866. return false;
  7867. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7868. return false;
  7869. return true;
  7870. };
  7871. // Statics
  7872. BoundingBox.Intersects = function (box0, box1) {
  7873. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7874. return false;
  7875. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7876. return false;
  7877. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7878. return false;
  7879. return true;
  7880. };
  7881. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7882. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7883. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7884. return (num <= (sphereRadius * sphereRadius));
  7885. };
  7886. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7887. for (var p = 0; p < 6; p++) {
  7888. for (var i = 0; i < 8; i++) {
  7889. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7890. return false;
  7891. }
  7892. }
  7893. }
  7894. return true;
  7895. };
  7896. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7897. for (var p = 0; p < 6; p++) {
  7898. var inCount = 8;
  7899. for (var i = 0; i < 8; i++) {
  7900. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7901. --inCount;
  7902. }
  7903. else {
  7904. break;
  7905. }
  7906. }
  7907. if (inCount === 0)
  7908. return false;
  7909. }
  7910. return true;
  7911. };
  7912. return BoundingBox;
  7913. }());
  7914. BABYLON.BoundingBox = BoundingBox;
  7915. })(BABYLON || (BABYLON = {}));
  7916. var BABYLON;
  7917. (function (BABYLON) {
  7918. var computeBoxExtents = function (axis, box) {
  7919. var p = BABYLON.Vector3.Dot(box.center, axis);
  7920. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7921. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7922. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7923. var r = r0 + r1 + r2;
  7924. return {
  7925. min: p - r,
  7926. max: p + r
  7927. };
  7928. };
  7929. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7930. var axisOverlap = function (axis, box0, box1) {
  7931. var result0 = computeBoxExtents(axis, box0);
  7932. var result1 = computeBoxExtents(axis, box1);
  7933. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7934. };
  7935. var BoundingInfo = (function () {
  7936. function BoundingInfo(minimum, maximum) {
  7937. this.minimum = minimum;
  7938. this.maximum = maximum;
  7939. this._isLocked = false;
  7940. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7941. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7942. }
  7943. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7944. get: function () {
  7945. return this._isLocked;
  7946. },
  7947. set: function (value) {
  7948. this._isLocked = value;
  7949. },
  7950. enumerable: true,
  7951. configurable: true
  7952. });
  7953. // Methods
  7954. BoundingInfo.prototype.update = function (world) {
  7955. if (this._isLocked) {
  7956. return;
  7957. }
  7958. this.boundingBox._update(world);
  7959. this.boundingSphere._update(world);
  7960. };
  7961. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7962. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7963. return false;
  7964. return this.boundingBox.isInFrustum(frustumPlanes);
  7965. };
  7966. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7967. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7968. };
  7969. BoundingInfo.prototype._checkCollision = function (collider) {
  7970. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7971. };
  7972. BoundingInfo.prototype.intersectsPoint = function (point) {
  7973. if (!this.boundingSphere.centerWorld) {
  7974. return false;
  7975. }
  7976. if (!this.boundingSphere.intersectsPoint(point)) {
  7977. return false;
  7978. }
  7979. if (!this.boundingBox.intersectsPoint(point)) {
  7980. return false;
  7981. }
  7982. return true;
  7983. };
  7984. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7985. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7986. return false;
  7987. }
  7988. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7989. return false;
  7990. }
  7991. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7992. return false;
  7993. }
  7994. if (!precise) {
  7995. return true;
  7996. }
  7997. var box0 = this.boundingBox;
  7998. var box1 = boundingInfo.boundingBox;
  7999. if (!axisOverlap(box0.directions[0], box0, box1))
  8000. return false;
  8001. if (!axisOverlap(box0.directions[1], box0, box1))
  8002. return false;
  8003. if (!axisOverlap(box0.directions[2], box0, box1))
  8004. return false;
  8005. if (!axisOverlap(box1.directions[0], box0, box1))
  8006. return false;
  8007. if (!axisOverlap(box1.directions[1], box0, box1))
  8008. return false;
  8009. if (!axisOverlap(box1.directions[2], box0, box1))
  8010. return false;
  8011. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8012. return false;
  8013. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8014. return false;
  8015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8016. return false;
  8017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8018. return false;
  8019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8020. return false;
  8021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8022. return false;
  8023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8024. return false;
  8025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8026. return false;
  8027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8028. return false;
  8029. return true;
  8030. };
  8031. return BoundingInfo;
  8032. }());
  8033. BABYLON.BoundingInfo = BoundingInfo;
  8034. })(BABYLON || (BABYLON = {}));
  8035. var BABYLON;
  8036. (function (BABYLON) {
  8037. var Ray = (function () {
  8038. function Ray(origin, direction, length) {
  8039. if (length === void 0) { length = Number.MAX_VALUE; }
  8040. this.origin = origin;
  8041. this.direction = direction;
  8042. this.length = length;
  8043. }
  8044. // Methods
  8045. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8046. var d = 0.0;
  8047. var maxValue = Number.MAX_VALUE;
  8048. var inv;
  8049. var min;
  8050. var max;
  8051. var temp;
  8052. if (Math.abs(this.direction.x) < 0.0000001) {
  8053. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8054. return false;
  8055. }
  8056. }
  8057. else {
  8058. inv = 1.0 / this.direction.x;
  8059. min = (minimum.x - this.origin.x) * inv;
  8060. max = (maximum.x - this.origin.x) * inv;
  8061. if (max === -Infinity) {
  8062. max = Infinity;
  8063. }
  8064. if (min > max) {
  8065. temp = min;
  8066. min = max;
  8067. max = temp;
  8068. }
  8069. d = Math.max(min, d);
  8070. maxValue = Math.min(max, maxValue);
  8071. if (d > maxValue) {
  8072. return false;
  8073. }
  8074. }
  8075. if (Math.abs(this.direction.y) < 0.0000001) {
  8076. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8077. return false;
  8078. }
  8079. }
  8080. else {
  8081. inv = 1.0 / this.direction.y;
  8082. min = (minimum.y - this.origin.y) * inv;
  8083. max = (maximum.y - this.origin.y) * inv;
  8084. if (max === -Infinity) {
  8085. max = Infinity;
  8086. }
  8087. if (min > max) {
  8088. temp = min;
  8089. min = max;
  8090. max = temp;
  8091. }
  8092. d = Math.max(min, d);
  8093. maxValue = Math.min(max, maxValue);
  8094. if (d > maxValue) {
  8095. return false;
  8096. }
  8097. }
  8098. if (Math.abs(this.direction.z) < 0.0000001) {
  8099. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8100. return false;
  8101. }
  8102. }
  8103. else {
  8104. inv = 1.0 / this.direction.z;
  8105. min = (minimum.z - this.origin.z) * inv;
  8106. max = (maximum.z - this.origin.z) * inv;
  8107. if (max === -Infinity) {
  8108. max = Infinity;
  8109. }
  8110. if (min > max) {
  8111. temp = min;
  8112. min = max;
  8113. max = temp;
  8114. }
  8115. d = Math.max(min, d);
  8116. maxValue = Math.min(max, maxValue);
  8117. if (d > maxValue) {
  8118. return false;
  8119. }
  8120. }
  8121. return true;
  8122. };
  8123. Ray.prototype.intersectsBox = function (box) {
  8124. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8125. };
  8126. Ray.prototype.intersectsSphere = function (sphere) {
  8127. var x = sphere.center.x - this.origin.x;
  8128. var y = sphere.center.y - this.origin.y;
  8129. var z = sphere.center.z - this.origin.z;
  8130. var pyth = (x * x) + (y * y) + (z * z);
  8131. var rr = sphere.radius * sphere.radius;
  8132. if (pyth <= rr) {
  8133. return true;
  8134. }
  8135. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8136. if (dot < 0.0) {
  8137. return false;
  8138. }
  8139. var temp = pyth - (dot * dot);
  8140. return temp <= rr;
  8141. };
  8142. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8143. if (!this._edge1) {
  8144. this._edge1 = BABYLON.Vector3.Zero();
  8145. this._edge2 = BABYLON.Vector3.Zero();
  8146. this._pvec = BABYLON.Vector3.Zero();
  8147. this._tvec = BABYLON.Vector3.Zero();
  8148. this._qvec = BABYLON.Vector3.Zero();
  8149. }
  8150. vertex1.subtractToRef(vertex0, this._edge1);
  8151. vertex2.subtractToRef(vertex0, this._edge2);
  8152. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8153. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8154. if (det === 0) {
  8155. return null;
  8156. }
  8157. var invdet = 1 / det;
  8158. this.origin.subtractToRef(vertex0, this._tvec);
  8159. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8160. if (bu < 0 || bu > 1.0) {
  8161. return null;
  8162. }
  8163. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8164. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8165. if (bv < 0 || bu + bv > 1.0) {
  8166. return null;
  8167. }
  8168. //check if the distance is longer than the predefined length.
  8169. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8170. if (distance > this.length) {
  8171. return null;
  8172. }
  8173. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8174. };
  8175. Ray.prototype.intersectsPlane = function (plane) {
  8176. var distance;
  8177. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8178. if (Math.abs(result1) < 9.99999997475243E-07) {
  8179. return null;
  8180. }
  8181. else {
  8182. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8183. distance = (-plane.d - result2) / result1;
  8184. if (distance < 0.0) {
  8185. if (distance < -9.99999997475243E-07) {
  8186. return null;
  8187. }
  8188. else {
  8189. return 0;
  8190. }
  8191. }
  8192. return distance;
  8193. }
  8194. };
  8195. /**
  8196. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8197. * @param sega the first point of the segment to test the intersection against
  8198. * @param segb the second point of the segment to test the intersection against
  8199. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8200. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8201. */
  8202. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8203. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8204. var u = segb.subtract(sega);
  8205. var v = rsegb.subtract(this.origin);
  8206. var w = sega.subtract(this.origin);
  8207. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8208. var b = BABYLON.Vector3.Dot(u, v);
  8209. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8210. var d = BABYLON.Vector3.Dot(u, w);
  8211. var e = BABYLON.Vector3.Dot(v, w);
  8212. var D = a * c - b * b; // always >= 0
  8213. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8214. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8215. // compute the line parameters of the two closest points
  8216. if (D < Ray.smallnum) {
  8217. sN = 0.0; // force using point P0 on segment S1
  8218. sD = 1.0; // to prevent possible division by 0.0 later
  8219. tN = e;
  8220. tD = c;
  8221. }
  8222. else {
  8223. sN = (b * e - c * d);
  8224. tN = (a * e - b * d);
  8225. if (sN < 0.0) {
  8226. sN = 0.0;
  8227. tN = e;
  8228. tD = c;
  8229. }
  8230. else if (sN > sD) {
  8231. sN = sD;
  8232. tN = e + b;
  8233. tD = c;
  8234. }
  8235. }
  8236. if (tN < 0.0) {
  8237. tN = 0.0;
  8238. // recompute sc for this edge
  8239. if (-d < 0.0) {
  8240. sN = 0.0;
  8241. }
  8242. else if (-d > a)
  8243. sN = sD;
  8244. else {
  8245. sN = -d;
  8246. sD = a;
  8247. }
  8248. }
  8249. else if (tN > tD) {
  8250. tN = tD;
  8251. // recompute sc for this edge
  8252. if ((-d + b) < 0.0) {
  8253. sN = 0;
  8254. }
  8255. else if ((-d + b) > a) {
  8256. sN = sD;
  8257. }
  8258. else {
  8259. sN = (-d + b);
  8260. sD = a;
  8261. }
  8262. }
  8263. // finally do the division to get sc and tc
  8264. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8265. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8266. // get the difference of the two closest points
  8267. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(v.multiplyByFloats(tc, tc, tc)); // = S1(sc) - S2(tc)
  8268. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8269. if (isIntersected) {
  8270. return tc;
  8271. }
  8272. return -1;
  8273. };
  8274. // Statics
  8275. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8276. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8277. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8278. var direction = end.subtract(start);
  8279. direction.normalize();
  8280. return new Ray(start, direction);
  8281. };
  8282. /**
  8283. * 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
  8284. * transformed to the given world matrix.
  8285. * @param origin The origin point
  8286. * @param end The end point
  8287. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8288. */
  8289. Ray.CreateNewFromTo = function (origin, end, world) {
  8290. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8291. var direction = end.subtract(origin);
  8292. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8293. direction.normalize();
  8294. return Ray.Transform(new Ray(origin, direction, length), world);
  8295. };
  8296. Ray.Transform = function (ray, matrix) {
  8297. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8298. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8299. return new Ray(newOrigin, newDirection, ray.length);
  8300. };
  8301. Ray.smallnum = 0.00000001;
  8302. Ray.rayl = 10e8;
  8303. return Ray;
  8304. }());
  8305. BABYLON.Ray = Ray;
  8306. })(BABYLON || (BABYLON = {}));
  8307. var BABYLON;
  8308. (function (BABYLON) {
  8309. var AbstractMesh = (function (_super) {
  8310. __extends(AbstractMesh, _super);
  8311. // Constructor
  8312. function AbstractMesh(name, scene) {
  8313. var _this = this;
  8314. _super.call(this, name, scene);
  8315. // Events
  8316. /**
  8317. * An event triggered when this mesh collides with another one
  8318. * @type {BABYLON.Observable}
  8319. */
  8320. this.onCollideObservable = new BABYLON.Observable();
  8321. /**
  8322. * An event triggered when the collision's position changes
  8323. * @type {BABYLON.Observable}
  8324. */
  8325. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8326. /**
  8327. * An event triggered after the world matrix is updated
  8328. * @type {BABYLON.Observable}
  8329. */
  8330. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8331. // Properties
  8332. this.definedFacingForward = true; // orientation for POV movement & rotation
  8333. this.position = new BABYLON.Vector3(0, 0, 0);
  8334. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8335. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8336. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8337. this.visibility = 1.0;
  8338. this.alphaIndex = Number.MAX_VALUE;
  8339. this.infiniteDistance = false;
  8340. this.isVisible = true;
  8341. this.isPickable = true;
  8342. this.showBoundingBox = false;
  8343. this.showSubMeshesBoundingBox = false;
  8344. this.onDispose = null;
  8345. this.isBlocker = false;
  8346. this.renderingGroupId = 0;
  8347. this.receiveShadows = false;
  8348. this.renderOutline = false;
  8349. this.outlineColor = BABYLON.Color3.Red();
  8350. this.outlineWidth = 0.02;
  8351. this.renderOverlay = false;
  8352. this.overlayColor = BABYLON.Color3.Red();
  8353. this.overlayAlpha = 0.5;
  8354. this.hasVertexAlpha = false;
  8355. this.useVertexColors = true;
  8356. this.applyFog = true;
  8357. this.computeBonesUsingShaders = true;
  8358. this.scalingDeterminant = 1;
  8359. this.numBoneInfluencers = 4;
  8360. this.useOctreeForRenderingSelection = true;
  8361. this.useOctreeForPicking = true;
  8362. this.useOctreeForCollisions = true;
  8363. this.layerMask = 0x0FFFFFFF;
  8364. this.alwaysSelectAsActiveMesh = false;
  8365. // Collisions
  8366. this._checkCollisions = false;
  8367. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8368. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8369. this._collider = new BABYLON.Collider();
  8370. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8371. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8372. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8373. // Edges
  8374. this.edgesWidth = 1;
  8375. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8376. // Cache
  8377. this._localWorld = BABYLON.Matrix.Zero();
  8378. this._worldMatrix = BABYLON.Matrix.Zero();
  8379. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8380. this._absolutePosition = BABYLON.Vector3.Zero();
  8381. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8382. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8383. this._isDirty = false;
  8384. this._pivotMatrix = BABYLON.Matrix.Identity();
  8385. this._isDisposed = false;
  8386. this._renderId = 0;
  8387. this._intersectionsInProgress = new Array();
  8388. this._isWorldMatrixFrozen = false;
  8389. this._unIndexed = false;
  8390. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8391. if (collidedMesh === void 0) { collidedMesh = null; }
  8392. //TODO move this to the collision coordinator!
  8393. if (_this.getScene().workerCollisions)
  8394. newPosition.multiplyInPlace(_this._collider.radius);
  8395. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8396. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8397. _this.position.addInPlace(_this._diffPositionForCollisions);
  8398. }
  8399. if (collidedMesh) {
  8400. _this.onCollideObservable.notifyObservers(collidedMesh);
  8401. }
  8402. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8403. };
  8404. scene.addMesh(this);
  8405. }
  8406. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8407. get: function () {
  8408. return AbstractMesh._BILLBOARDMODE_NONE;
  8409. },
  8410. enumerable: true,
  8411. configurable: true
  8412. });
  8413. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8414. get: function () {
  8415. return AbstractMesh._BILLBOARDMODE_X;
  8416. },
  8417. enumerable: true,
  8418. configurable: true
  8419. });
  8420. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8421. get: function () {
  8422. return AbstractMesh._BILLBOARDMODE_Y;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8428. get: function () {
  8429. return AbstractMesh._BILLBOARDMODE_Z;
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8435. get: function () {
  8436. return AbstractMesh._BILLBOARDMODE_ALL;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8442. set: function (callback) {
  8443. if (this._onCollideObserver) {
  8444. this.onCollideObservable.remove(this._onCollideObserver);
  8445. }
  8446. this._onCollideObserver = this.onCollideObservable.add(callback);
  8447. },
  8448. enumerable: true,
  8449. configurable: true
  8450. });
  8451. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8452. set: function (callback) {
  8453. if (this._onCollisionPositionChangeObserver) {
  8454. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8455. }
  8456. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8457. },
  8458. enumerable: true,
  8459. configurable: true
  8460. });
  8461. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8462. get: function () {
  8463. return this._skeleton;
  8464. },
  8465. set: function (value) {
  8466. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8467. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8468. }
  8469. if (value && value.needInitialSkinMatrix) {
  8470. value._registerMeshWithPoseMatrix(this);
  8471. }
  8472. this._skeleton = value;
  8473. if (!this._skeleton) {
  8474. this._bonesTransformMatrices = null;
  8475. }
  8476. },
  8477. enumerable: true,
  8478. configurable: true
  8479. });
  8480. /**
  8481. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8482. */
  8483. AbstractMesh.prototype.toString = function (fullDetails) {
  8484. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8485. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8486. if (this._skeleton) {
  8487. ret += ", skeleton: " + this._skeleton.name;
  8488. }
  8489. if (fullDetails) {
  8490. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8491. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8492. }
  8493. return ret;
  8494. };
  8495. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8496. /**
  8497. * Getting the rotation object.
  8498. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8499. */
  8500. get: function () {
  8501. return this._rotation;
  8502. },
  8503. set: function (newRotation) {
  8504. this._rotation = newRotation;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8510. get: function () {
  8511. return this._scaling;
  8512. },
  8513. set: function (newScaling) {
  8514. this._scaling = newScaling;
  8515. if (this.physicsImpostor) {
  8516. this.physicsImpostor.forceUpdate();
  8517. }
  8518. },
  8519. enumerable: true,
  8520. configurable: true
  8521. });
  8522. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8523. get: function () {
  8524. return this._rotationQuaternion;
  8525. },
  8526. set: function (quaternion) {
  8527. this._rotationQuaternion = quaternion;
  8528. //reset the rotation vector.
  8529. if (quaternion && this.rotation.length()) {
  8530. this.rotation.copyFromFloats(0, 0, 0);
  8531. }
  8532. },
  8533. enumerable: true,
  8534. configurable: true
  8535. });
  8536. // Methods
  8537. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8538. this._poseMatrix.copyFrom(matrix);
  8539. };
  8540. AbstractMesh.prototype.getPoseMatrix = function () {
  8541. return this._poseMatrix;
  8542. };
  8543. AbstractMesh.prototype.disableEdgesRendering = function () {
  8544. if (this._edgesRenderer !== undefined) {
  8545. this._edgesRenderer.dispose();
  8546. this._edgesRenderer = undefined;
  8547. }
  8548. };
  8549. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8550. if (epsilon === void 0) { epsilon = 0.95; }
  8551. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8552. this.disableEdgesRendering();
  8553. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8554. };
  8555. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8556. get: function () {
  8557. return false;
  8558. },
  8559. enumerable: true,
  8560. configurable: true
  8561. });
  8562. AbstractMesh.prototype.getLOD = function (camera) {
  8563. return this;
  8564. };
  8565. AbstractMesh.prototype.getTotalVertices = function () {
  8566. return 0;
  8567. };
  8568. AbstractMesh.prototype.getIndices = function () {
  8569. return null;
  8570. };
  8571. AbstractMesh.prototype.getVerticesData = function (kind) {
  8572. return null;
  8573. };
  8574. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8575. return false;
  8576. };
  8577. AbstractMesh.prototype.getBoundingInfo = function () {
  8578. if (this._masterMesh) {
  8579. return this._masterMesh.getBoundingInfo();
  8580. }
  8581. if (!this._boundingInfo) {
  8582. this._updateBoundingInfo();
  8583. }
  8584. return this._boundingInfo;
  8585. };
  8586. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8587. get: function () {
  8588. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8589. },
  8590. enumerable: true,
  8591. configurable: true
  8592. });
  8593. AbstractMesh.prototype._preActivate = function () {
  8594. };
  8595. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8596. };
  8597. AbstractMesh.prototype._activate = function (renderId) {
  8598. this._renderId = renderId;
  8599. };
  8600. AbstractMesh.prototype.getWorldMatrix = function () {
  8601. if (this._masterMesh) {
  8602. return this._masterMesh.getWorldMatrix();
  8603. }
  8604. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8605. this.computeWorldMatrix();
  8606. }
  8607. return this._worldMatrix;
  8608. };
  8609. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8610. get: function () {
  8611. return this._worldMatrix;
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8617. get: function () {
  8618. return this._absolutePosition;
  8619. },
  8620. enumerable: true,
  8621. configurable: true
  8622. });
  8623. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8624. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8625. this.computeWorldMatrix(true);
  8626. this._isWorldMatrixFrozen = true;
  8627. };
  8628. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8629. this._isWorldMatrixFrozen = false;
  8630. this.computeWorldMatrix(true);
  8631. };
  8632. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8633. get: function () {
  8634. return this._isWorldMatrixFrozen;
  8635. },
  8636. enumerable: true,
  8637. configurable: true
  8638. });
  8639. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8640. axis.normalize();
  8641. if (!this.rotationQuaternion) {
  8642. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8643. this.rotation = BABYLON.Vector3.Zero();
  8644. }
  8645. var rotationQuaternion;
  8646. if (!space || space === BABYLON.Space.LOCAL) {
  8647. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8648. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8649. }
  8650. else {
  8651. if (this.parent) {
  8652. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8653. invertParentWorldMatrix.invert();
  8654. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8655. }
  8656. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8657. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8658. }
  8659. };
  8660. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8661. var displacementVector = axis.scale(distance);
  8662. if (!space || space === BABYLON.Space.LOCAL) {
  8663. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8664. this.setPositionWithLocalVector(tempV3);
  8665. }
  8666. else {
  8667. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8668. }
  8669. };
  8670. AbstractMesh.prototype.getAbsolutePosition = function () {
  8671. this.computeWorldMatrix();
  8672. return this._absolutePosition;
  8673. };
  8674. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8675. if (!absolutePosition) {
  8676. return;
  8677. }
  8678. var absolutePositionX;
  8679. var absolutePositionY;
  8680. var absolutePositionZ;
  8681. if (absolutePosition.x === undefined) {
  8682. if (arguments.length < 3) {
  8683. return;
  8684. }
  8685. absolutePositionX = arguments[0];
  8686. absolutePositionY = arguments[1];
  8687. absolutePositionZ = arguments[2];
  8688. }
  8689. else {
  8690. absolutePositionX = absolutePosition.x;
  8691. absolutePositionY = absolutePosition.y;
  8692. absolutePositionZ = absolutePosition.z;
  8693. }
  8694. if (this.parent) {
  8695. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8696. invertParentWorldMatrix.invert();
  8697. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8698. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8699. }
  8700. else {
  8701. this.position.x = absolutePositionX;
  8702. this.position.y = absolutePositionY;
  8703. this.position.z = absolutePositionZ;
  8704. }
  8705. };
  8706. // ================================== Point of View Movement =================================
  8707. /**
  8708. * Perform relative position change from the point of view of behind the front of the mesh.
  8709. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8710. * Supports definition of mesh facing forward or backward.
  8711. * @param {number} amountRight
  8712. * @param {number} amountUp
  8713. * @param {number} amountForward
  8714. */
  8715. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8716. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8717. };
  8718. /**
  8719. * Calculate relative position change from the point of view of behind the front of the mesh.
  8720. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8721. * Supports definition of mesh facing forward or backward.
  8722. * @param {number} amountRight
  8723. * @param {number} amountUp
  8724. * @param {number} amountForward
  8725. */
  8726. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8727. var rotMatrix = new BABYLON.Matrix();
  8728. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8729. rotQuaternion.toRotationMatrix(rotMatrix);
  8730. var translationDelta = BABYLON.Vector3.Zero();
  8731. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8732. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8733. return translationDelta;
  8734. };
  8735. // ================================== Point of View Rotation =================================
  8736. /**
  8737. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8738. * Supports definition of mesh facing forward or backward.
  8739. * @param {number} flipBack
  8740. * @param {number} twirlClockwise
  8741. * @param {number} tiltRight
  8742. */
  8743. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8744. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8745. };
  8746. /**
  8747. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8748. * Supports definition of mesh facing forward or backward.
  8749. * @param {number} flipBack
  8750. * @param {number} twirlClockwise
  8751. * @param {number} tiltRight
  8752. */
  8753. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8754. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8755. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8756. };
  8757. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8758. this._pivotMatrix = matrix;
  8759. this._cache.pivotMatrixUpdated = true;
  8760. };
  8761. AbstractMesh.prototype.getPivotMatrix = function () {
  8762. return this._pivotMatrix;
  8763. };
  8764. AbstractMesh.prototype._isSynchronized = function () {
  8765. if (this._isDirty) {
  8766. return false;
  8767. }
  8768. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8769. return false;
  8770. if (this._cache.pivotMatrixUpdated) {
  8771. return false;
  8772. }
  8773. if (this.infiniteDistance) {
  8774. return false;
  8775. }
  8776. if (!this._cache.position.equals(this.position))
  8777. return false;
  8778. if (this.rotationQuaternion) {
  8779. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8780. return false;
  8781. }
  8782. else {
  8783. if (!this._cache.rotation.equals(this.rotation))
  8784. return false;
  8785. }
  8786. if (!this._cache.scaling.equals(this.scaling))
  8787. return false;
  8788. return true;
  8789. };
  8790. AbstractMesh.prototype._initCache = function () {
  8791. _super.prototype._initCache.call(this);
  8792. this._cache.localMatrixUpdated = false;
  8793. this._cache.position = BABYLON.Vector3.Zero();
  8794. this._cache.scaling = BABYLON.Vector3.Zero();
  8795. this._cache.rotation = BABYLON.Vector3.Zero();
  8796. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8797. this._cache.billboardMode = -1;
  8798. };
  8799. AbstractMesh.prototype.markAsDirty = function (property) {
  8800. if (property === "rotation") {
  8801. this.rotationQuaternion = null;
  8802. }
  8803. this._currentRenderId = Number.MAX_VALUE;
  8804. this._isDirty = true;
  8805. };
  8806. AbstractMesh.prototype._updateBoundingInfo = function () {
  8807. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8808. this._boundingInfo.update(this.worldMatrixFromCache);
  8809. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8810. };
  8811. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8812. if (!this.subMeshes) {
  8813. return;
  8814. }
  8815. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8816. var subMesh = this.subMeshes[subIndex];
  8817. if (!subMesh.IsGlobal) {
  8818. subMesh.updateBoundingInfo(matrix);
  8819. }
  8820. }
  8821. };
  8822. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8823. if (this._isWorldMatrixFrozen) {
  8824. return this._worldMatrix;
  8825. }
  8826. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8827. this._currentRenderId = this.getScene().getRenderId();
  8828. return this._worldMatrix;
  8829. }
  8830. this._cache.position.copyFrom(this.position);
  8831. this._cache.scaling.copyFrom(this.scaling);
  8832. this._cache.pivotMatrixUpdated = false;
  8833. this._cache.billboardMode = this.billboardMode;
  8834. this._currentRenderId = this.getScene().getRenderId();
  8835. this._isDirty = false;
  8836. // Scaling
  8837. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8838. // Rotation
  8839. //rotate, if quaternion is set and rotation was used
  8840. if (this.rotationQuaternion) {
  8841. var len = this.rotation.length();
  8842. if (len) {
  8843. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8844. this.rotation.copyFromFloats(0, 0, 0);
  8845. }
  8846. }
  8847. if (this.rotationQuaternion) {
  8848. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8849. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8850. }
  8851. else {
  8852. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8853. this._cache.rotation.copyFrom(this.rotation);
  8854. }
  8855. // Translation
  8856. if (this.infiniteDistance && !this.parent) {
  8857. var camera = this.getScene().activeCamera;
  8858. if (camera) {
  8859. var cameraWorldMatrix = camera.getWorldMatrix();
  8860. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8861. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8862. }
  8863. }
  8864. else {
  8865. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8866. }
  8867. // Composing transformations
  8868. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8869. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8870. // Billboarding
  8871. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8872. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8873. var localPosition = BABYLON.Tmp.Vector3[0];
  8874. if (this.parent && this.parent.getWorldMatrix) {
  8875. this._markSyncedWithParent();
  8876. var parentMatrix;
  8877. if (this._meshToBoneReferal) {
  8878. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8879. parentMatrix = BABYLON.Tmp.Matrix[6];
  8880. }
  8881. else {
  8882. parentMatrix = this.parent.getWorldMatrix();
  8883. }
  8884. BABYLON.Vector3.TransformCoordinatesToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  8885. localPosition = BABYLON.Tmp.Vector3[1];
  8886. }
  8887. var zero = this.getScene().activeCamera.globalPosition.clone();
  8888. if (this.parent && this.parent.position) {
  8889. localPosition.addInPlace(this.parent.position);
  8890. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8891. }
  8892. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8893. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8894. zero.x = localPosition.x + BABYLON.Epsilon;
  8895. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8896. zero.y = localPosition.y + BABYLON.Epsilon;
  8897. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8898. zero.z = localPosition.z + BABYLON.Epsilon;
  8899. }
  8900. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8901. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8902. BABYLON.Tmp.Matrix[3].invert();
  8903. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8904. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8905. }
  8906. // Local world
  8907. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8908. // Parent
  8909. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8910. this._markSyncedWithParent();
  8911. if (this._meshToBoneReferal) {
  8912. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8913. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8914. }
  8915. else {
  8916. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8917. }
  8918. }
  8919. else {
  8920. this._worldMatrix.copyFrom(this._localWorld);
  8921. }
  8922. // Bounding info
  8923. this._updateBoundingInfo();
  8924. // Absolute position
  8925. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8926. // Callbacks
  8927. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  8928. if (!this._poseMatrix) {
  8929. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8930. }
  8931. return this._worldMatrix;
  8932. };
  8933. /**
  8934. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8935. * @param func: callback function to add
  8936. */
  8937. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8938. this.onAfterWorldMatrixUpdateObservable.add(func);
  8939. };
  8940. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8941. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  8942. };
  8943. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8944. this.computeWorldMatrix();
  8945. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8946. };
  8947. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8948. this.computeWorldMatrix();
  8949. var invLocalWorldMatrix = this._localWorld.clone();
  8950. invLocalWorldMatrix.invert();
  8951. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8952. };
  8953. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8954. this.computeWorldMatrix(true);
  8955. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8956. };
  8957. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8958. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8959. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8960. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8961. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8962. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8963. /// <returns>Mesh oriented towards targetMesh</returns>
  8964. yawCor = yawCor || 0; // default to zero if undefined
  8965. pitchCor = pitchCor || 0;
  8966. rollCor = rollCor || 0;
  8967. var dv = targetPoint.subtract(this.position);
  8968. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8969. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8970. var pitch = Math.atan2(dv.y, len);
  8971. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8972. };
  8973. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8974. this._meshToBoneReferal = affectedMesh;
  8975. this.parent = bone;
  8976. if (bone.getWorldMatrix().determinant() < 0) {
  8977. this.scalingDeterminant *= -1;
  8978. }
  8979. };
  8980. AbstractMesh.prototype.detachFromBone = function () {
  8981. if (this.parent.getWorldMatrix().determinant() < 0) {
  8982. this.scalingDeterminant *= -1;
  8983. }
  8984. this._meshToBoneReferal = null;
  8985. this.parent = null;
  8986. };
  8987. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8988. return this._boundingInfo.isInFrustum(frustumPlanes);
  8989. };
  8990. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8991. if (!camera) {
  8992. camera = this.getScene().activeCamera;
  8993. }
  8994. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8995. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8996. return false;
  8997. }
  8998. return true;
  8999. };
  9000. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9001. if (!this._boundingInfo || !mesh._boundingInfo) {
  9002. return false;
  9003. }
  9004. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9005. };
  9006. AbstractMesh.prototype.intersectsPoint = function (point) {
  9007. if (!this._boundingInfo) {
  9008. return false;
  9009. }
  9010. return this._boundingInfo.intersectsPoint(point);
  9011. };
  9012. // Physics
  9013. /**
  9014. * @Deprecated. Use new PhysicsImpostor instead.
  9015. * */
  9016. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9017. //legacy support
  9018. if (impostor.impostor) {
  9019. options = impostor;
  9020. impostor = impostor.impostor;
  9021. }
  9022. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9023. return this.physicsImpostor.physicsBody;
  9024. };
  9025. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9026. return this.physicsImpostor;
  9027. };
  9028. /**
  9029. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9030. */
  9031. AbstractMesh.prototype.getPhysicsMass = function () {
  9032. return this.physicsImpostor.getParam("mass");
  9033. };
  9034. /**
  9035. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9036. */
  9037. AbstractMesh.prototype.getPhysicsFriction = function () {
  9038. return this.physicsImpostor.getParam("friction");
  9039. };
  9040. /**
  9041. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9042. */
  9043. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9044. return this.physicsImpostor.getParam("resitution");
  9045. };
  9046. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9047. if (!camera) {
  9048. camera = this.getScene().activeCamera;
  9049. }
  9050. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9051. };
  9052. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9053. if (!camera) {
  9054. camera = this.getScene().activeCamera;
  9055. }
  9056. return this.absolutePosition.subtract(camera.position).length();
  9057. };
  9058. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9059. if (!this.physicsImpostor) {
  9060. return;
  9061. }
  9062. this.physicsImpostor.applyImpulse(force, contactPoint);
  9063. };
  9064. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9065. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9066. return;
  9067. }
  9068. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9069. mainPivot: pivot1,
  9070. connectedPivot: pivot2,
  9071. nativeParams: options
  9072. });
  9073. };
  9074. /**
  9075. * @Deprecated
  9076. */
  9077. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9078. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9079. this.updatePhysicsBody();
  9080. };
  9081. /**
  9082. * @Deprecated
  9083. * Calling this function is not needed anymore.
  9084. * The physics engine takes care of transofmration automatically.
  9085. */
  9086. AbstractMesh.prototype.updatePhysicsBody = function () {
  9087. //Unneeded
  9088. };
  9089. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9090. // Collisions
  9091. get: function () {
  9092. return this._checkCollisions;
  9093. },
  9094. set: function (collisionEnabled) {
  9095. this._checkCollisions = collisionEnabled;
  9096. if (this.getScene().workerCollisions) {
  9097. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9098. }
  9099. },
  9100. enumerable: true,
  9101. configurable: true
  9102. });
  9103. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9104. var globalPosition = this.getAbsolutePosition();
  9105. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9106. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9107. this._collider.radius = this.ellipsoid;
  9108. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9109. };
  9110. // Submeshes octree
  9111. /**
  9112. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9113. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9114. */
  9115. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9116. if (maxCapacity === void 0) { maxCapacity = 64; }
  9117. if (maxDepth === void 0) { maxDepth = 2; }
  9118. if (!this._submeshesOctree) {
  9119. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9120. }
  9121. this.computeWorldMatrix(true);
  9122. // Update octree
  9123. var bbox = this.getBoundingInfo().boundingBox;
  9124. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9125. return this._submeshesOctree;
  9126. };
  9127. // Collisions
  9128. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9129. this._generatePointsArray();
  9130. // Transformation
  9131. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9132. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9133. subMesh._lastColliderWorldVertices = [];
  9134. subMesh._trianglePlanes = [];
  9135. var start = subMesh.verticesStart;
  9136. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9137. for (var i = start; i < end; i++) {
  9138. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9139. }
  9140. }
  9141. // Collide
  9142. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9143. if (collider.collisionFound) {
  9144. collider.collidedMesh = this;
  9145. }
  9146. };
  9147. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9148. var subMeshes;
  9149. var len;
  9150. // Octrees
  9151. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9152. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9153. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9154. len = intersections.length;
  9155. subMeshes = intersections.data;
  9156. }
  9157. else {
  9158. subMeshes = this.subMeshes;
  9159. len = subMeshes.length;
  9160. }
  9161. for (var index = 0; index < len; index++) {
  9162. var subMesh = subMeshes[index];
  9163. // Bounding test
  9164. if (len > 1 && !subMesh._checkCollision(collider))
  9165. continue;
  9166. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9167. }
  9168. };
  9169. AbstractMesh.prototype._checkCollision = function (collider) {
  9170. // Bounding box test
  9171. if (!this._boundingInfo._checkCollision(collider))
  9172. return;
  9173. // Transformation matrix
  9174. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9175. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9176. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9177. };
  9178. // Picking
  9179. AbstractMesh.prototype._generatePointsArray = function () {
  9180. return false;
  9181. };
  9182. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9183. var pickingInfo = new BABYLON.PickingInfo();
  9184. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9185. return pickingInfo;
  9186. }
  9187. if (!this._generatePointsArray()) {
  9188. return pickingInfo;
  9189. }
  9190. var intersectInfo = null;
  9191. // Octrees
  9192. var subMeshes;
  9193. var len;
  9194. if (this._submeshesOctree && this.useOctreeForPicking) {
  9195. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9196. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9197. len = intersections.length;
  9198. subMeshes = intersections.data;
  9199. }
  9200. else {
  9201. subMeshes = this.subMeshes;
  9202. len = subMeshes.length;
  9203. }
  9204. for (var index = 0; index < len; index++) {
  9205. var subMesh = subMeshes[index];
  9206. // Bounding test
  9207. if (len > 1 && !subMesh.canIntersects(ray))
  9208. continue;
  9209. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9210. if (currentIntersectInfo) {
  9211. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9212. intersectInfo = currentIntersectInfo;
  9213. intersectInfo.subMeshId = index;
  9214. if (fastCheck) {
  9215. break;
  9216. }
  9217. }
  9218. }
  9219. }
  9220. if (intersectInfo) {
  9221. // Get picked point
  9222. var world = this.getWorldMatrix();
  9223. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9224. var direction = ray.direction.clone();
  9225. direction = direction.scale(intersectInfo.distance);
  9226. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9227. var pickedPoint = worldOrigin.add(worldDirection);
  9228. // Return result
  9229. pickingInfo.hit = true;
  9230. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9231. pickingInfo.pickedPoint = pickedPoint;
  9232. pickingInfo.pickedMesh = this;
  9233. pickingInfo.bu = intersectInfo.bu;
  9234. pickingInfo.bv = intersectInfo.bv;
  9235. pickingInfo.faceId = intersectInfo.faceId;
  9236. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9237. return pickingInfo;
  9238. }
  9239. return pickingInfo;
  9240. };
  9241. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9242. return null;
  9243. };
  9244. AbstractMesh.prototype.releaseSubMeshes = function () {
  9245. if (this.subMeshes) {
  9246. while (this.subMeshes.length) {
  9247. this.subMeshes[0].dispose();
  9248. }
  9249. }
  9250. else {
  9251. this.subMeshes = new Array();
  9252. }
  9253. };
  9254. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9255. var _this = this;
  9256. var index;
  9257. // Action manager
  9258. if (this.actionManager) {
  9259. this.actionManager.dispose();
  9260. this.actionManager = null;
  9261. }
  9262. // Skeleton
  9263. this.skeleton = null;
  9264. // Animations
  9265. this.getScene().stopAnimation(this);
  9266. // Physics
  9267. if (this.physicsImpostor) {
  9268. this.physicsImpostor.dispose();
  9269. }
  9270. // Intersections in progress
  9271. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9272. var other = this._intersectionsInProgress[index];
  9273. var pos = other._intersectionsInProgress.indexOf(this);
  9274. other._intersectionsInProgress.splice(pos, 1);
  9275. }
  9276. this._intersectionsInProgress = [];
  9277. // Lights
  9278. var lights = this.getScene().lights;
  9279. lights.forEach(function (light) {
  9280. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9281. if (meshIndex !== -1) {
  9282. light.includedOnlyMeshes.splice(meshIndex, 1);
  9283. }
  9284. meshIndex = light.excludedMeshes.indexOf(_this);
  9285. if (meshIndex !== -1) {
  9286. light.excludedMeshes.splice(meshIndex, 1);
  9287. }
  9288. });
  9289. // Edges
  9290. if (this._edgesRenderer) {
  9291. this._edgesRenderer.dispose();
  9292. this._edgesRenderer = null;
  9293. }
  9294. // SubMeshes
  9295. this.releaseSubMeshes();
  9296. // Remove from scene
  9297. this.getScene().removeMesh(this);
  9298. if (!doNotRecurse) {
  9299. // Particles
  9300. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9301. if (this.getScene().particleSystems[index].emitter === this) {
  9302. this.getScene().particleSystems[index].dispose();
  9303. index--;
  9304. }
  9305. }
  9306. // Children
  9307. var objects = this.getDescendants(true);
  9308. for (index = 0; index < objects.length; index++) {
  9309. objects[index].dispose();
  9310. }
  9311. }
  9312. else {
  9313. var childMeshes = this.getChildMeshes(true);
  9314. for (index = 0; index < childMeshes.length; index++) {
  9315. var child = childMeshes[index];
  9316. child.parent = null;
  9317. child.computeWorldMatrix(true);
  9318. }
  9319. }
  9320. _super.prototype.dispose.call(this);
  9321. this.onAfterWorldMatrixUpdateObservable.clear();
  9322. this._isDisposed = true;
  9323. // Callback
  9324. if (this.onDispose) {
  9325. this.onDispose();
  9326. }
  9327. };
  9328. // Statics
  9329. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9330. AbstractMesh._BILLBOARDMODE_X = 1;
  9331. AbstractMesh._BILLBOARDMODE_Y = 2;
  9332. AbstractMesh._BILLBOARDMODE_Z = 4;
  9333. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9334. return AbstractMesh;
  9335. }(BABYLON.Node));
  9336. BABYLON.AbstractMesh = AbstractMesh;
  9337. })(BABYLON || (BABYLON = {}));
  9338. var BABYLON;
  9339. (function (BABYLON) {
  9340. var Light = (function (_super) {
  9341. __extends(Light, _super);
  9342. function Light(name, scene) {
  9343. _super.call(this, name, scene);
  9344. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9345. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9346. this.intensity = 1.0;
  9347. this.range = Number.MAX_VALUE;
  9348. this.includeOnlyWithLayerMask = 0;
  9349. this.includedOnlyMeshes = new Array();
  9350. this.excludedMeshes = new Array();
  9351. this.excludeWithLayerMask = 0;
  9352. // PBR Properties.
  9353. this.radius = 0.00001;
  9354. this._excludedMeshesIds = new Array();
  9355. this._includedOnlyMeshesIds = new Array();
  9356. scene.addLight(this);
  9357. }
  9358. /**
  9359. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9360. */
  9361. Light.prototype.toString = function (fullDetails) {
  9362. var ret = "Name: " + this.name;
  9363. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9364. if (this.animations) {
  9365. for (var i = 0; i < this.animations.length; i++) {
  9366. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9367. }
  9368. }
  9369. if (fullDetails) {
  9370. }
  9371. return ret;
  9372. };
  9373. Light.prototype.getShadowGenerator = function () {
  9374. return this._shadowGenerator;
  9375. };
  9376. Light.prototype.getAbsolutePosition = function () {
  9377. return BABYLON.Vector3.Zero();
  9378. };
  9379. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9380. };
  9381. Light.prototype._getWorldMatrix = function () {
  9382. return BABYLON.Matrix.Identity();
  9383. };
  9384. Light.prototype.canAffectMesh = function (mesh) {
  9385. if (!mesh) {
  9386. return true;
  9387. }
  9388. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9389. return false;
  9390. }
  9391. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9392. return false;
  9393. }
  9394. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9395. return false;
  9396. }
  9397. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9398. return false;
  9399. }
  9400. return true;
  9401. };
  9402. Light.prototype.getWorldMatrix = function () {
  9403. this._currentRenderId = this.getScene().getRenderId();
  9404. var worldMatrix = this._getWorldMatrix();
  9405. if (this.parent && this.parent.getWorldMatrix) {
  9406. if (!this._parentedWorldMatrix) {
  9407. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9408. }
  9409. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9410. this._markSyncedWithParent();
  9411. return this._parentedWorldMatrix;
  9412. }
  9413. return worldMatrix;
  9414. };
  9415. Light.prototype.dispose = function () {
  9416. if (this._shadowGenerator) {
  9417. this._shadowGenerator.dispose();
  9418. this._shadowGenerator = null;
  9419. }
  9420. // Animations
  9421. this.getScene().stopAnimation(this);
  9422. // Remove from scene
  9423. this.getScene().removeLight(this);
  9424. _super.prototype.dispose.call(this);
  9425. };
  9426. Light.prototype.getTypeID = function () {
  9427. return 0;
  9428. };
  9429. Light.prototype.clone = function (name) {
  9430. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9431. };
  9432. Light.prototype.serialize = function () {
  9433. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9434. // Type
  9435. serializationObject.type = this.getTypeID();
  9436. // Parent
  9437. if (this.parent) {
  9438. serializationObject.parentId = this.parent.id;
  9439. }
  9440. // Inclusion / exclusions
  9441. if (this.excludedMeshes.length > 0) {
  9442. serializationObject.excludedMeshesIds = [];
  9443. this.excludedMeshes.forEach(function (mesh) {
  9444. serializationObject.excludedMeshesIds.push(mesh.id);
  9445. });
  9446. }
  9447. if (this.includedOnlyMeshes.length > 0) {
  9448. serializationObject.includedOnlyMeshesIds = [];
  9449. this.includedOnlyMeshes.forEach(function (mesh) {
  9450. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9451. });
  9452. }
  9453. // Animations
  9454. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9455. serializationObject.ranges = this.serializeAnimationRanges();
  9456. return serializationObject;
  9457. };
  9458. Light.GetConstructorFromName = function (type, name, scene) {
  9459. switch (type) {
  9460. case 0:
  9461. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9462. case 1:
  9463. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9464. case 2:
  9465. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9466. case 3:
  9467. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9468. }
  9469. };
  9470. Light.Parse = function (parsedLight, scene) {
  9471. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9472. // Inclusion / exclusions
  9473. if (parsedLight.excludedMeshesIds) {
  9474. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9475. }
  9476. if (parsedLight.includedOnlyMeshesIds) {
  9477. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9478. }
  9479. // Parent
  9480. if (parsedLight.parentId) {
  9481. light._waitingParentId = parsedLight.parentId;
  9482. }
  9483. // Animations
  9484. if (parsedLight.animations) {
  9485. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9486. var parsedAnimation = parsedLight.animations[animationIndex];
  9487. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9488. }
  9489. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9490. }
  9491. if (parsedLight.autoAnimate) {
  9492. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9493. }
  9494. return light;
  9495. };
  9496. __decorate([
  9497. BABYLON.serializeAsColor3()
  9498. ], Light.prototype, "diffuse", void 0);
  9499. __decorate([
  9500. BABYLON.serializeAsColor3()
  9501. ], Light.prototype, "specular", void 0);
  9502. __decorate([
  9503. BABYLON.serialize()
  9504. ], Light.prototype, "intensity", void 0);
  9505. __decorate([
  9506. BABYLON.serialize()
  9507. ], Light.prototype, "range", void 0);
  9508. __decorate([
  9509. BABYLON.serialize()
  9510. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9511. __decorate([
  9512. BABYLON.serialize()
  9513. ], Light.prototype, "excludeWithLayerMask", void 0);
  9514. __decorate([
  9515. BABYLON.serialize()
  9516. ], Light.prototype, "radius", void 0);
  9517. return Light;
  9518. }(BABYLON.Node));
  9519. BABYLON.Light = Light;
  9520. })(BABYLON || (BABYLON = {}));
  9521. var BABYLON;
  9522. (function (BABYLON) {
  9523. var PointLight = (function (_super) {
  9524. __extends(PointLight, _super);
  9525. function PointLight(name, position, scene) {
  9526. _super.call(this, name, scene);
  9527. this.position = position;
  9528. }
  9529. PointLight.prototype.getAbsolutePosition = function () {
  9530. return this.transformedPosition ? this.transformedPosition : this.position;
  9531. };
  9532. PointLight.prototype.computeTransformedPosition = function () {
  9533. if (this.parent && this.parent.getWorldMatrix) {
  9534. if (!this.transformedPosition) {
  9535. this.transformedPosition = BABYLON.Vector3.Zero();
  9536. }
  9537. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9538. return true;
  9539. }
  9540. return false;
  9541. };
  9542. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9543. if (this.parent && this.parent.getWorldMatrix) {
  9544. this.computeTransformedPosition();
  9545. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9546. return;
  9547. }
  9548. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9549. };
  9550. PointLight.prototype.needCube = function () {
  9551. return true;
  9552. };
  9553. PointLight.prototype.supportsVSM = function () {
  9554. return false;
  9555. };
  9556. PointLight.prototype.needRefreshPerFrame = function () {
  9557. return false;
  9558. };
  9559. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9560. switch (faceIndex) {
  9561. case 0:
  9562. return new BABYLON.Vector3(1, 0, 0);
  9563. case 1:
  9564. return new BABYLON.Vector3(-1, 0, 0);
  9565. case 2:
  9566. return new BABYLON.Vector3(0, -1, 0);
  9567. case 3:
  9568. return new BABYLON.Vector3(0, 1, 0);
  9569. case 4:
  9570. return new BABYLON.Vector3(0, 0, 1);
  9571. case 5:
  9572. return new BABYLON.Vector3(0, 0, -1);
  9573. }
  9574. return BABYLON.Vector3.Zero();
  9575. };
  9576. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9577. var activeCamera = this.getScene().activeCamera;
  9578. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9579. };
  9580. PointLight.prototype._getWorldMatrix = function () {
  9581. if (!this._worldMatrix) {
  9582. this._worldMatrix = BABYLON.Matrix.Identity();
  9583. }
  9584. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9585. return this._worldMatrix;
  9586. };
  9587. PointLight.prototype.getTypeID = function () {
  9588. return 0;
  9589. };
  9590. __decorate([
  9591. BABYLON.serializeAsVector3()
  9592. ], PointLight.prototype, "position", void 0);
  9593. return PointLight;
  9594. }(BABYLON.Light));
  9595. BABYLON.PointLight = PointLight;
  9596. })(BABYLON || (BABYLON = {}));
  9597. var BABYLON;
  9598. (function (BABYLON) {
  9599. var SpotLight = (function (_super) {
  9600. __extends(SpotLight, _super);
  9601. function SpotLight(name, position, direction, angle, exponent, scene) {
  9602. _super.call(this, name, scene);
  9603. this.position = position;
  9604. this.direction = direction;
  9605. this.angle = angle;
  9606. this.exponent = exponent;
  9607. }
  9608. SpotLight.prototype.getAbsolutePosition = function () {
  9609. return this.transformedPosition ? this.transformedPosition : this.position;
  9610. };
  9611. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9612. var activeCamera = this.getScene().activeCamera;
  9613. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9614. };
  9615. SpotLight.prototype.needCube = function () {
  9616. return false;
  9617. };
  9618. SpotLight.prototype.supportsVSM = function () {
  9619. return true;
  9620. };
  9621. SpotLight.prototype.needRefreshPerFrame = function () {
  9622. return false;
  9623. };
  9624. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9625. return this.direction;
  9626. };
  9627. SpotLight.prototype.setDirectionToTarget = function (target) {
  9628. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9629. return this.direction;
  9630. };
  9631. SpotLight.prototype.computeTransformedPosition = function () {
  9632. if (this.parent && this.parent.getWorldMatrix) {
  9633. if (!this.transformedPosition) {
  9634. this.transformedPosition = BABYLON.Vector3.Zero();
  9635. }
  9636. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9637. return true;
  9638. }
  9639. return false;
  9640. };
  9641. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9642. var normalizeDirection;
  9643. if (this.parent && this.parent.getWorldMatrix) {
  9644. if (!this._transformedDirection) {
  9645. this._transformedDirection = BABYLON.Vector3.Zero();
  9646. }
  9647. this.computeTransformedPosition();
  9648. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9649. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9650. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9651. }
  9652. else {
  9653. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9654. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9655. }
  9656. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9657. };
  9658. SpotLight.prototype._getWorldMatrix = function () {
  9659. if (!this._worldMatrix) {
  9660. this._worldMatrix = BABYLON.Matrix.Identity();
  9661. }
  9662. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9663. return this._worldMatrix;
  9664. };
  9665. SpotLight.prototype.getTypeID = function () {
  9666. return 2;
  9667. };
  9668. __decorate([
  9669. BABYLON.serializeAsVector3()
  9670. ], SpotLight.prototype, "position", void 0);
  9671. __decorate([
  9672. BABYLON.serializeAsVector3()
  9673. ], SpotLight.prototype, "direction", void 0);
  9674. __decorate([
  9675. BABYLON.serialize()
  9676. ], SpotLight.prototype, "angle", void 0);
  9677. __decorate([
  9678. BABYLON.serialize()
  9679. ], SpotLight.prototype, "exponent", void 0);
  9680. return SpotLight;
  9681. }(BABYLON.Light));
  9682. BABYLON.SpotLight = SpotLight;
  9683. })(BABYLON || (BABYLON = {}));
  9684. var BABYLON;
  9685. (function (BABYLON) {
  9686. var HemisphericLight = (function (_super) {
  9687. __extends(HemisphericLight, _super);
  9688. function HemisphericLight(name, direction, scene) {
  9689. _super.call(this, name, scene);
  9690. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9691. this.direction = direction;
  9692. }
  9693. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9694. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9695. return this.direction;
  9696. };
  9697. HemisphericLight.prototype.getShadowGenerator = function () {
  9698. return null;
  9699. };
  9700. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9701. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9702. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9703. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9704. };
  9705. HemisphericLight.prototype._getWorldMatrix = function () {
  9706. if (!this._worldMatrix) {
  9707. this._worldMatrix = BABYLON.Matrix.Identity();
  9708. }
  9709. return this._worldMatrix;
  9710. };
  9711. HemisphericLight.prototype.getTypeID = function () {
  9712. return 3;
  9713. };
  9714. __decorate([
  9715. BABYLON.serializeAsColor3()
  9716. ], HemisphericLight.prototype, "groundColor", void 0);
  9717. __decorate([
  9718. BABYLON.serializeAsVector3()
  9719. ], HemisphericLight.prototype, "direction", void 0);
  9720. return HemisphericLight;
  9721. }(BABYLON.Light));
  9722. BABYLON.HemisphericLight = HemisphericLight;
  9723. })(BABYLON || (BABYLON = {}));
  9724. var BABYLON;
  9725. (function (BABYLON) {
  9726. var DirectionalLight = (function (_super) {
  9727. __extends(DirectionalLight, _super);
  9728. function DirectionalLight(name, direction, scene) {
  9729. _super.call(this, name, scene);
  9730. this.shadowOrthoScale = 0.5;
  9731. this.autoUpdateExtends = true;
  9732. // Cache
  9733. this._orthoLeft = Number.MAX_VALUE;
  9734. this._orthoRight = Number.MIN_VALUE;
  9735. this._orthoTop = Number.MIN_VALUE;
  9736. this._orthoBottom = Number.MAX_VALUE;
  9737. this.position = direction.scale(-1);
  9738. this.direction = direction;
  9739. }
  9740. DirectionalLight.prototype.getAbsolutePosition = function () {
  9741. return this.transformedPosition ? this.transformedPosition : this.position;
  9742. };
  9743. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9744. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9745. return this.direction;
  9746. };
  9747. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9748. var activeCamera = this.getScene().activeCamera;
  9749. // Check extends
  9750. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9751. var tempVector3 = BABYLON.Vector3.Zero();
  9752. this._orthoLeft = Number.MAX_VALUE;
  9753. this._orthoRight = Number.MIN_VALUE;
  9754. this._orthoTop = Number.MIN_VALUE;
  9755. this._orthoBottom = Number.MAX_VALUE;
  9756. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9757. var mesh = renderList[meshIndex];
  9758. if (!mesh) {
  9759. continue;
  9760. }
  9761. var boundingInfo = mesh.getBoundingInfo();
  9762. if (!boundingInfo) {
  9763. continue;
  9764. }
  9765. var boundingBox = boundingInfo.boundingBox;
  9766. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9767. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9768. if (tempVector3.x < this._orthoLeft)
  9769. this._orthoLeft = tempVector3.x;
  9770. if (tempVector3.y < this._orthoBottom)
  9771. this._orthoBottom = tempVector3.y;
  9772. if (tempVector3.x > this._orthoRight)
  9773. this._orthoRight = tempVector3.x;
  9774. if (tempVector3.y > this._orthoTop)
  9775. this._orthoTop = tempVector3.y;
  9776. }
  9777. }
  9778. }
  9779. var xOffset = this._orthoRight - this._orthoLeft;
  9780. var yOffset = this._orthoTop - this._orthoBottom;
  9781. 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);
  9782. };
  9783. DirectionalLight.prototype.supportsVSM = function () {
  9784. return true;
  9785. };
  9786. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9787. return true;
  9788. };
  9789. DirectionalLight.prototype.needCube = function () {
  9790. return false;
  9791. };
  9792. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9793. return this.direction;
  9794. };
  9795. DirectionalLight.prototype.computeTransformedPosition = function () {
  9796. if (this.parent && this.parent.getWorldMatrix) {
  9797. if (!this.transformedPosition) {
  9798. this.transformedPosition = BABYLON.Vector3.Zero();
  9799. }
  9800. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9801. return true;
  9802. }
  9803. return false;
  9804. };
  9805. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9806. if (this.parent && this.parent.getWorldMatrix) {
  9807. if (!this._transformedDirection) {
  9808. this._transformedDirection = BABYLON.Vector3.Zero();
  9809. }
  9810. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9811. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9812. return;
  9813. }
  9814. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9815. };
  9816. DirectionalLight.prototype._getWorldMatrix = function () {
  9817. if (!this._worldMatrix) {
  9818. this._worldMatrix = BABYLON.Matrix.Identity();
  9819. }
  9820. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9821. return this._worldMatrix;
  9822. };
  9823. DirectionalLight.prototype.getTypeID = function () {
  9824. return 1;
  9825. };
  9826. __decorate([
  9827. BABYLON.serializeAsVector3()
  9828. ], DirectionalLight.prototype, "position", void 0);
  9829. __decorate([
  9830. BABYLON.serializeAsVector3()
  9831. ], DirectionalLight.prototype, "direction", void 0);
  9832. __decorate([
  9833. BABYLON.serialize()
  9834. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9835. __decorate([
  9836. BABYLON.serialize()
  9837. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9838. return DirectionalLight;
  9839. }(BABYLON.Light));
  9840. BABYLON.DirectionalLight = DirectionalLight;
  9841. })(BABYLON || (BABYLON = {}));
  9842. var BABYLON;
  9843. (function (BABYLON) {
  9844. var ShadowGenerator = (function () {
  9845. function ShadowGenerator(mapSize, light) {
  9846. var _this = this;
  9847. // Members
  9848. this._filter = ShadowGenerator.FILTER_NONE;
  9849. this.blurScale = 2;
  9850. this._blurBoxOffset = 0;
  9851. this._bias = 0.00005;
  9852. this._lightDirection = BABYLON.Vector3.Zero();
  9853. this.forceBackFacesOnly = false;
  9854. this._darkness = 0;
  9855. this._transparencyShadow = false;
  9856. this._viewMatrix = BABYLON.Matrix.Zero();
  9857. this._projectionMatrix = BABYLON.Matrix.Zero();
  9858. this._transformMatrix = BABYLON.Matrix.Zero();
  9859. this._worldViewProjection = BABYLON.Matrix.Zero();
  9860. this._currentFaceIndex = 0;
  9861. this._currentFaceIndexCache = 0;
  9862. this._light = light;
  9863. this._scene = light.getScene();
  9864. this._mapSize = mapSize;
  9865. light._shadowGenerator = this;
  9866. // Render target
  9867. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9868. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9869. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9870. this._shadowMap.anisotropicFilteringLevel = 1;
  9871. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9872. this._shadowMap.renderParticles = false;
  9873. this._shadowMap.onBeforeRender = function (faceIndex) {
  9874. _this._currentFaceIndex = faceIndex;
  9875. };
  9876. this._shadowMap.onAfterUnbind = function () {
  9877. if (!_this.useBlurVarianceShadowMap) {
  9878. return;
  9879. }
  9880. if (!_this._shadowMap2) {
  9881. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9882. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9883. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9884. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9885. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9886. _this._downSamplePostprocess.onApply = function (effect) {
  9887. effect.setTexture("textureSampler", _this._shadowMap);
  9888. };
  9889. _this.blurBoxOffset = 1;
  9890. }
  9891. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9892. };
  9893. // Custom render function
  9894. var renderSubMesh = function (subMesh) {
  9895. var mesh = subMesh.getRenderingMesh();
  9896. var scene = _this._scene;
  9897. var engine = scene.getEngine();
  9898. // Culling
  9899. engine.setState(subMesh.getMaterial().backFaceCulling);
  9900. // Managing instances
  9901. var batch = mesh._getInstancesRenderList(subMesh._id);
  9902. if (batch.mustReturn) {
  9903. return;
  9904. }
  9905. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9906. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9907. engine.enableEffect(_this._effect);
  9908. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9909. var material = subMesh.getMaterial();
  9910. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9911. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9912. if (_this.getLight().needCube()) {
  9913. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9914. }
  9915. // Alpha test
  9916. if (material && material.needAlphaTesting()) {
  9917. var alphaTexture = material.getAlphaTestTexture();
  9918. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9919. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9920. }
  9921. // Bones
  9922. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9923. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9924. }
  9925. if (_this.forceBackFacesOnly) {
  9926. engine.setState(true, 0, false, true);
  9927. }
  9928. // Draw
  9929. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9930. if (_this.forceBackFacesOnly) {
  9931. engine.setState(true, 0, false, false);
  9932. }
  9933. }
  9934. else {
  9935. // Need to reset refresh rate of the shadowMap
  9936. _this._shadowMap.resetRefreshCounter();
  9937. }
  9938. };
  9939. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9940. var index;
  9941. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9942. renderSubMesh(opaqueSubMeshes.data[index]);
  9943. }
  9944. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9945. renderSubMesh(alphaTestSubMeshes.data[index]);
  9946. }
  9947. if (_this._transparencyShadow) {
  9948. for (index = 0; index < transparentSubMeshes.length; index++) {
  9949. renderSubMesh(transparentSubMeshes.data[index]);
  9950. }
  9951. }
  9952. };
  9953. this._shadowMap.onClear = function (engine) {
  9954. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9955. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9956. }
  9957. else {
  9958. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9959. }
  9960. };
  9961. }
  9962. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9963. // Static
  9964. get: function () {
  9965. return ShadowGenerator._FILTER_NONE;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9971. get: function () {
  9972. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9978. get: function () {
  9979. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9985. get: function () {
  9986. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9992. get: function () {
  9993. return this._bias;
  9994. },
  9995. set: function (bias) {
  9996. this._bias = bias;
  9997. },
  9998. enumerable: true,
  9999. configurable: true
  10000. });
  10001. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10002. get: function () {
  10003. return this._blurBoxOffset;
  10004. },
  10005. set: function (value) {
  10006. var _this = this;
  10007. if (this._blurBoxOffset === value) {
  10008. return;
  10009. }
  10010. this._blurBoxOffset = value;
  10011. if (this._boxBlurPostprocess) {
  10012. this._boxBlurPostprocess.dispose();
  10013. }
  10014. 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);
  10015. this._boxBlurPostprocess.onApply = function (effect) {
  10016. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10017. };
  10018. },
  10019. enumerable: true,
  10020. configurable: true
  10021. });
  10022. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10023. get: function () {
  10024. return this._filter;
  10025. },
  10026. set: function (value) {
  10027. if (this._filter === value) {
  10028. return;
  10029. }
  10030. this._filter = value;
  10031. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10032. this._shadowMap.anisotropicFilteringLevel = 16;
  10033. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10034. }
  10035. else {
  10036. this._shadowMap.anisotropicFilteringLevel = 1;
  10037. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10038. }
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10044. get: function () {
  10045. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10046. },
  10047. set: function (value) {
  10048. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10054. get: function () {
  10055. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10056. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10057. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10058. },
  10059. set: function (value) {
  10060. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10066. get: function () {
  10067. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10068. },
  10069. set: function (value) {
  10070. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10071. },
  10072. enumerable: true,
  10073. configurable: true
  10074. });
  10075. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10076. var defines = [];
  10077. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10078. defines.push("#define VSM");
  10079. }
  10080. if (this.getLight().needCube()) {
  10081. defines.push("#define CUBEMAP");
  10082. }
  10083. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10084. var mesh = subMesh.getMesh();
  10085. var material = subMesh.getMaterial();
  10086. // Alpha test
  10087. if (material && material.needAlphaTesting()) {
  10088. defines.push("#define ALPHATEST");
  10089. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10090. attribs.push(BABYLON.VertexBuffer.UVKind);
  10091. defines.push("#define UV1");
  10092. }
  10093. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10094. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10095. defines.push("#define UV2");
  10096. }
  10097. }
  10098. // Bones
  10099. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10100. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10101. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10102. if (mesh.numBoneInfluencers > 4) {
  10103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10105. }
  10106. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10107. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10108. }
  10109. else {
  10110. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10111. }
  10112. // Instances
  10113. if (useInstances) {
  10114. defines.push("#define INSTANCES");
  10115. attribs.push("world0");
  10116. attribs.push("world1");
  10117. attribs.push("world2");
  10118. attribs.push("world3");
  10119. }
  10120. // Get correct effect
  10121. var join = defines.join("\n");
  10122. if (this._cachedDefines !== join) {
  10123. this._cachedDefines = join;
  10124. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10125. }
  10126. return this._effect.isReady();
  10127. };
  10128. ShadowGenerator.prototype.getShadowMap = function () {
  10129. return this._shadowMap;
  10130. };
  10131. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10132. if (this._shadowMap2) {
  10133. return this._shadowMap2;
  10134. }
  10135. return this._shadowMap;
  10136. };
  10137. ShadowGenerator.prototype.getLight = function () {
  10138. return this._light;
  10139. };
  10140. // Methods
  10141. ShadowGenerator.prototype.getTransformMatrix = function () {
  10142. var scene = this._scene;
  10143. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10144. return this._transformMatrix;
  10145. }
  10146. this._currentRenderID = scene.getRenderId();
  10147. this._currentFaceIndexCache = this._currentFaceIndex;
  10148. var lightPosition = this._light.position;
  10149. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10150. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10151. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10152. }
  10153. if (this._light.computeTransformedPosition()) {
  10154. lightPosition = this._light.transformedPosition;
  10155. }
  10156. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10157. this._cachedPosition = lightPosition.clone();
  10158. this._cachedDirection = this._lightDirection.clone();
  10159. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10160. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10161. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10162. }
  10163. return this._transformMatrix;
  10164. };
  10165. ShadowGenerator.prototype.getDarkness = function () {
  10166. return this._darkness;
  10167. };
  10168. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10169. if (darkness >= 1.0)
  10170. this._darkness = 1.0;
  10171. else if (darkness <= 0.0)
  10172. this._darkness = 0.0;
  10173. else
  10174. this._darkness = darkness;
  10175. };
  10176. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10177. this._transparencyShadow = hasShadow;
  10178. };
  10179. ShadowGenerator.prototype._packHalf = function (depth) {
  10180. var scale = depth * 255.0;
  10181. var fract = scale - Math.floor(scale);
  10182. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10183. };
  10184. ShadowGenerator.prototype.dispose = function () {
  10185. this._shadowMap.dispose();
  10186. if (this._shadowMap2) {
  10187. this._shadowMap2.dispose();
  10188. }
  10189. if (this._downSamplePostprocess) {
  10190. this._downSamplePostprocess.dispose();
  10191. }
  10192. if (this._boxBlurPostprocess) {
  10193. this._boxBlurPostprocess.dispose();
  10194. }
  10195. };
  10196. ShadowGenerator.prototype.serialize = function () {
  10197. var serializationObject = {};
  10198. serializationObject.lightId = this._light.id;
  10199. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10200. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10201. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10202. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10203. serializationObject.renderList = [];
  10204. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10205. var mesh = this.getShadowMap().renderList[meshIndex];
  10206. serializationObject.renderList.push(mesh.id);
  10207. }
  10208. return serializationObject;
  10209. };
  10210. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10211. //casting to point light, as light is missing the position attr and typescript complains.
  10212. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10213. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10214. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10215. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  10216. shadowGenerator.getShadowMap().renderList.push(mesh);
  10217. }
  10218. if (parsedShadowGenerator.usePoissonSampling) {
  10219. shadowGenerator.usePoissonSampling = true;
  10220. }
  10221. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10222. shadowGenerator.useVarianceShadowMap = true;
  10223. }
  10224. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10225. shadowGenerator.useBlurVarianceShadowMap = true;
  10226. if (parsedShadowGenerator.blurScale) {
  10227. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10228. }
  10229. if (parsedShadowGenerator.blurBoxOffset) {
  10230. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10231. }
  10232. }
  10233. if (parsedShadowGenerator.bias !== undefined) {
  10234. shadowGenerator.bias = parsedShadowGenerator.bias;
  10235. }
  10236. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10237. return shadowGenerator;
  10238. };
  10239. ShadowGenerator._FILTER_NONE = 0;
  10240. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10241. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10242. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10243. return ShadowGenerator;
  10244. }());
  10245. BABYLON.ShadowGenerator = ShadowGenerator;
  10246. })(BABYLON || (BABYLON = {}));
  10247. var BABYLON;
  10248. (function (BABYLON) {
  10249. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10250. if (boxMin.x > sphereCenter.x + sphereRadius)
  10251. return false;
  10252. if (sphereCenter.x - sphereRadius > boxMax.x)
  10253. return false;
  10254. if (boxMin.y > sphereCenter.y + sphereRadius)
  10255. return false;
  10256. if (sphereCenter.y - sphereRadius > boxMax.y)
  10257. return false;
  10258. if (boxMin.z > sphereCenter.z + sphereRadius)
  10259. return false;
  10260. if (sphereCenter.z - sphereRadius > boxMax.z)
  10261. return false;
  10262. return true;
  10263. };
  10264. var getLowestRoot = function (a, b, c, maxR) {
  10265. var determinant = b * b - 4.0 * a * c;
  10266. var result = { root: 0, found: false };
  10267. if (determinant < 0)
  10268. return result;
  10269. var sqrtD = Math.sqrt(determinant);
  10270. var r1 = (-b - sqrtD) / (2.0 * a);
  10271. var r2 = (-b + sqrtD) / (2.0 * a);
  10272. if (r1 > r2) {
  10273. var temp = r2;
  10274. r2 = r1;
  10275. r1 = temp;
  10276. }
  10277. if (r1 > 0 && r1 < maxR) {
  10278. result.root = r1;
  10279. result.found = true;
  10280. return result;
  10281. }
  10282. if (r2 > 0 && r2 < maxR) {
  10283. result.root = r2;
  10284. result.found = true;
  10285. return result;
  10286. }
  10287. return result;
  10288. };
  10289. var Collider = (function () {
  10290. function Collider() {
  10291. this.radius = new BABYLON.Vector3(1, 1, 1);
  10292. this.retry = 0;
  10293. this.basePointWorld = BABYLON.Vector3.Zero();
  10294. this.velocityWorld = BABYLON.Vector3.Zero();
  10295. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10296. this._collisionPoint = BABYLON.Vector3.Zero();
  10297. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10298. this._tempVector = BABYLON.Vector3.Zero();
  10299. this._tempVector2 = BABYLON.Vector3.Zero();
  10300. this._tempVector3 = BABYLON.Vector3.Zero();
  10301. this._tempVector4 = BABYLON.Vector3.Zero();
  10302. this._edge = BABYLON.Vector3.Zero();
  10303. this._baseToVertex = BABYLON.Vector3.Zero();
  10304. this._destinationPoint = BABYLON.Vector3.Zero();
  10305. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10306. this._displacementVector = BABYLON.Vector3.Zero();
  10307. }
  10308. // Methods
  10309. Collider.prototype._initialize = function (source, dir, e) {
  10310. this.velocity = dir;
  10311. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10312. this.basePoint = source;
  10313. source.multiplyToRef(this.radius, this.basePointWorld);
  10314. dir.multiplyToRef(this.radius, this.velocityWorld);
  10315. this.velocityWorldLength = this.velocityWorld.length();
  10316. this.epsilon = e;
  10317. this.collisionFound = false;
  10318. };
  10319. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10320. pa.subtractToRef(point, this._tempVector);
  10321. pb.subtractToRef(point, this._tempVector2);
  10322. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10323. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10324. if (d < 0)
  10325. return false;
  10326. pc.subtractToRef(point, this._tempVector3);
  10327. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10328. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10329. if (d < 0)
  10330. return false;
  10331. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10332. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10333. return d >= 0;
  10334. };
  10335. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10336. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10337. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10338. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10339. return false;
  10340. }
  10341. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10342. return false;
  10343. return true;
  10344. };
  10345. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10346. var t0;
  10347. var embeddedInPlane = false;
  10348. //defensive programming, actually not needed.
  10349. if (!trianglePlaneArray) {
  10350. trianglePlaneArray = [];
  10351. }
  10352. if (!trianglePlaneArray[faceIndex]) {
  10353. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10354. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10355. }
  10356. var trianglePlane = trianglePlaneArray[faceIndex];
  10357. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10358. return;
  10359. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10360. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10361. if (normalDotVelocity == 0) {
  10362. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10363. return;
  10364. embeddedInPlane = true;
  10365. t0 = 0;
  10366. }
  10367. else {
  10368. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10369. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10370. if (t0 > t1) {
  10371. var temp = t1;
  10372. t1 = t0;
  10373. t0 = temp;
  10374. }
  10375. if (t0 > 1.0 || t1 < 0.0)
  10376. return;
  10377. if (t0 < 0)
  10378. t0 = 0;
  10379. if (t0 > 1.0)
  10380. t0 = 1.0;
  10381. }
  10382. this._collisionPoint.copyFromFloats(0, 0, 0);
  10383. var found = false;
  10384. var t = 1.0;
  10385. if (!embeddedInPlane) {
  10386. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10387. this.velocity.scaleToRef(t0, this._tempVector);
  10388. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10389. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10390. found = true;
  10391. t = t0;
  10392. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10393. }
  10394. }
  10395. if (!found) {
  10396. var velocitySquaredLength = this.velocity.lengthSquared();
  10397. var a = velocitySquaredLength;
  10398. this.basePoint.subtractToRef(p1, this._tempVector);
  10399. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10400. var c = this._tempVector.lengthSquared() - 1.0;
  10401. var lowestRoot = getLowestRoot(a, b, c, t);
  10402. if (lowestRoot.found) {
  10403. t = lowestRoot.root;
  10404. found = true;
  10405. this._collisionPoint.copyFrom(p1);
  10406. }
  10407. this.basePoint.subtractToRef(p2, this._tempVector);
  10408. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10409. c = this._tempVector.lengthSquared() - 1.0;
  10410. lowestRoot = getLowestRoot(a, b, c, t);
  10411. if (lowestRoot.found) {
  10412. t = lowestRoot.root;
  10413. found = true;
  10414. this._collisionPoint.copyFrom(p2);
  10415. }
  10416. this.basePoint.subtractToRef(p3, this._tempVector);
  10417. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10418. c = this._tempVector.lengthSquared() - 1.0;
  10419. lowestRoot = getLowestRoot(a, b, c, t);
  10420. if (lowestRoot.found) {
  10421. t = lowestRoot.root;
  10422. found = true;
  10423. this._collisionPoint.copyFrom(p3);
  10424. }
  10425. p2.subtractToRef(p1, this._edge);
  10426. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10427. var edgeSquaredLength = this._edge.lengthSquared();
  10428. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10429. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10430. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10431. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10432. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10433. lowestRoot = getLowestRoot(a, b, c, t);
  10434. if (lowestRoot.found) {
  10435. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10436. if (f >= 0.0 && f <= 1.0) {
  10437. t = lowestRoot.root;
  10438. found = true;
  10439. this._edge.scaleInPlace(f);
  10440. p1.addToRef(this._edge, this._collisionPoint);
  10441. }
  10442. }
  10443. p3.subtractToRef(p2, this._edge);
  10444. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10445. edgeSquaredLength = this._edge.lengthSquared();
  10446. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10447. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10448. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10449. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10450. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10451. lowestRoot = getLowestRoot(a, b, c, t);
  10452. if (lowestRoot.found) {
  10453. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10454. if (f >= 0.0 && f <= 1.0) {
  10455. t = lowestRoot.root;
  10456. found = true;
  10457. this._edge.scaleInPlace(f);
  10458. p2.addToRef(this._edge, this._collisionPoint);
  10459. }
  10460. }
  10461. p1.subtractToRef(p3, this._edge);
  10462. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10463. edgeSquaredLength = this._edge.lengthSquared();
  10464. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10465. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10466. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10467. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10468. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10469. lowestRoot = getLowestRoot(a, b, c, t);
  10470. if (lowestRoot.found) {
  10471. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10472. if (f >= 0.0 && f <= 1.0) {
  10473. t = lowestRoot.root;
  10474. found = true;
  10475. this._edge.scaleInPlace(f);
  10476. p3.addToRef(this._edge, this._collisionPoint);
  10477. }
  10478. }
  10479. }
  10480. if (found) {
  10481. var distToCollision = t * this.velocity.length();
  10482. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10483. if (!this.intersectionPoint) {
  10484. this.intersectionPoint = this._collisionPoint.clone();
  10485. }
  10486. else {
  10487. this.intersectionPoint.copyFrom(this._collisionPoint);
  10488. }
  10489. this.nearestDistance = distToCollision;
  10490. this.collisionFound = true;
  10491. }
  10492. }
  10493. };
  10494. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10495. for (var i = indexStart; i < indexEnd; i += 3) {
  10496. var p1 = pts[indices[i] - decal];
  10497. var p2 = pts[indices[i + 1] - decal];
  10498. var p3 = pts[indices[i + 2] - decal];
  10499. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10500. }
  10501. };
  10502. Collider.prototype._getResponse = function (pos, vel) {
  10503. pos.addToRef(vel, this._destinationPoint);
  10504. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10505. this.basePoint.addToRef(vel, pos);
  10506. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10507. this._slidePlaneNormal.normalize();
  10508. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10509. pos.addInPlace(this._displacementVector);
  10510. this.intersectionPoint.addInPlace(this._displacementVector);
  10511. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10512. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10513. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10514. };
  10515. return Collider;
  10516. }());
  10517. BABYLON.Collider = Collider;
  10518. })(BABYLON || (BABYLON = {}));
  10519. var BABYLON;
  10520. (function (BABYLON) {
  10521. //WebWorker code will be inserted to this variable.
  10522. BABYLON.CollisionWorker = "";
  10523. (function (WorkerTaskType) {
  10524. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10525. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10526. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10527. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10528. var WorkerTaskType = BABYLON.WorkerTaskType;
  10529. (function (WorkerReplyType) {
  10530. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10531. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10532. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10533. var WorkerReplyType = BABYLON.WorkerReplyType;
  10534. var CollisionCoordinatorWorker = (function () {
  10535. function CollisionCoordinatorWorker() {
  10536. var _this = this;
  10537. this._scaledPosition = BABYLON.Vector3.Zero();
  10538. this._scaledVelocity = BABYLON.Vector3.Zero();
  10539. this.onMeshUpdated = function (mesh) {
  10540. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10541. };
  10542. this.onGeometryUpdated = function (geometry) {
  10543. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10544. };
  10545. this._afterRender = function () {
  10546. if (!_this._init)
  10547. return;
  10548. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10549. return;
  10550. }
  10551. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10552. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10553. if (_this._runningUpdated > 4) {
  10554. return;
  10555. }
  10556. ++_this._runningUpdated;
  10557. var payload = {
  10558. updatedMeshes: _this._addUpdateMeshesList,
  10559. updatedGeometries: _this._addUpdateGeometriesList,
  10560. removedGeometries: _this._toRemoveGeometryArray,
  10561. removedMeshes: _this._toRemoveMeshesArray
  10562. };
  10563. var message = {
  10564. payload: payload,
  10565. taskType: WorkerTaskType.UPDATE
  10566. };
  10567. var serializable = [];
  10568. for (var id in payload.updatedGeometries) {
  10569. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10570. //prepare transferables
  10571. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10572. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10573. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10574. }
  10575. }
  10576. _this._worker.postMessage(message, serializable);
  10577. _this._addUpdateMeshesList = {};
  10578. _this._addUpdateGeometriesList = {};
  10579. _this._toRemoveGeometryArray = [];
  10580. _this._toRemoveMeshesArray = [];
  10581. };
  10582. this._onMessageFromWorker = function (e) {
  10583. var returnData = e.data;
  10584. if (returnData.error != WorkerReplyType.SUCCESS) {
  10585. //TODO what errors can be returned from the worker?
  10586. BABYLON.Tools.Warn("error returned from worker!");
  10587. return;
  10588. }
  10589. switch (returnData.taskType) {
  10590. case WorkerTaskType.INIT:
  10591. _this._init = true;
  10592. //Update the worked with ALL of the scene's current state
  10593. _this._scene.meshes.forEach(function (mesh) {
  10594. _this.onMeshAdded(mesh);
  10595. });
  10596. _this._scene.getGeometries().forEach(function (geometry) {
  10597. _this.onGeometryAdded(geometry);
  10598. });
  10599. break;
  10600. case WorkerTaskType.UPDATE:
  10601. _this._runningUpdated--;
  10602. break;
  10603. case WorkerTaskType.COLLIDE:
  10604. _this._runningCollisionTask = false;
  10605. var returnPayload = returnData.payload;
  10606. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10607. return;
  10608. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10609. //cleanup
  10610. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10611. break;
  10612. }
  10613. };
  10614. this._collisionsCallbackArray = [];
  10615. this._init = false;
  10616. this._runningUpdated = 0;
  10617. this._runningCollisionTask = false;
  10618. this._addUpdateMeshesList = {};
  10619. this._addUpdateGeometriesList = {};
  10620. this._toRemoveGeometryArray = [];
  10621. this._toRemoveMeshesArray = [];
  10622. }
  10623. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10624. if (!this._init)
  10625. return;
  10626. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10627. return;
  10628. position.divideToRef(collider.radius, this._scaledPosition);
  10629. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10630. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10631. var payload = {
  10632. collider: {
  10633. position: this._scaledPosition.asArray(),
  10634. velocity: this._scaledVelocity.asArray(),
  10635. radius: collider.radius.asArray()
  10636. },
  10637. collisionId: collisionIndex,
  10638. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10639. maximumRetry: maximumRetry
  10640. };
  10641. var message = {
  10642. payload: payload,
  10643. taskType: WorkerTaskType.COLLIDE
  10644. };
  10645. this._worker.postMessage(message);
  10646. };
  10647. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10648. this._scene = scene;
  10649. this._scene.registerAfterRender(this._afterRender);
  10650. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10651. this._worker = new Worker(workerUrl);
  10652. this._worker.onmessage = this._onMessageFromWorker;
  10653. var message = {
  10654. payload: {},
  10655. taskType: WorkerTaskType.INIT
  10656. };
  10657. this._worker.postMessage(message);
  10658. };
  10659. CollisionCoordinatorWorker.prototype.destroy = function () {
  10660. this._scene.unregisterAfterRender(this._afterRender);
  10661. this._worker.terminate();
  10662. };
  10663. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10664. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10665. this.onMeshUpdated(mesh);
  10666. };
  10667. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10668. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10669. };
  10670. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10671. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10672. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10673. this.onGeometryUpdated(geometry);
  10674. };
  10675. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10676. this._toRemoveGeometryArray.push(geometry.id);
  10677. };
  10678. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10679. var submeshes = [];
  10680. if (mesh.subMeshes) {
  10681. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10682. return {
  10683. position: idx,
  10684. verticesStart: sm.verticesStart,
  10685. verticesCount: sm.verticesCount,
  10686. indexStart: sm.indexStart,
  10687. indexCount: sm.indexCount,
  10688. hasMaterial: !!sm.getMaterial(),
  10689. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10690. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10691. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10692. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10693. };
  10694. });
  10695. }
  10696. var geometryId = null;
  10697. if (mesh instanceof BABYLON.Mesh) {
  10698. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10699. }
  10700. else if (mesh instanceof BABYLON.InstancedMesh) {
  10701. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10702. }
  10703. return {
  10704. uniqueId: mesh.uniqueId,
  10705. id: mesh.id,
  10706. name: mesh.name,
  10707. geometryId: geometryId,
  10708. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10709. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10710. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10711. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10712. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10713. subMeshes: submeshes,
  10714. checkCollisions: mesh.checkCollisions
  10715. };
  10716. };
  10717. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10718. return {
  10719. id: geometry.id,
  10720. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10721. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10722. indices: new Int32Array(geometry.getIndices() || []),
  10723. };
  10724. };
  10725. return CollisionCoordinatorWorker;
  10726. }());
  10727. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10728. var CollisionCoordinatorLegacy = (function () {
  10729. function CollisionCoordinatorLegacy() {
  10730. this._scaledPosition = BABYLON.Vector3.Zero();
  10731. this._scaledVelocity = BABYLON.Vector3.Zero();
  10732. this._finalPosition = BABYLON.Vector3.Zero();
  10733. }
  10734. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10735. position.divideToRef(collider.radius, this._scaledPosition);
  10736. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10737. collider.collidedMesh = null;
  10738. collider.retry = 0;
  10739. collider.initialVelocity = this._scaledVelocity;
  10740. collider.initialPosition = this._scaledPosition;
  10741. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10742. this._finalPosition.multiplyInPlace(collider.radius);
  10743. //run the callback
  10744. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10745. };
  10746. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10747. this._scene = scene;
  10748. };
  10749. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10750. //Legacy need no destruction method.
  10751. };
  10752. //No update in legacy mode
  10753. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10754. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10755. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10756. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10757. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10758. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10759. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10760. if (excludedMesh === void 0) { excludedMesh = null; }
  10761. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10762. if (collider.retry >= maximumRetry) {
  10763. finalPosition.copyFrom(position);
  10764. return;
  10765. }
  10766. collider._initialize(position, velocity, closeDistance);
  10767. // Check all meshes
  10768. for (var index = 0; index < this._scene.meshes.length; index++) {
  10769. var mesh = this._scene.meshes[index];
  10770. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10771. mesh._checkCollision(collider);
  10772. }
  10773. }
  10774. if (!collider.collisionFound) {
  10775. position.addToRef(velocity, finalPosition);
  10776. return;
  10777. }
  10778. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10779. collider._getResponse(position, velocity);
  10780. }
  10781. if (velocity.length() <= closeDistance) {
  10782. finalPosition.copyFrom(position);
  10783. return;
  10784. }
  10785. collider.retry++;
  10786. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10787. };
  10788. return CollisionCoordinatorLegacy;
  10789. }());
  10790. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10791. })(BABYLON || (BABYLON = {}));
  10792. var BABYLON;
  10793. (function (BABYLON) {
  10794. var Camera = (function (_super) {
  10795. __extends(Camera, _super);
  10796. function Camera(name, position, scene) {
  10797. _super.call(this, name, scene);
  10798. this.upVector = BABYLON.Vector3.Up();
  10799. this.orthoLeft = null;
  10800. this.orthoRight = null;
  10801. this.orthoBottom = null;
  10802. this.orthoTop = null;
  10803. this.fov = 0.8;
  10804. this.minZ = 1.0;
  10805. this.maxZ = 10000.0;
  10806. this.inertia = 0.9;
  10807. this.mode = Camera.PERSPECTIVE_CAMERA;
  10808. this.isIntermediate = false;
  10809. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10810. this.layerMask = 0x0FFFFFFF;
  10811. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10812. // Camera rig members
  10813. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10814. this._rigCameras = new Array();
  10815. // Cache
  10816. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10817. this._projectionMatrix = new BABYLON.Matrix();
  10818. this._postProcesses = new Array();
  10819. this._postProcessesTakenIndices = [];
  10820. this._activeMeshes = new BABYLON.SmartArray(256);
  10821. this._globalPosition = BABYLON.Vector3.Zero();
  10822. scene.addCamera(this);
  10823. if (!scene.activeCamera) {
  10824. scene.activeCamera = this;
  10825. }
  10826. this.position = position;
  10827. }
  10828. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10829. get: function () {
  10830. return Camera._PERSPECTIVE_CAMERA;
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10836. get: function () {
  10837. return Camera._ORTHOGRAPHIC_CAMERA;
  10838. },
  10839. enumerable: true,
  10840. configurable: true
  10841. });
  10842. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10843. get: function () {
  10844. return Camera._FOVMODE_VERTICAL_FIXED;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10850. get: function () {
  10851. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10857. get: function () {
  10858. return Camera._RIG_MODE_NONE;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10864. get: function () {
  10865. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10871. get: function () {
  10872. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10878. get: function () {
  10879. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10885. get: function () {
  10886. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10892. get: function () {
  10893. return Camera._RIG_MODE_VR;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. /**
  10899. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10900. */
  10901. Camera.prototype.toString = function (fullDetails) {
  10902. var ret = "Name: " + this.name;
  10903. ret += ", type: " + this.getTypeName();
  10904. if (this.animations) {
  10905. for (var i = 0; i < this.animations.length; i++) {
  10906. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10907. }
  10908. }
  10909. if (fullDetails) {
  10910. }
  10911. return ret;
  10912. };
  10913. Object.defineProperty(Camera.prototype, "globalPosition", {
  10914. get: function () {
  10915. return this._globalPosition;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Camera.prototype.getActiveMeshes = function () {
  10921. return this._activeMeshes;
  10922. };
  10923. Camera.prototype.isActiveMesh = function (mesh) {
  10924. return (this._activeMeshes.indexOf(mesh) !== -1);
  10925. };
  10926. //Cache
  10927. Camera.prototype._initCache = function () {
  10928. _super.prototype._initCache.call(this);
  10929. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10930. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10931. this._cache.mode = undefined;
  10932. this._cache.minZ = undefined;
  10933. this._cache.maxZ = undefined;
  10934. this._cache.fov = undefined;
  10935. this._cache.aspectRatio = undefined;
  10936. this._cache.orthoLeft = undefined;
  10937. this._cache.orthoRight = undefined;
  10938. this._cache.orthoBottom = undefined;
  10939. this._cache.orthoTop = undefined;
  10940. this._cache.renderWidth = undefined;
  10941. this._cache.renderHeight = undefined;
  10942. };
  10943. Camera.prototype._updateCache = function (ignoreParentClass) {
  10944. if (!ignoreParentClass) {
  10945. _super.prototype._updateCache.call(this);
  10946. }
  10947. var engine = this.getEngine();
  10948. this._cache.position.copyFrom(this.position);
  10949. this._cache.upVector.copyFrom(this.upVector);
  10950. this._cache.mode = this.mode;
  10951. this._cache.minZ = this.minZ;
  10952. this._cache.maxZ = this.maxZ;
  10953. this._cache.fov = this.fov;
  10954. this._cache.aspectRatio = engine.getAspectRatio(this);
  10955. this._cache.orthoLeft = this.orthoLeft;
  10956. this._cache.orthoRight = this.orthoRight;
  10957. this._cache.orthoBottom = this.orthoBottom;
  10958. this._cache.orthoTop = this.orthoTop;
  10959. this._cache.renderWidth = engine.getRenderWidth();
  10960. this._cache.renderHeight = engine.getRenderHeight();
  10961. };
  10962. Camera.prototype._updateFromScene = function () {
  10963. this.updateCache();
  10964. this._update();
  10965. };
  10966. // Synchronized
  10967. Camera.prototype._isSynchronized = function () {
  10968. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10969. };
  10970. Camera.prototype._isSynchronizedViewMatrix = function () {
  10971. if (!_super.prototype._isSynchronized.call(this))
  10972. return false;
  10973. return this._cache.position.equals(this.position)
  10974. && this._cache.upVector.equals(this.upVector)
  10975. && this.isSynchronizedWithParent();
  10976. };
  10977. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10978. var check = this._cache.mode === this.mode
  10979. && this._cache.minZ === this.minZ
  10980. && this._cache.maxZ === this.maxZ;
  10981. if (!check) {
  10982. return false;
  10983. }
  10984. var engine = this.getEngine();
  10985. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10986. check = this._cache.fov === this.fov
  10987. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10988. }
  10989. else {
  10990. check = this._cache.orthoLeft === this.orthoLeft
  10991. && this._cache.orthoRight === this.orthoRight
  10992. && this._cache.orthoBottom === this.orthoBottom
  10993. && this._cache.orthoTop === this.orthoTop
  10994. && this._cache.renderWidth === engine.getRenderWidth()
  10995. && this._cache.renderHeight === engine.getRenderHeight();
  10996. }
  10997. return check;
  10998. };
  10999. // Controls
  11000. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11001. };
  11002. Camera.prototype.detachControl = function (element) {
  11003. };
  11004. Camera.prototype._update = function () {
  11005. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11006. this._updateRigCameras();
  11007. }
  11008. this._checkInputs();
  11009. };
  11010. Camera.prototype._checkInputs = function () {
  11011. };
  11012. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11013. if (insertAt === void 0) { insertAt = null; }
  11014. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11015. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11016. return 0;
  11017. }
  11018. if (insertAt == null || insertAt < 0) {
  11019. this._postProcesses.push(postProcess);
  11020. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11021. return this._postProcesses.length - 1;
  11022. }
  11023. var add = 0;
  11024. var i;
  11025. var start;
  11026. if (this._postProcesses[insertAt]) {
  11027. start = this._postProcesses.length - 1;
  11028. for (i = start; i >= insertAt + 1; --i) {
  11029. this._postProcesses[i + 1] = this._postProcesses[i];
  11030. }
  11031. add = 1;
  11032. }
  11033. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11034. if (this._postProcessesTakenIndices[i] < insertAt) {
  11035. continue;
  11036. }
  11037. start = this._postProcessesTakenIndices.length - 1;
  11038. for (var j = start; j >= i; --j) {
  11039. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11040. }
  11041. this._postProcessesTakenIndices[i] = insertAt;
  11042. break;
  11043. }
  11044. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11045. this._postProcessesTakenIndices.push(insertAt);
  11046. }
  11047. var result = insertAt + add;
  11048. this._postProcesses[result] = postProcess;
  11049. return result;
  11050. };
  11051. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11052. if (atIndices === void 0) { atIndices = null; }
  11053. var result = [];
  11054. var i;
  11055. var index;
  11056. if (!atIndices) {
  11057. var length = this._postProcesses.length;
  11058. for (i = 0; i < length; i++) {
  11059. if (this._postProcesses[i] !== postProcess) {
  11060. continue;
  11061. }
  11062. delete this._postProcesses[i];
  11063. index = this._postProcessesTakenIndices.indexOf(i);
  11064. this._postProcessesTakenIndices.splice(index, 1);
  11065. }
  11066. }
  11067. else {
  11068. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11069. for (i = 0; i < atIndices.length; i++) {
  11070. var foundPostProcess = this._postProcesses[atIndices[i]];
  11071. if (foundPostProcess !== postProcess) {
  11072. result.push(i);
  11073. continue;
  11074. }
  11075. delete this._postProcesses[atIndices[i]];
  11076. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11077. this._postProcessesTakenIndices.splice(index, 1);
  11078. }
  11079. }
  11080. return result;
  11081. };
  11082. Camera.prototype.getWorldMatrix = function () {
  11083. if (!this._worldMatrix) {
  11084. this._worldMatrix = BABYLON.Matrix.Identity();
  11085. }
  11086. var viewMatrix = this.getViewMatrix();
  11087. viewMatrix.invertToRef(this._worldMatrix);
  11088. return this._worldMatrix;
  11089. };
  11090. Camera.prototype._getViewMatrix = function () {
  11091. return BABYLON.Matrix.Identity();
  11092. };
  11093. Camera.prototype.getViewMatrix = function (force) {
  11094. this._computedViewMatrix = this._computeViewMatrix(force);
  11095. if (!force && this._isSynchronizedViewMatrix()) {
  11096. return this._computedViewMatrix;
  11097. }
  11098. if (!this.parent || !this.parent.getWorldMatrix) {
  11099. this._globalPosition.copyFrom(this.position);
  11100. }
  11101. else {
  11102. if (!this._worldMatrix) {
  11103. this._worldMatrix = BABYLON.Matrix.Identity();
  11104. }
  11105. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11106. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11107. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11108. this._computedViewMatrix.invert();
  11109. this._markSyncedWithParent();
  11110. }
  11111. this._currentRenderId = this.getScene().getRenderId();
  11112. return this._computedViewMatrix;
  11113. };
  11114. Camera.prototype._computeViewMatrix = function (force) {
  11115. if (!force && this._isSynchronizedViewMatrix()) {
  11116. return this._computedViewMatrix;
  11117. }
  11118. this._computedViewMatrix = this._getViewMatrix();
  11119. this._currentRenderId = this.getScene().getRenderId();
  11120. return this._computedViewMatrix;
  11121. };
  11122. Camera.prototype.getProjectionMatrix = function (force) {
  11123. if (!force && this._isSynchronizedProjectionMatrix()) {
  11124. return this._projectionMatrix;
  11125. }
  11126. var engine = this.getEngine();
  11127. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11128. if (this.minZ <= 0) {
  11129. this.minZ = 0.1;
  11130. }
  11131. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11132. return this._projectionMatrix;
  11133. }
  11134. var halfWidth = engine.getRenderWidth() / 2.0;
  11135. var halfHeight = engine.getRenderHeight() / 2.0;
  11136. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11137. return this._projectionMatrix;
  11138. };
  11139. Camera.prototype.dispose = function () {
  11140. // Animations
  11141. this.getScene().stopAnimation(this);
  11142. // Remove from scene
  11143. this.getScene().removeCamera(this);
  11144. while (this._rigCameras.length > 0) {
  11145. this._rigCameras.pop().dispose();
  11146. }
  11147. // Postprocesses
  11148. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11149. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11150. }
  11151. _super.prototype.dispose.call(this);
  11152. };
  11153. // ---- Camera rigs section ----
  11154. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11155. while (this._rigCameras.length > 0) {
  11156. this._rigCameras.pop().dispose();
  11157. }
  11158. this.cameraRigMode = mode;
  11159. this._cameraRigParams = {};
  11160. switch (this.cameraRigMode) {
  11161. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11162. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11163. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11164. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11165. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11166. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11167. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11168. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11169. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11170. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11171. break;
  11172. }
  11173. var postProcesses = new Array();
  11174. switch (this.cameraRigMode) {
  11175. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11176. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11177. this._rigCameras[0].isIntermediate = true;
  11178. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11179. postProcesses[1].onApply = function (effect) {
  11180. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11181. };
  11182. break;
  11183. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11184. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11185. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11186. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11187. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11188. var secondCamIndex = 1 - firstCamIndex;
  11189. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11190. this._rigCameras[firstCamIndex].isIntermediate = true;
  11191. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11192. break;
  11193. case Camera.RIG_MODE_VR:
  11194. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11195. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11196. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11197. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11198. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11199. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11200. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11201. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11202. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11203. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11204. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11205. if (metrics.compensateDistortion) {
  11206. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11207. }
  11208. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11209. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11210. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11211. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11212. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11213. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11214. if (metrics.compensateDistortion) {
  11215. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11216. }
  11217. break;
  11218. }
  11219. this._update();
  11220. };
  11221. Camera.prototype._getVRProjectionMatrix = function () {
  11222. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11223. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11224. return this._projectionMatrix;
  11225. };
  11226. Camera.prototype.setCameraRigParameter = function (name, value) {
  11227. this._cameraRigParams[name] = value;
  11228. //provisionnally:
  11229. if (name === "interaxialDistance") {
  11230. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11231. }
  11232. };
  11233. /**
  11234. * May needs to be overridden by children so sub has required properties to be copied
  11235. */
  11236. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11237. return null;
  11238. };
  11239. /**
  11240. * May needs to be overridden by children
  11241. */
  11242. Camera.prototype._updateRigCameras = function () {
  11243. for (var i = 0; i < this._rigCameras.length; i++) {
  11244. this._rigCameras[i].minZ = this.minZ;
  11245. this._rigCameras[i].maxZ = this.maxZ;
  11246. this._rigCameras[i].fov = this.fov;
  11247. }
  11248. // only update viewport when ANAGLYPH
  11249. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11250. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11251. }
  11252. };
  11253. Camera.prototype.serialize = function () {
  11254. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11255. // Type
  11256. serializationObject.type = this.getTypeName();
  11257. // Parent
  11258. if (this.parent) {
  11259. serializationObject.parentId = this.parent.id;
  11260. }
  11261. if (this.inputs) {
  11262. this.inputs.serialize(serializationObject);
  11263. }
  11264. // Animations
  11265. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11266. serializationObject.ranges = this.serializeAnimationRanges();
  11267. return serializationObject;
  11268. };
  11269. Camera.prototype.getTypeName = function () {
  11270. return "Camera";
  11271. };
  11272. Camera.prototype.clone = function (name) {
  11273. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11274. };
  11275. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11276. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11277. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11278. switch (type) {
  11279. case "ArcRotateCamera":
  11280. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11281. case "DeviceOrientationCamera":
  11282. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11283. case "FollowCamera":
  11284. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11285. case "ArcFollowCamera":
  11286. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11287. case "GamepadCamera":
  11288. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11289. case "TouchCamera":
  11290. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11291. case "VirtualJoysticksCamera":
  11292. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11293. case "WebVRFreeCamera":
  11294. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11295. case "VRDeviceOrientationFreeCamera":
  11296. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11297. case "AnaglyphArcRotateCamera":
  11298. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11299. case "AnaglyphFreeCamera":
  11300. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11301. case "AnaglyphGamepadCamera":
  11302. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11303. case "AnaglyphUniversalCamera":
  11304. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11305. case "StereoscopicArcRotateCamera":
  11306. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11307. case "StereoscopicFreeCamera":
  11308. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11309. case "StereoscopicGamepadCamera":
  11310. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11311. case "StereoscopicUniversalCamera":
  11312. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11313. case "FreeCamera":
  11314. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11315. default:
  11316. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11317. }
  11318. };
  11319. Camera.Parse = function (parsedCamera, scene) {
  11320. var type = parsedCamera.type;
  11321. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11322. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11323. // Parent
  11324. if (parsedCamera.parentId) {
  11325. camera._waitingParentId = parsedCamera.parentId;
  11326. }
  11327. //If camera has an input manager, let it parse inputs settings
  11328. if (camera.inputs) {
  11329. camera.inputs.parse(parsedCamera);
  11330. }
  11331. // Target
  11332. if (parsedCamera.target) {
  11333. if (camera.setTarget) {
  11334. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11335. }
  11336. }
  11337. // Apply 3d rig, when found
  11338. if (parsedCamera.cameraRigMode) {
  11339. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11340. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11341. }
  11342. // Animations
  11343. if (parsedCamera.animations) {
  11344. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11345. var parsedAnimation = parsedCamera.animations[animationIndex];
  11346. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11347. }
  11348. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11349. }
  11350. if (parsedCamera.autoAnimate) {
  11351. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11352. }
  11353. return camera;
  11354. };
  11355. // Statics
  11356. Camera._PERSPECTIVE_CAMERA = 0;
  11357. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11358. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11359. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11360. Camera._RIG_MODE_NONE = 0;
  11361. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11362. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11363. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11364. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11365. Camera._RIG_MODE_VR = 20;
  11366. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11367. __decorate([
  11368. BABYLON.serializeAsVector3()
  11369. ], Camera.prototype, "position", void 0);
  11370. __decorate([
  11371. BABYLON.serializeAsVector3()
  11372. ], Camera.prototype, "upVector", void 0);
  11373. __decorate([
  11374. BABYLON.serialize()
  11375. ], Camera.prototype, "orthoLeft", void 0);
  11376. __decorate([
  11377. BABYLON.serialize()
  11378. ], Camera.prototype, "orthoRight", void 0);
  11379. __decorate([
  11380. BABYLON.serialize()
  11381. ], Camera.prototype, "orthoBottom", void 0);
  11382. __decorate([
  11383. BABYLON.serialize()
  11384. ], Camera.prototype, "orthoTop", void 0);
  11385. __decorate([
  11386. BABYLON.serialize()
  11387. ], Camera.prototype, "fov", void 0);
  11388. __decorate([
  11389. BABYLON.serialize()
  11390. ], Camera.prototype, "minZ", void 0);
  11391. __decorate([
  11392. BABYLON.serialize()
  11393. ], Camera.prototype, "maxZ", void 0);
  11394. __decorate([
  11395. BABYLON.serialize()
  11396. ], Camera.prototype, "inertia", void 0);
  11397. __decorate([
  11398. BABYLON.serialize()
  11399. ], Camera.prototype, "mode", void 0);
  11400. __decorate([
  11401. BABYLON.serialize()
  11402. ], Camera.prototype, "layerMask", void 0);
  11403. __decorate([
  11404. BABYLON.serialize()
  11405. ], Camera.prototype, "fovMode", void 0);
  11406. __decorate([
  11407. BABYLON.serialize()
  11408. ], Camera.prototype, "cameraRigMode", void 0);
  11409. __decorate([
  11410. BABYLON.serialize()
  11411. ], Camera.prototype, "interaxialDistance", void 0);
  11412. __decorate([
  11413. BABYLON.serialize()
  11414. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11415. return Camera;
  11416. }(BABYLON.Node));
  11417. BABYLON.Camera = Camera;
  11418. })(BABYLON || (BABYLON = {}));
  11419. var BABYLON;
  11420. (function (BABYLON) {
  11421. BABYLON.CameraInputTypes = {};
  11422. var CameraInputsManager = (function () {
  11423. function CameraInputsManager(camera) {
  11424. this.attached = {};
  11425. this.camera = camera;
  11426. this.checkInputs = function () { };
  11427. }
  11428. CameraInputsManager.prototype.add = function (input) {
  11429. var type = input.getSimpleName();
  11430. if (this.attached[type]) {
  11431. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11432. return;
  11433. }
  11434. this.attached[type] = input;
  11435. input.camera = this.camera;
  11436. //for checkInputs, we are dynamically creating a function
  11437. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11438. if (input.checkInputs) {
  11439. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11440. }
  11441. if (this.attachedElement) {
  11442. input.attachControl(this.attachedElement);
  11443. }
  11444. };
  11445. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11446. for (var cam in this.attached) {
  11447. var input = this.attached[cam];
  11448. if (input === inputToRemove) {
  11449. input.detachControl(this.attachedElement);
  11450. delete this.attached[cam];
  11451. this.rebuildInputCheck();
  11452. }
  11453. }
  11454. };
  11455. CameraInputsManager.prototype.removeByType = function (inputType) {
  11456. for (var cam in this.attached) {
  11457. var input = this.attached[cam];
  11458. if (input.getTypeName() === inputType) {
  11459. input.detachControl(this.attachedElement);
  11460. delete this.attached[cam];
  11461. this.rebuildInputCheck();
  11462. }
  11463. }
  11464. };
  11465. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11466. var current = this.checkInputs;
  11467. return function () {
  11468. current();
  11469. fn();
  11470. };
  11471. };
  11472. CameraInputsManager.prototype.attachInput = function (input) {
  11473. input.attachControl(this.attachedElement, this.noPreventDefault);
  11474. };
  11475. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11476. if (this.attachedElement) {
  11477. return;
  11478. }
  11479. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11480. this.attachedElement = element;
  11481. this.noPreventDefault = noPreventDefault;
  11482. for (var cam in this.attached) {
  11483. var input = this.attached[cam];
  11484. this.attached[cam].attachControl(element, noPreventDefault);
  11485. }
  11486. };
  11487. CameraInputsManager.prototype.detachElement = function (element) {
  11488. if (this.attachedElement !== element) {
  11489. return;
  11490. }
  11491. for (var cam in this.attached) {
  11492. var input = this.attached[cam];
  11493. this.attached[cam].detachControl(element);
  11494. }
  11495. this.attachedElement = null;
  11496. };
  11497. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11498. this.checkInputs = function () { };
  11499. for (var cam in this.attached) {
  11500. var input = this.attached[cam];
  11501. if (input.checkInputs) {
  11502. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11503. }
  11504. }
  11505. };
  11506. CameraInputsManager.prototype.clear = function () {
  11507. if (this.attachedElement) {
  11508. this.detachElement(this.attachedElement);
  11509. }
  11510. this.attached = {};
  11511. this.attachedElement = null;
  11512. this.checkInputs = function () { };
  11513. };
  11514. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11515. var inputs = {};
  11516. for (var cam in this.attached) {
  11517. var input = this.attached[cam];
  11518. var res = BABYLON.SerializationHelper.Serialize(input);
  11519. inputs[input.getTypeName()] = res;
  11520. }
  11521. serializedCamera.inputsmgr = inputs;
  11522. };
  11523. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11524. var parsedInputs = parsedCamera.inputsmgr;
  11525. if (parsedInputs) {
  11526. this.clear();
  11527. for (var n in parsedInputs) {
  11528. var construct = BABYLON.CameraInputTypes[n];
  11529. if (construct) {
  11530. var parsedinput = parsedInputs[n];
  11531. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11532. this.add(input);
  11533. }
  11534. }
  11535. }
  11536. else {
  11537. //2016-03-08 this part is for managing backward compatibility
  11538. for (var n in this.attached) {
  11539. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11540. if (construct) {
  11541. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11542. this.remove(this.attached[n]);
  11543. this.add(input);
  11544. }
  11545. }
  11546. }
  11547. };
  11548. return CameraInputsManager;
  11549. }());
  11550. BABYLON.CameraInputsManager = CameraInputsManager;
  11551. })(BABYLON || (BABYLON = {}));
  11552. var BABYLON;
  11553. (function (BABYLON) {
  11554. var FreeCameraMouseInput = (function () {
  11555. function FreeCameraMouseInput() {
  11556. this.angularSensibility = 2000.0;
  11557. }
  11558. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11559. var _this = this;
  11560. if (!this._onMouseDown) {
  11561. var camera = this.camera;
  11562. var engine = this.camera.getEngine();
  11563. this._onMouseDown = function (evt) {
  11564. _this.previousPosition = {
  11565. x: evt.clientX,
  11566. y: evt.clientY
  11567. };
  11568. if (!noPreventDefault) {
  11569. evt.preventDefault();
  11570. }
  11571. };
  11572. this._onMouseUp = function (evt) {
  11573. _this.previousPosition = null;
  11574. if (!noPreventDefault) {
  11575. evt.preventDefault();
  11576. }
  11577. };
  11578. this._onMouseOut = function (evt) {
  11579. _this.previousPosition = null;
  11580. if (!noPreventDefault) {
  11581. evt.preventDefault();
  11582. }
  11583. };
  11584. this._onMouseMove = function (evt) {
  11585. if (!_this.previousPosition && !engine.isPointerLock) {
  11586. return;
  11587. }
  11588. var offsetX;
  11589. var offsetY;
  11590. if (!engine.isPointerLock) {
  11591. offsetX = evt.clientX - _this.previousPosition.x;
  11592. offsetY = evt.clientY - _this.previousPosition.y;
  11593. }
  11594. else {
  11595. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11596. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11597. }
  11598. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11599. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11600. _this.previousPosition = {
  11601. x: evt.clientX,
  11602. y: evt.clientY
  11603. };
  11604. if (!noPreventDefault) {
  11605. evt.preventDefault();
  11606. }
  11607. };
  11608. }
  11609. element.addEventListener("mousedown", this._onMouseDown, false);
  11610. element.addEventListener("mouseup", this._onMouseUp, false);
  11611. element.addEventListener("mouseout", this._onMouseOut, false);
  11612. element.addEventListener("mousemove", this._onMouseMove, false);
  11613. };
  11614. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11615. if (this._onMouseDown && element) {
  11616. this.previousPosition = null;
  11617. element.removeEventListener("mousedown", this._onMouseDown);
  11618. element.removeEventListener("mouseup", this._onMouseUp);
  11619. element.removeEventListener("mouseout", this._onMouseOut);
  11620. element.removeEventListener("mousemove", this._onMouseMove);
  11621. this._onMouseDown = null;
  11622. this._onMouseUp = null;
  11623. this._onMouseOut = null;
  11624. this._onMouseMove = null;
  11625. }
  11626. };
  11627. FreeCameraMouseInput.prototype.getTypeName = function () {
  11628. return "FreeCameraMouseInput";
  11629. };
  11630. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11631. return "mouse";
  11632. };
  11633. __decorate([
  11634. BABYLON.serialize()
  11635. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11636. return FreeCameraMouseInput;
  11637. }());
  11638. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11639. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11640. })(BABYLON || (BABYLON = {}));
  11641. var BABYLON;
  11642. (function (BABYLON) {
  11643. var FreeCameraKeyboardMoveInput = (function () {
  11644. function FreeCameraKeyboardMoveInput() {
  11645. this._keys = [];
  11646. this.keysUp = [38];
  11647. this.keysDown = [40];
  11648. this.keysLeft = [37];
  11649. this.keysRight = [39];
  11650. }
  11651. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11652. var _this = this;
  11653. if (!this._onKeyDown) {
  11654. this._onKeyDown = function (evt) {
  11655. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11656. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11657. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11658. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11659. var index = _this._keys.indexOf(evt.keyCode);
  11660. if (index === -1) {
  11661. _this._keys.push(evt.keyCode);
  11662. }
  11663. if (!noPreventDefault) {
  11664. evt.preventDefault();
  11665. }
  11666. }
  11667. };
  11668. this._onKeyUp = function (evt) {
  11669. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11670. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11671. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11672. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11673. var index = _this._keys.indexOf(evt.keyCode);
  11674. if (index >= 0) {
  11675. _this._keys.splice(index, 1);
  11676. }
  11677. if (!noPreventDefault) {
  11678. evt.preventDefault();
  11679. }
  11680. }
  11681. };
  11682. BABYLON.Tools.RegisterTopRootEvents([
  11683. { name: "keydown", handler: this._onKeyDown },
  11684. { name: "keyup", handler: this._onKeyUp },
  11685. { name: "blur", handler: this._onLostFocus }
  11686. ]);
  11687. }
  11688. };
  11689. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11690. if (this._onKeyDown) {
  11691. BABYLON.Tools.UnregisterTopRootEvents([
  11692. { name: "keydown", handler: this._onKeyDown },
  11693. { name: "keyup", handler: this._onKeyUp },
  11694. { name: "blur", handler: this._onLostFocus }
  11695. ]);
  11696. this._keys = [];
  11697. this._onKeyDown = null;
  11698. this._onKeyUp = null;
  11699. }
  11700. };
  11701. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11702. if (this._onKeyDown) {
  11703. var camera = this.camera;
  11704. // Keyboard
  11705. for (var index = 0; index < this._keys.length; index++) {
  11706. var keyCode = this._keys[index];
  11707. var speed = camera._computeLocalCameraSpeed();
  11708. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11709. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11710. }
  11711. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11712. camera._localDirection.copyFromFloats(0, 0, speed);
  11713. }
  11714. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11715. camera._localDirection.copyFromFloats(speed, 0, 0);
  11716. }
  11717. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11718. camera._localDirection.copyFromFloats(0, 0, -speed);
  11719. }
  11720. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11721. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11722. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11723. }
  11724. }
  11725. };
  11726. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11727. return "FreeCameraKeyboardMoveInput";
  11728. };
  11729. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11730. this._keys = [];
  11731. };
  11732. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11733. return "keyboard";
  11734. };
  11735. __decorate([
  11736. BABYLON.serialize()
  11737. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11738. __decorate([
  11739. BABYLON.serialize()
  11740. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11741. __decorate([
  11742. BABYLON.serialize()
  11743. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11744. __decorate([
  11745. BABYLON.serialize()
  11746. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11747. return FreeCameraKeyboardMoveInput;
  11748. }());
  11749. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11750. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11751. })(BABYLON || (BABYLON = {}));
  11752. var BABYLON;
  11753. (function (BABYLON) {
  11754. var FreeCameraTouchInput = (function () {
  11755. function FreeCameraTouchInput() {
  11756. this._offsetX = null;
  11757. this._offsetY = null;
  11758. this._pointerCount = 0;
  11759. this._pointerPressed = [];
  11760. this.touchAngularSensibility = 200000.0;
  11761. this.touchMoveSensibility = 250.0;
  11762. }
  11763. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11764. var _this = this;
  11765. var previousPosition;
  11766. if (this._onPointerDown === undefined) {
  11767. this._onLostFocus = function (evt) {
  11768. _this._offsetX = null;
  11769. _this._offsetY = null;
  11770. };
  11771. this._onPointerDown = function (evt) {
  11772. if (evt.pointerType === "mouse") {
  11773. return;
  11774. }
  11775. if (!noPreventDefault) {
  11776. evt.preventDefault();
  11777. }
  11778. _this._pointerPressed.push(evt.pointerId);
  11779. if (_this._pointerPressed.length !== 1) {
  11780. return;
  11781. }
  11782. previousPosition = {
  11783. x: evt.clientX,
  11784. y: evt.clientY
  11785. };
  11786. };
  11787. this._onPointerUp = function (evt) {
  11788. if (evt.pointerType === "mouse") {
  11789. return;
  11790. }
  11791. if (!noPreventDefault) {
  11792. evt.preventDefault();
  11793. }
  11794. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11795. if (index === -1) {
  11796. return;
  11797. }
  11798. _this._pointerPressed.splice(index, 1);
  11799. if (index != 0) {
  11800. return;
  11801. }
  11802. previousPosition = null;
  11803. _this._offsetX = null;
  11804. _this._offsetY = null;
  11805. };
  11806. this._onPointerMove = function (evt) {
  11807. if (evt.pointerType === "mouse") {
  11808. return;
  11809. }
  11810. if (!noPreventDefault) {
  11811. evt.preventDefault();
  11812. }
  11813. if (!previousPosition) {
  11814. return;
  11815. }
  11816. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11817. if (index != 0) {
  11818. return;
  11819. }
  11820. _this._offsetX = evt.clientX - previousPosition.x;
  11821. _this._offsetY = -(evt.clientY - previousPosition.y);
  11822. };
  11823. }
  11824. element.addEventListener("blur", this._onLostFocus);
  11825. element.addEventListener("pointerdown", this._onPointerDown);
  11826. element.addEventListener("pointerup", this._onPointerUp);
  11827. element.addEventListener("pointerout", this._onPointerUp);
  11828. element.addEventListener("pointermove", this._onPointerMove);
  11829. };
  11830. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11831. if (this._onPointerDown && element) {
  11832. element.removeEventListener("blur", this._onLostFocus);
  11833. element.removeEventListener("pointerdown", this._onPointerDown);
  11834. element.removeEventListener("pointerup", this._onPointerUp);
  11835. element.removeEventListener("pointerout", this._onPointerUp);
  11836. element.removeEventListener("pointermove", this._onPointerMove);
  11837. this._onPointerDown = null;
  11838. this._onPointerUp = null;
  11839. this._onPointerMove = null;
  11840. this._onLostFocus = null;
  11841. this._pointerPressed = [];
  11842. this._offsetX = null;
  11843. this._offsetY = null;
  11844. this._pointerCount = 0;
  11845. }
  11846. };
  11847. FreeCameraTouchInput.prototype.checkInputs = function () {
  11848. if (this._offsetX) {
  11849. var camera = this.camera;
  11850. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11851. if (this._pointerPressed.length > 1) {
  11852. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11853. }
  11854. else {
  11855. var speed = camera._computeLocalCameraSpeed();
  11856. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11857. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11858. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11859. }
  11860. }
  11861. };
  11862. FreeCameraTouchInput.prototype.getTypeName = function () {
  11863. return "FreeCameraTouchInput";
  11864. };
  11865. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11866. return "touch";
  11867. };
  11868. __decorate([
  11869. BABYLON.serialize()
  11870. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11871. __decorate([
  11872. BABYLON.serialize()
  11873. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11874. return FreeCameraTouchInput;
  11875. }());
  11876. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11877. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11878. })(BABYLON || (BABYLON = {}));
  11879. var BABYLON;
  11880. (function (BABYLON) {
  11881. var FreeCameraDeviceOrientationInput = (function () {
  11882. function FreeCameraDeviceOrientationInput() {
  11883. this._offsetX = null;
  11884. this._offsetY = null;
  11885. this._orientationGamma = 0;
  11886. this._orientationBeta = 0;
  11887. this._initialOrientationGamma = 0;
  11888. this._initialOrientationBeta = 0;
  11889. this.angularSensibility = 10000.0;
  11890. this.moveSensibility = 50.0;
  11891. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11892. this._orientationChanged = this.orientationChanged.bind(this);
  11893. }
  11894. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11895. window.addEventListener("resize", this._resetOrientationGamma, false);
  11896. window.addEventListener("deviceorientation", this._orientationChanged);
  11897. };
  11898. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11899. this._initialOrientationGamma = null;
  11900. };
  11901. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11902. if (!this._initialOrientationGamma) {
  11903. this._initialOrientationGamma = evt.gamma;
  11904. this._initialOrientationBeta = evt.beta;
  11905. }
  11906. this._orientationGamma = evt.gamma;
  11907. this._orientationBeta = evt.beta;
  11908. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11909. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11910. };
  11911. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11912. window.removeEventListener("resize", this._resetOrientationGamma);
  11913. window.removeEventListener("deviceorientation", this._orientationChanged);
  11914. this._orientationGamma = 0;
  11915. this._orientationBeta = 0;
  11916. this._initialOrientationGamma = 0;
  11917. this._initialOrientationBeta = 0;
  11918. this._offsetX = null;
  11919. this._offsetY = null;
  11920. };
  11921. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11922. if (!this._offsetX) {
  11923. return;
  11924. }
  11925. var camera = this.camera;
  11926. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11927. var speed = camera._computeLocalCameraSpeed();
  11928. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11929. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11930. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11931. };
  11932. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11933. return "FreeCameraDeviceOrientationInput";
  11934. };
  11935. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11936. return "deviceOrientation";
  11937. };
  11938. __decorate([
  11939. BABYLON.serialize()
  11940. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11941. __decorate([
  11942. BABYLON.serialize()
  11943. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11944. return FreeCameraDeviceOrientationInput;
  11945. }());
  11946. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11947. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11948. })(BABYLON || (BABYLON = {}));
  11949. var BABYLON;
  11950. (function (BABYLON) {
  11951. var FreeCameraVRDeviceOrientationInput = (function () {
  11952. function FreeCameraVRDeviceOrientationInput() {
  11953. this.alphaCorrection = 1;
  11954. this.betaCorrection = 1;
  11955. this.gammaCorrection = 1;
  11956. this._alpha = 0;
  11957. this._beta = 0;
  11958. this._gamma = 0;
  11959. this._dirty = false;
  11960. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11961. }
  11962. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11963. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11964. };
  11965. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11966. var camera = this.camera;
  11967. this._alpha = +evt.alpha | 0;
  11968. this._beta = +evt.beta | 0;
  11969. this._gamma = +evt.gamma | 0;
  11970. this._dirty = true;
  11971. };
  11972. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  11973. if (this._dirty) {
  11974. this._dirty = false;
  11975. var rotationX = this._gamma;
  11976. if (rotationX < 0) {
  11977. rotationX = 90 + rotationX;
  11978. }
  11979. else {
  11980. // Incline it in the correct angle.
  11981. rotationX = 270 - rotationX;
  11982. }
  11983. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  11984. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  11985. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  11986. }
  11987. };
  11988. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  11989. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11990. };
  11991. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  11992. return "FreeCameraVRDeviceOrientationInput";
  11993. };
  11994. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  11995. return "VRDeviceOrientation";
  11996. };
  11997. return FreeCameraVRDeviceOrientationInput;
  11998. }());
  11999. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12000. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12001. })(BABYLON || (BABYLON = {}));
  12002. var BABYLON;
  12003. (function (BABYLON) {
  12004. var FreeCameraGamepadInput = (function () {
  12005. function FreeCameraGamepadInput() {
  12006. this.gamepadAngularSensibility = 200;
  12007. this.gamepadMoveSensibility = 40;
  12008. }
  12009. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12010. var _this = this;
  12011. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12012. };
  12013. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12014. if (this._gamepads) {
  12015. this._gamepads.dispose();
  12016. }
  12017. this.gamepad = null;
  12018. };
  12019. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12020. if (this.gamepad) {
  12021. var camera = this.camera;
  12022. var LSValues = this.gamepad.leftStick;
  12023. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12024. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12025. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12026. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12027. var RSValues = this.gamepad.rightStick;
  12028. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12029. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12030. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12031. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12032. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12033. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12034. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12035. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12036. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12037. }
  12038. };
  12039. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12040. // Only the first gamepad can control the camera
  12041. if (gamepad.index === 0) {
  12042. this.gamepad = gamepad;
  12043. }
  12044. };
  12045. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12046. return "FreeCameraGamepadInput";
  12047. };
  12048. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12049. return "gamepad";
  12050. };
  12051. __decorate([
  12052. BABYLON.serialize()
  12053. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12054. __decorate([
  12055. BABYLON.serialize()
  12056. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12057. return FreeCameraGamepadInput;
  12058. }());
  12059. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12060. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12061. })(BABYLON || (BABYLON = {}));
  12062. var BABYLON;
  12063. (function (BABYLON) {
  12064. var FreeCameraVirtualJoystickInput = (function () {
  12065. function FreeCameraVirtualJoystickInput() {
  12066. }
  12067. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12068. return this._leftjoystick;
  12069. };
  12070. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12071. return this._rightjoystick;
  12072. };
  12073. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12074. if (this._leftjoystick) {
  12075. var camera = this.camera;
  12076. var speed = camera._computeLocalCameraSpeed() * 50;
  12077. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12078. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12079. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12080. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12081. if (!this._leftjoystick.pressed) {
  12082. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12083. }
  12084. if (!this._rightjoystick.pressed) {
  12085. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12086. }
  12087. }
  12088. };
  12089. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12090. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12091. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12092. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12093. this._leftjoystick.setJoystickSensibility(0.15);
  12094. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12095. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12096. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12097. this._rightjoystick.reverseUpDown = true;
  12098. this._rightjoystick.setJoystickSensibility(0.05);
  12099. this._rightjoystick.setJoystickColor("yellow");
  12100. };
  12101. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12102. this._leftjoystick.releaseCanvas();
  12103. this._rightjoystick.releaseCanvas();
  12104. };
  12105. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12106. return "FreeCameraVirtualJoystickInput";
  12107. };
  12108. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12109. return "virtualJoystick";
  12110. };
  12111. return FreeCameraVirtualJoystickInput;
  12112. }());
  12113. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12114. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12115. })(BABYLON || (BABYLON = {}));
  12116. var BABYLON;
  12117. (function (BABYLON) {
  12118. var ArcRotateCameraKeyboardMoveInput = (function () {
  12119. function ArcRotateCameraKeyboardMoveInput() {
  12120. this._keys = [];
  12121. this.keysUp = [38];
  12122. this.keysDown = [40];
  12123. this.keysLeft = [37];
  12124. this.keysRight = [39];
  12125. }
  12126. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12127. var _this = this;
  12128. this._onKeyDown = function (evt) {
  12129. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12130. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12131. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12132. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12133. var index = _this._keys.indexOf(evt.keyCode);
  12134. if (index === -1) {
  12135. _this._keys.push(evt.keyCode);
  12136. }
  12137. if (evt.preventDefault) {
  12138. if (!noPreventDefault) {
  12139. evt.preventDefault();
  12140. }
  12141. }
  12142. }
  12143. };
  12144. this._onKeyUp = function (evt) {
  12145. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12146. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12147. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12148. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12149. var index = _this._keys.indexOf(evt.keyCode);
  12150. if (index >= 0) {
  12151. _this._keys.splice(index, 1);
  12152. }
  12153. if (evt.preventDefault) {
  12154. if (!noPreventDefault) {
  12155. evt.preventDefault();
  12156. }
  12157. }
  12158. }
  12159. };
  12160. this._onLostFocus = function () {
  12161. _this._keys = [];
  12162. };
  12163. BABYLON.Tools.RegisterTopRootEvents([
  12164. { name: "keydown", handler: this._onKeyDown },
  12165. { name: "keyup", handler: this._onKeyUp },
  12166. { name: "blur", handler: this._onLostFocus }
  12167. ]);
  12168. };
  12169. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12170. BABYLON.Tools.UnregisterTopRootEvents([
  12171. { name: "keydown", handler: this._onKeyDown },
  12172. { name: "keyup", handler: this._onKeyUp },
  12173. { name: "blur", handler: this._onLostFocus }
  12174. ]);
  12175. this._keys = [];
  12176. this._onKeyDown = null;
  12177. this._onKeyUp = null;
  12178. this._onLostFocus = null;
  12179. };
  12180. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12181. if (this._onKeyDown) {
  12182. var camera = this.camera;
  12183. for (var index = 0; index < this._keys.length; index++) {
  12184. var keyCode = this._keys[index];
  12185. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12186. camera.inertialAlphaOffset -= 0.01;
  12187. }
  12188. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12189. camera.inertialBetaOffset -= 0.01;
  12190. }
  12191. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12192. camera.inertialAlphaOffset += 0.01;
  12193. }
  12194. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12195. camera.inertialBetaOffset += 0.01;
  12196. }
  12197. }
  12198. }
  12199. };
  12200. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12201. return "ArcRotateCameraKeyboardMoveInput";
  12202. };
  12203. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12204. return "keyboard";
  12205. };
  12206. __decorate([
  12207. BABYLON.serialize()
  12208. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12209. __decorate([
  12210. BABYLON.serialize()
  12211. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12212. __decorate([
  12213. BABYLON.serialize()
  12214. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12215. __decorate([
  12216. BABYLON.serialize()
  12217. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12218. return ArcRotateCameraKeyboardMoveInput;
  12219. }());
  12220. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12221. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12222. })(BABYLON || (BABYLON = {}));
  12223. var BABYLON;
  12224. (function (BABYLON) {
  12225. var ArcRotateCameraMouseWheelInput = (function () {
  12226. function ArcRotateCameraMouseWheelInput() {
  12227. this.wheelPrecision = 3.0;
  12228. }
  12229. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12230. var _this = this;
  12231. this._wheel = function (event) {
  12232. var delta = 0;
  12233. if (event.wheelDelta) {
  12234. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12235. }
  12236. else if (event.detail) {
  12237. delta = -event.detail / _this.wheelPrecision;
  12238. }
  12239. if (delta)
  12240. _this.camera.inertialRadiusOffset += delta;
  12241. if (event.preventDefault) {
  12242. if (!noPreventDefault) {
  12243. event.preventDefault();
  12244. }
  12245. }
  12246. };
  12247. element.addEventListener('mousewheel', this._wheel, false);
  12248. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12249. };
  12250. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12251. if (this._wheel && element) {
  12252. element.removeEventListener('mousewheel', this._wheel);
  12253. element.removeEventListener('DOMMouseScroll', this._wheel);
  12254. this._wheel = null;
  12255. }
  12256. };
  12257. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12258. return "ArcRotateCameraMouseWheelInput";
  12259. };
  12260. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12261. return "mousewheel";
  12262. };
  12263. __decorate([
  12264. BABYLON.serialize()
  12265. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12266. return ArcRotateCameraMouseWheelInput;
  12267. }());
  12268. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12269. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12270. })(BABYLON || (BABYLON = {}));
  12271. var BABYLON;
  12272. (function (BABYLON) {
  12273. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12274. var ArcRotateCameraPointersInput = (function () {
  12275. function ArcRotateCameraPointersInput() {
  12276. this.angularSensibilityX = 1000.0;
  12277. this.angularSensibilityY = 1000.0;
  12278. this.pinchPrecision = 6.0;
  12279. this.panningSensibility = 50.0;
  12280. this._isRightClick = false;
  12281. this._isCtrlPushed = false;
  12282. this.pinchInwards = true;
  12283. }
  12284. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12285. var _this = this;
  12286. var engine = this.camera.getEngine();
  12287. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12288. var pointers = new BABYLON.SmartCollection();
  12289. var previousPinchDistance = 0;
  12290. this._onContextMenu = function (evt) {
  12291. evt.preventDefault();
  12292. };
  12293. if (!this.camera._useCtrlForPanning) {
  12294. element.addEventListener("contextmenu", this._onContextMenu, false);
  12295. }
  12296. this._onLostFocus = function () {
  12297. //this._keys = [];
  12298. pointers.empty();
  12299. previousPinchDistance = 0;
  12300. cacheSoloPointer = null;
  12301. };
  12302. this._onKeyDown = function (evt) {
  12303. _this._isCtrlPushed = evt.ctrlKey;
  12304. };
  12305. this._onKeyUp = function (evt) {
  12306. _this._isCtrlPushed = evt.ctrlKey;
  12307. };
  12308. this._onPointerDown = function (evt) {
  12309. // Manage panning with right click
  12310. _this._isRightClick = evt.button === 2;
  12311. // manage pointers
  12312. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  12313. cacheSoloPointer = pointers.item(evt.pointerId);
  12314. if (!noPreventDefault) {
  12315. evt.preventDefault();
  12316. }
  12317. };
  12318. this._onPointerUp = function (evt) {
  12319. cacheSoloPointer = null;
  12320. previousPinchDistance = 0;
  12321. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12322. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12323. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12324. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12325. pointers.empty();
  12326. if (!noPreventDefault) {
  12327. evt.preventDefault();
  12328. }
  12329. };
  12330. this._onPointerMove = function (evt) {
  12331. if (!noPreventDefault) {
  12332. evt.preventDefault();
  12333. }
  12334. switch (pointers.count) {
  12335. case 1:
  12336. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12337. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12338. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12339. }
  12340. else {
  12341. var offsetX = evt.clientX - cacheSoloPointer.x;
  12342. var offsetY = evt.clientY - cacheSoloPointer.y;
  12343. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12344. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12345. }
  12346. cacheSoloPointer.x = evt.clientX;
  12347. cacheSoloPointer.y = evt.clientY;
  12348. break;
  12349. case 2:
  12350. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12351. pointers.item(evt.pointerId).x = evt.clientX;
  12352. pointers.item(evt.pointerId).y = evt.clientY;
  12353. var direction = _this.pinchInwards ? 1 : -1;
  12354. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  12355. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  12356. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12357. if (previousPinchDistance === 0) {
  12358. previousPinchDistance = pinchSquaredDistance;
  12359. return;
  12360. }
  12361. if (pinchSquaredDistance !== previousPinchDistance) {
  12362. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12363. previousPinchDistance = pinchSquaredDistance;
  12364. }
  12365. break;
  12366. default:
  12367. if (pointers.item(evt.pointerId)) {
  12368. pointers.item(evt.pointerId).x = evt.clientX;
  12369. pointers.item(evt.pointerId).y = evt.clientY;
  12370. }
  12371. }
  12372. };
  12373. this._onMouseMove = function (evt) {
  12374. if (!engine.isPointerLock) {
  12375. return;
  12376. }
  12377. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12378. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12379. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12380. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12381. if (!noPreventDefault) {
  12382. evt.preventDefault();
  12383. }
  12384. };
  12385. this._onGestureStart = function (e) {
  12386. if (window.MSGesture === undefined) {
  12387. return;
  12388. }
  12389. if (!_this._MSGestureHandler) {
  12390. _this._MSGestureHandler = new MSGesture();
  12391. _this._MSGestureHandler.target = element;
  12392. }
  12393. _this._MSGestureHandler.addPointer(e.pointerId);
  12394. };
  12395. this._onGesture = function (e) {
  12396. _this.camera.radius *= e.scale;
  12397. if (e.preventDefault) {
  12398. if (!noPreventDefault) {
  12399. e.stopPropagation();
  12400. e.preventDefault();
  12401. }
  12402. }
  12403. };
  12404. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12405. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12406. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12407. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12408. element.addEventListener("mousemove", this._onMouseMove, false);
  12409. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12410. element.addEventListener("MSGestureChange", this._onGesture, false);
  12411. BABYLON.Tools.RegisterTopRootEvents([
  12412. { name: "keydown", handler: this._onKeyDown },
  12413. { name: "keyup", handler: this._onKeyUp },
  12414. { name: "blur", handler: this._onLostFocus }
  12415. ]);
  12416. };
  12417. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12418. if (element && this._onPointerDown) {
  12419. element.removeEventListener("contextmenu", this._onContextMenu);
  12420. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12421. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12422. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12423. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12424. element.removeEventListener("mousemove", this._onMouseMove);
  12425. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12426. element.removeEventListener("MSGestureChange", this._onGesture);
  12427. this._isRightClick = false;
  12428. this._isCtrlPushed = false;
  12429. this.pinchInwards = true;
  12430. this._onKeyDown = null;
  12431. this._onKeyUp = null;
  12432. this._onPointerDown = null;
  12433. this._onPointerUp = null;
  12434. this._onPointerMove = null;
  12435. this._onMouseMove = null;
  12436. this._onGestureStart = null;
  12437. this._onGesture = null;
  12438. this._MSGestureHandler = null;
  12439. this._onLostFocus = null;
  12440. this._onContextMenu = null;
  12441. }
  12442. BABYLON.Tools.UnregisterTopRootEvents([
  12443. { name: "keydown", handler: this._onKeyDown },
  12444. { name: "keyup", handler: this._onKeyUp },
  12445. { name: "blur", handler: this._onLostFocus }
  12446. ]);
  12447. };
  12448. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12449. return "ArcRotateCameraPointersInput";
  12450. };
  12451. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12452. return "pointers";
  12453. };
  12454. __decorate([
  12455. BABYLON.serialize()
  12456. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12457. __decorate([
  12458. BABYLON.serialize()
  12459. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12460. __decorate([
  12461. BABYLON.serialize()
  12462. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12463. __decorate([
  12464. BABYLON.serialize()
  12465. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12466. return ArcRotateCameraPointersInput;
  12467. }());
  12468. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12469. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12470. })(BABYLON || (BABYLON = {}));
  12471. var BABYLON;
  12472. (function (BABYLON) {
  12473. var ArcRotateCameraGamepadInput = (function () {
  12474. function ArcRotateCameraGamepadInput() {
  12475. this.gamepadRotationSensibility = 80;
  12476. this.gamepadMoveSensibility = 40;
  12477. }
  12478. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12479. var _this = this;
  12480. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12481. };
  12482. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12483. if (this._gamepads) {
  12484. this._gamepads.dispose();
  12485. }
  12486. this.gamepad = null;
  12487. };
  12488. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12489. if (this.gamepad) {
  12490. var camera = this.camera;
  12491. var RSValues = this.gamepad.rightStick;
  12492. if (RSValues.x != 0) {
  12493. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12494. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12495. camera.inertialAlphaOffset += normalizedRX;
  12496. }
  12497. }
  12498. if (RSValues.y != 0) {
  12499. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12500. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12501. camera.inertialBetaOffset += normalizedRY;
  12502. }
  12503. }
  12504. var LSValues = this.gamepad.leftStick;
  12505. if (LSValues.y != 0) {
  12506. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12507. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12508. this.camera.inertialRadiusOffset -= normalizedLY;
  12509. }
  12510. }
  12511. }
  12512. };
  12513. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12514. // Only the first gamepad can control the camera
  12515. if (gamepad.index === 0) {
  12516. this.gamepad = gamepad;
  12517. }
  12518. };
  12519. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12520. return "ArcRotateCameraGamepadInput";
  12521. };
  12522. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12523. return "gamepad";
  12524. };
  12525. __decorate([
  12526. BABYLON.serialize()
  12527. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12528. __decorate([
  12529. BABYLON.serialize()
  12530. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12531. return ArcRotateCameraGamepadInput;
  12532. }());
  12533. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12534. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12535. })(BABYLON || (BABYLON = {}));
  12536. var BABYLON;
  12537. (function (BABYLON) {
  12538. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12539. function ArcRotateCameraVRDeviceOrientationInput() {
  12540. this.alphaCorrection = 1;
  12541. this.betaCorrection = 1;
  12542. this.gammaCorrection = 1;
  12543. this._alpha = 0;
  12544. this._beta = 0;
  12545. this._gamma = 0;
  12546. this._dirty = false;
  12547. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12548. }
  12549. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12550. this.camera.attachControl(element, noPreventDefault);
  12551. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12552. };
  12553. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12554. var camera = this.camera;
  12555. this._alpha = +evt.alpha | 0;
  12556. this._beta = +evt.beta | 0;
  12557. this._gamma = +evt.gamma | 0;
  12558. this._dirty = true;
  12559. };
  12560. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12561. if (this._dirty) {
  12562. this._dirty = false;
  12563. if (this._gamma < 0) {
  12564. this._gamma = 180 + this._gamma;
  12565. }
  12566. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12567. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12568. }
  12569. };
  12570. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12571. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12572. };
  12573. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12574. return "ArcRotateCameraVRDeviceOrientationInput";
  12575. };
  12576. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12577. return "VRDeviceOrientation";
  12578. };
  12579. return ArcRotateCameraVRDeviceOrientationInput;
  12580. }());
  12581. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12582. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12583. })(BABYLON || (BABYLON = {}));
  12584. var BABYLON;
  12585. (function (BABYLON) {
  12586. var TargetCamera = (function (_super) {
  12587. __extends(TargetCamera, _super);
  12588. function TargetCamera(name, position, scene) {
  12589. _super.call(this, name, position, scene);
  12590. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12591. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12592. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12593. this.speed = 2.0;
  12594. this.noRotationConstraint = false;
  12595. this.lockedTarget = null;
  12596. this._currentTarget = BABYLON.Vector3.Zero();
  12597. this._viewMatrix = BABYLON.Matrix.Zero();
  12598. this._camMatrix = BABYLON.Matrix.Zero();
  12599. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12600. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12601. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12602. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12603. this._lookAtTemp = BABYLON.Matrix.Zero();
  12604. this._tempMatrix = BABYLON.Matrix.Zero();
  12605. }
  12606. TargetCamera.prototype.getFrontPosition = function (distance) {
  12607. var direction = this.getTarget().subtract(this.position);
  12608. direction.normalize();
  12609. direction.scaleInPlace(distance);
  12610. return this.globalPosition.add(direction);
  12611. };
  12612. TargetCamera.prototype._getLockedTargetPosition = function () {
  12613. if (!this.lockedTarget) {
  12614. return null;
  12615. }
  12616. return this.lockedTarget.position || this.lockedTarget;
  12617. };
  12618. // Cache
  12619. TargetCamera.prototype._initCache = function () {
  12620. _super.prototype._initCache.call(this);
  12621. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12622. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12623. };
  12624. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12625. if (!ignoreParentClass) {
  12626. _super.prototype._updateCache.call(this);
  12627. }
  12628. var lockedTargetPosition = this._getLockedTargetPosition();
  12629. if (!lockedTargetPosition) {
  12630. this._cache.lockedTarget = null;
  12631. }
  12632. else {
  12633. if (!this._cache.lockedTarget) {
  12634. this._cache.lockedTarget = lockedTargetPosition.clone();
  12635. }
  12636. else {
  12637. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12638. }
  12639. }
  12640. this._cache.rotation.copyFrom(this.rotation);
  12641. };
  12642. // Synchronized
  12643. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12644. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12645. return false;
  12646. }
  12647. var lockedTargetPosition = this._getLockedTargetPosition();
  12648. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12649. && this._cache.rotation.equals(this.rotation);
  12650. };
  12651. // Methods
  12652. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12653. var engine = this.getEngine();
  12654. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12655. };
  12656. // Target
  12657. TargetCamera.prototype.setTarget = function (target) {
  12658. this.upVector.normalize();
  12659. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12660. this._camMatrix.invert();
  12661. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12662. var vDir = target.subtract(this.position);
  12663. if (vDir.x >= 0.0) {
  12664. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12665. }
  12666. else {
  12667. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12668. }
  12669. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12670. if (isNaN(this.rotation.x)) {
  12671. this.rotation.x = 0;
  12672. }
  12673. if (isNaN(this.rotation.y)) {
  12674. this.rotation.y = 0;
  12675. }
  12676. if (isNaN(this.rotation.z)) {
  12677. this.rotation.z = 0;
  12678. }
  12679. };
  12680. TargetCamera.prototype.getTarget = function () {
  12681. return this._currentTarget;
  12682. };
  12683. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12684. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12685. };
  12686. TargetCamera.prototype._updatePosition = function () {
  12687. this.position.addInPlace(this.cameraDirection);
  12688. };
  12689. TargetCamera.prototype._checkInputs = function () {
  12690. var needToMove = this._decideIfNeedsToMove();
  12691. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12692. // Move
  12693. if (needToMove) {
  12694. this._updatePosition();
  12695. }
  12696. // Rotate
  12697. if (needToRotate) {
  12698. this.rotation.x += this.cameraRotation.x;
  12699. this.rotation.y += this.cameraRotation.y;
  12700. if (!this.noRotationConstraint) {
  12701. var limit = (Math.PI / 2) * 0.95;
  12702. if (this.rotation.x > limit)
  12703. this.rotation.x = limit;
  12704. if (this.rotation.x < -limit)
  12705. this.rotation.x = -limit;
  12706. }
  12707. }
  12708. // Inertia
  12709. if (needToMove) {
  12710. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12711. this.cameraDirection.x = 0;
  12712. }
  12713. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12714. this.cameraDirection.y = 0;
  12715. }
  12716. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12717. this.cameraDirection.z = 0;
  12718. }
  12719. this.cameraDirection.scaleInPlace(this.inertia);
  12720. }
  12721. if (needToRotate) {
  12722. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12723. this.cameraRotation.x = 0;
  12724. }
  12725. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12726. this.cameraRotation.y = 0;
  12727. }
  12728. this.cameraRotation.scaleInPlace(this.inertia);
  12729. }
  12730. _super.prototype._checkInputs.call(this);
  12731. };
  12732. TargetCamera.prototype._getViewMatrix = function () {
  12733. if (!this.lockedTarget) {
  12734. // Compute
  12735. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12736. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12737. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12738. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12739. this._lookAtTemp.invert();
  12740. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12741. }
  12742. else {
  12743. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12744. }
  12745. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12746. // Computing target and final matrix
  12747. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12748. }
  12749. else {
  12750. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12751. }
  12752. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12753. return this._viewMatrix;
  12754. };
  12755. TargetCamera.prototype._getVRViewMatrix = function () {
  12756. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12757. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12758. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12759. // Computing target and final matrix
  12760. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12761. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12762. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12763. return this._viewMatrix;
  12764. };
  12765. /**
  12766. * @override
  12767. * Override Camera.createRigCamera
  12768. */
  12769. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12770. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12771. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12772. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12773. rigCamera._cameraRigParams = {};
  12774. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12775. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12776. }
  12777. return rigCamera;
  12778. }
  12779. return null;
  12780. };
  12781. /**
  12782. * @override
  12783. * Override Camera._updateRigCameras
  12784. */
  12785. TargetCamera.prototype._updateRigCameras = function () {
  12786. switch (this.cameraRigMode) {
  12787. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12788. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12789. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12790. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12791. case BABYLON.Camera.RIG_MODE_VR:
  12792. var camLeft = this._rigCameras[0];
  12793. var camRight = this._rigCameras[1];
  12794. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12795. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12796. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12797. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12798. camLeft.position.copyFrom(this.position);
  12799. camRight.position.copyFrom(this.position);
  12800. }
  12801. else {
  12802. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12803. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12804. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12805. camLeft.setTarget(this.getTarget());
  12806. camRight.setTarget(this.getTarget());
  12807. }
  12808. break;
  12809. }
  12810. _super.prototype._updateRigCameras.call(this);
  12811. };
  12812. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12813. if (!this._rigCamTransformMatrix) {
  12814. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12815. }
  12816. var target = this.getTarget();
  12817. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12818. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12819. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12820. };
  12821. TargetCamera.prototype.getTypeName = function () {
  12822. return "TargetCamera";
  12823. };
  12824. __decorate([
  12825. BABYLON.serializeAsVector3()
  12826. ], TargetCamera.prototype, "rotation", void 0);
  12827. __decorate([
  12828. BABYLON.serialize()
  12829. ], TargetCamera.prototype, "speed", void 0);
  12830. __decorate([
  12831. BABYLON.serializeAsMeshReference("lockedTargetId")
  12832. ], TargetCamera.prototype, "lockedTarget", void 0);
  12833. return TargetCamera;
  12834. }(BABYLON.Camera));
  12835. BABYLON.TargetCamera = TargetCamera;
  12836. })(BABYLON || (BABYLON = {}));
  12837. var BABYLON;
  12838. (function (BABYLON) {
  12839. var FreeCamera = (function (_super) {
  12840. __extends(FreeCamera, _super);
  12841. function FreeCamera(name, position, scene) {
  12842. var _this = this;
  12843. _super.call(this, name, position, scene);
  12844. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12845. this.checkCollisions = false;
  12846. this.applyGravity = false;
  12847. this._collider = new BABYLON.Collider();
  12848. this._needMoveForGravity = false;
  12849. this._oldPosition = BABYLON.Vector3.Zero();
  12850. this._diffPosition = BABYLON.Vector3.Zero();
  12851. this._newPosition = BABYLON.Vector3.Zero();
  12852. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12853. if (collidedMesh === void 0) { collidedMesh = null; }
  12854. //TODO move this to the collision coordinator!
  12855. if (_this.getScene().workerCollisions)
  12856. newPosition.multiplyInPlace(_this._collider.radius);
  12857. var updatePosition = function (newPos) {
  12858. _this._newPosition.copyFrom(newPos);
  12859. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12860. var oldPosition = _this.position.clone();
  12861. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12862. _this.position.addInPlace(_this._diffPosition);
  12863. if (_this.onCollide && collidedMesh) {
  12864. _this.onCollide(collidedMesh);
  12865. }
  12866. }
  12867. };
  12868. updatePosition(newPosition);
  12869. };
  12870. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12871. this.inputs.addKeyboard().addMouse();
  12872. }
  12873. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12874. //-- begin properties for backward compatibility for inputs
  12875. get: function () {
  12876. var mouse = this.inputs.attached["mouse"];
  12877. if (mouse)
  12878. return mouse.angularSensibility;
  12879. },
  12880. set: function (value) {
  12881. var mouse = this.inputs.attached["mouse"];
  12882. if (mouse)
  12883. mouse.angularSensibility = value;
  12884. },
  12885. enumerable: true,
  12886. configurable: true
  12887. });
  12888. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12889. get: function () {
  12890. var keyboard = this.inputs.attached["keyboard"];
  12891. if (keyboard)
  12892. return keyboard.keysUp;
  12893. },
  12894. set: function (value) {
  12895. var keyboard = this.inputs.attached["keyboard"];
  12896. if (keyboard)
  12897. keyboard.keysUp = value;
  12898. },
  12899. enumerable: true,
  12900. configurable: true
  12901. });
  12902. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12903. get: function () {
  12904. var keyboard = this.inputs.attached["keyboard"];
  12905. if (keyboard)
  12906. return keyboard.keysDown;
  12907. },
  12908. set: function (value) {
  12909. var keyboard = this.inputs.attached["keyboard"];
  12910. if (keyboard)
  12911. keyboard.keysDown = value;
  12912. },
  12913. enumerable: true,
  12914. configurable: true
  12915. });
  12916. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12917. get: function () {
  12918. var keyboard = this.inputs.attached["keyboard"];
  12919. if (keyboard)
  12920. return keyboard.keysLeft;
  12921. },
  12922. set: function (value) {
  12923. var keyboard = this.inputs.attached["keyboard"];
  12924. if (keyboard)
  12925. keyboard.keysLeft = value;
  12926. },
  12927. enumerable: true,
  12928. configurable: true
  12929. });
  12930. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12931. get: function () {
  12932. var keyboard = this.inputs.attached["keyboard"];
  12933. if (keyboard)
  12934. return keyboard.keysRight;
  12935. },
  12936. set: function (value) {
  12937. var keyboard = this.inputs.attached["keyboard"];
  12938. if (keyboard)
  12939. keyboard.keysRight = value;
  12940. },
  12941. enumerable: true,
  12942. configurable: true
  12943. });
  12944. // Controls
  12945. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12946. this.inputs.attachElement(element, noPreventDefault);
  12947. };
  12948. FreeCamera.prototype.detachControl = function (element) {
  12949. this.inputs.detachElement(element);
  12950. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12951. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12952. };
  12953. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12954. var globalPosition;
  12955. if (this.parent) {
  12956. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12957. }
  12958. else {
  12959. globalPosition = this.position;
  12960. }
  12961. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12962. this._collider.radius = this.ellipsoid;
  12963. //no need for clone, as long as gravity is not on.
  12964. var actualVelocity = velocity;
  12965. //add gravity to the velocity to prevent the dual-collision checking
  12966. if (this.applyGravity) {
  12967. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12968. actualVelocity = velocity.add(this.getScene().gravity);
  12969. }
  12970. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12971. };
  12972. FreeCamera.prototype._checkInputs = function () {
  12973. if (!this._localDirection) {
  12974. this._localDirection = BABYLON.Vector3.Zero();
  12975. this._transformedDirection = BABYLON.Vector3.Zero();
  12976. }
  12977. this.inputs.checkInputs();
  12978. _super.prototype._checkInputs.call(this);
  12979. };
  12980. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12981. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12982. };
  12983. FreeCamera.prototype._updatePosition = function () {
  12984. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  12985. this._collideWithWorld(this.cameraDirection);
  12986. }
  12987. else {
  12988. this.position.addInPlace(this.cameraDirection);
  12989. }
  12990. };
  12991. FreeCamera.prototype.dispose = function () {
  12992. this.inputs.clear();
  12993. _super.prototype.dispose.call(this);
  12994. };
  12995. FreeCamera.prototype.getTypeName = function () {
  12996. return "FreeCamera";
  12997. };
  12998. __decorate([
  12999. BABYLON.serializeAsVector3()
  13000. ], FreeCamera.prototype, "ellipsoid", void 0);
  13001. __decorate([
  13002. BABYLON.serialize()
  13003. ], FreeCamera.prototype, "checkCollisions", void 0);
  13004. __decorate([
  13005. BABYLON.serialize()
  13006. ], FreeCamera.prototype, "applyGravity", void 0);
  13007. return FreeCamera;
  13008. }(BABYLON.TargetCamera));
  13009. BABYLON.FreeCamera = FreeCamera;
  13010. })(BABYLON || (BABYLON = {}));
  13011. var BABYLON;
  13012. (function (BABYLON) {
  13013. var FreeCameraInputsManager = (function (_super) {
  13014. __extends(FreeCameraInputsManager, _super);
  13015. function FreeCameraInputsManager(camera) {
  13016. _super.call(this, camera);
  13017. }
  13018. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13019. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13020. return this;
  13021. };
  13022. FreeCameraInputsManager.prototype.addMouse = function () {
  13023. this.add(new BABYLON.FreeCameraMouseInput());
  13024. return this;
  13025. };
  13026. FreeCameraInputsManager.prototype.addGamepad = function () {
  13027. this.add(new BABYLON.FreeCameraGamepadInput());
  13028. return this;
  13029. };
  13030. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13031. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13032. return this;
  13033. };
  13034. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13035. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13036. return this;
  13037. };
  13038. FreeCameraInputsManager.prototype.addTouch = function () {
  13039. this.add(new BABYLON.FreeCameraTouchInput());
  13040. return this;
  13041. };
  13042. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13043. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13044. return this;
  13045. };
  13046. return FreeCameraInputsManager;
  13047. }(BABYLON.CameraInputsManager));
  13048. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13049. })(BABYLON || (BABYLON = {}));
  13050. var BABYLON;
  13051. (function (BABYLON) {
  13052. var FollowCamera = (function (_super) {
  13053. __extends(FollowCamera, _super);
  13054. function FollowCamera(name, position, scene, target) {
  13055. _super.call(this, name, position, scene);
  13056. this.radius = 12;
  13057. this.rotationOffset = 0;
  13058. this.heightOffset = 4;
  13059. this.cameraAcceleration = 0.05;
  13060. this.maxCameraSpeed = 20;
  13061. this.target = target;
  13062. }
  13063. FollowCamera.prototype.getRadians = function (degrees) {
  13064. return degrees * Math.PI / 180;
  13065. };
  13066. FollowCamera.prototype.follow = function (cameraTarget) {
  13067. if (!cameraTarget)
  13068. return;
  13069. var yRotation;
  13070. if (cameraTarget.rotationQuaternion) {
  13071. var rotMatrix = new BABYLON.Matrix();
  13072. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13073. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13074. }
  13075. else {
  13076. yRotation = cameraTarget.rotation.y;
  13077. }
  13078. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13079. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13080. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13081. var dx = targetX - this.position.x;
  13082. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13083. var dz = (targetZ) - this.position.z;
  13084. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13085. var vy = dy * this.cameraAcceleration;
  13086. var vz = dz * this.cameraAcceleration * 2;
  13087. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13088. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13089. }
  13090. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13091. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13092. }
  13093. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13094. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13095. }
  13096. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13097. this.setTarget(cameraTarget.position);
  13098. };
  13099. FollowCamera.prototype._checkInputs = function () {
  13100. _super.prototype._checkInputs.call(this);
  13101. this.follow(this.target);
  13102. };
  13103. FollowCamera.prototype.getTypeName = function () {
  13104. return "FollowCamera";
  13105. };
  13106. __decorate([
  13107. BABYLON.serialize()
  13108. ], FollowCamera.prototype, "radius", void 0);
  13109. __decorate([
  13110. BABYLON.serialize()
  13111. ], FollowCamera.prototype, "rotationOffset", void 0);
  13112. __decorate([
  13113. BABYLON.serialize()
  13114. ], FollowCamera.prototype, "heightOffset", void 0);
  13115. __decorate([
  13116. BABYLON.serialize()
  13117. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13118. __decorate([
  13119. BABYLON.serialize()
  13120. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13121. __decorate([
  13122. BABYLON.serializeAsMeshReference("lockedTargetId")
  13123. ], FollowCamera.prototype, "target", void 0);
  13124. return FollowCamera;
  13125. }(BABYLON.TargetCamera));
  13126. BABYLON.FollowCamera = FollowCamera;
  13127. var ArcFollowCamera = (function (_super) {
  13128. __extends(ArcFollowCamera, _super);
  13129. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13130. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13131. this.alpha = alpha;
  13132. this.beta = beta;
  13133. this.radius = radius;
  13134. this.target = target;
  13135. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13136. this.follow();
  13137. }
  13138. ArcFollowCamera.prototype.follow = function () {
  13139. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13140. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13141. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13142. this.position = this.target.position.add(this._cartesianCoordinates);
  13143. this.setTarget(this.target.position);
  13144. };
  13145. ArcFollowCamera.prototype._checkInputs = function () {
  13146. _super.prototype._checkInputs.call(this);
  13147. this.follow();
  13148. };
  13149. ArcFollowCamera.prototype.getTypeName = function () {
  13150. return "ArcFollowCamera";
  13151. };
  13152. return ArcFollowCamera;
  13153. }(BABYLON.TargetCamera));
  13154. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13155. })(BABYLON || (BABYLON = {}));
  13156. var BABYLON;
  13157. (function (BABYLON) {
  13158. // We're mainly based on the logic defined into the FreeCamera code
  13159. var TouchCamera = (function (_super) {
  13160. __extends(TouchCamera, _super);
  13161. //-- end properties for backward compatibility for inputs
  13162. function TouchCamera(name, position, scene) {
  13163. _super.call(this, name, position, scene);
  13164. this.inputs.addTouch();
  13165. }
  13166. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13167. //-- Begin properties for backward compatibility for inputs
  13168. get: function () {
  13169. var touch = this.inputs.attached["touch"];
  13170. if (touch)
  13171. return touch.touchAngularSensibility;
  13172. },
  13173. set: function (value) {
  13174. var touch = this.inputs.attached["touch"];
  13175. if (touch)
  13176. touch.touchAngularSensibility = value;
  13177. },
  13178. enumerable: true,
  13179. configurable: true
  13180. });
  13181. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13182. get: function () {
  13183. var touch = this.inputs.attached["touch"];
  13184. if (touch)
  13185. return touch.touchMoveSensibility;
  13186. },
  13187. set: function (value) {
  13188. var touch = this.inputs.attached["touch"];
  13189. if (touch)
  13190. touch.touchMoveSensibility = value;
  13191. },
  13192. enumerable: true,
  13193. configurable: true
  13194. });
  13195. TouchCamera.prototype.getTypeName = function () {
  13196. return "TouchCamera";
  13197. };
  13198. return TouchCamera;
  13199. }(BABYLON.FreeCamera));
  13200. BABYLON.TouchCamera = TouchCamera;
  13201. })(BABYLON || (BABYLON = {}));
  13202. var BABYLON;
  13203. (function (BABYLON) {
  13204. var ArcRotateCamera = (function (_super) {
  13205. __extends(ArcRotateCamera, _super);
  13206. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13207. var _this = this;
  13208. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13209. this.inertialAlphaOffset = 0;
  13210. this.inertialBetaOffset = 0;
  13211. this.inertialRadiusOffset = 0;
  13212. this.lowerAlphaLimit = null;
  13213. this.upperAlphaLimit = null;
  13214. this.lowerBetaLimit = 0.01;
  13215. this.upperBetaLimit = Math.PI;
  13216. this.lowerRadiusLimit = null;
  13217. this.upperRadiusLimit = null;
  13218. this.inertialPanningX = 0;
  13219. this.inertialPanningY = 0;
  13220. //-- end properties for backward compatibility for inputs
  13221. this.zoomOnFactor = 1;
  13222. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13223. this.allowUpsideDown = true;
  13224. this._viewMatrix = new BABYLON.Matrix();
  13225. // Panning
  13226. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13227. this.checkCollisions = false;
  13228. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13229. this._collider = new BABYLON.Collider();
  13230. this._previousPosition = BABYLON.Vector3.Zero();
  13231. this._collisionVelocity = BABYLON.Vector3.Zero();
  13232. this._newPosition = BABYLON.Vector3.Zero();
  13233. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13234. if (collidedMesh === void 0) { collidedMesh = null; }
  13235. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13236. newPosition.multiplyInPlace(_this._collider.radius);
  13237. }
  13238. if (!collidedMesh) {
  13239. _this._previousPosition.copyFrom(_this.position);
  13240. }
  13241. else {
  13242. _this.setPosition(newPosition);
  13243. if (_this.onCollide) {
  13244. _this.onCollide(collidedMesh);
  13245. }
  13246. }
  13247. // Recompute because of constraints
  13248. var cosa = Math.cos(_this.alpha);
  13249. var sina = Math.sin(_this.alpha);
  13250. var cosb = Math.cos(_this.beta);
  13251. var sinb = Math.sin(_this.beta);
  13252. if (sinb === 0) {
  13253. sinb = 0.0001;
  13254. }
  13255. var target = _this._getTargetPosition();
  13256. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13257. _this.position.copyFrom(_this._newPosition);
  13258. var up = _this.upVector;
  13259. if (_this.allowUpsideDown && _this.beta < 0) {
  13260. up = up.clone();
  13261. up = up.negate();
  13262. }
  13263. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13264. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13265. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13266. _this._collisionTriggered = false;
  13267. };
  13268. if (!target) {
  13269. this.target = BABYLON.Vector3.Zero();
  13270. }
  13271. else {
  13272. this.target = target;
  13273. }
  13274. this.alpha = alpha;
  13275. this.beta = beta;
  13276. this.radius = radius;
  13277. this.getViewMatrix();
  13278. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13279. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13280. }
  13281. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13282. //-- begin properties for backward compatibility for inputs
  13283. get: function () {
  13284. var pointers = this.inputs.attached["pointers"];
  13285. if (pointers)
  13286. return pointers.angularSensibilityX;
  13287. },
  13288. set: function (value) {
  13289. var pointers = this.inputs.attached["pointers"];
  13290. if (pointers) {
  13291. pointers.angularSensibilityX = value;
  13292. }
  13293. },
  13294. enumerable: true,
  13295. configurable: true
  13296. });
  13297. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13298. get: function () {
  13299. var pointers = this.inputs.attached["pointers"];
  13300. if (pointers)
  13301. return pointers.angularSensibilityY;
  13302. },
  13303. set: function (value) {
  13304. var pointers = this.inputs.attached["pointers"];
  13305. if (pointers) {
  13306. pointers.angularSensibilityY = value;
  13307. }
  13308. },
  13309. enumerable: true,
  13310. configurable: true
  13311. });
  13312. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13313. get: function () {
  13314. var pointers = this.inputs.attached["pointers"];
  13315. if (pointers)
  13316. return pointers.pinchPrecision;
  13317. },
  13318. set: function (value) {
  13319. var pointers = this.inputs.attached["pointers"];
  13320. if (pointers) {
  13321. pointers.pinchPrecision = value;
  13322. }
  13323. },
  13324. enumerable: true,
  13325. configurable: true
  13326. });
  13327. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13328. get: function () {
  13329. var pointers = this.inputs.attached["pointers"];
  13330. if (pointers)
  13331. return pointers.panningSensibility;
  13332. },
  13333. set: function (value) {
  13334. var pointers = this.inputs.attached["pointers"];
  13335. if (pointers) {
  13336. pointers.panningSensibility = value;
  13337. }
  13338. },
  13339. enumerable: true,
  13340. configurable: true
  13341. });
  13342. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13343. get: function () {
  13344. var keyboard = this.inputs.attached["keyboard"];
  13345. if (keyboard)
  13346. return keyboard.keysUp;
  13347. },
  13348. set: function (value) {
  13349. var keyboard = this.inputs.attached["keyboard"];
  13350. if (keyboard)
  13351. keyboard.keysUp = value;
  13352. },
  13353. enumerable: true,
  13354. configurable: true
  13355. });
  13356. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13357. get: function () {
  13358. var keyboard = this.inputs.attached["keyboard"];
  13359. if (keyboard)
  13360. return keyboard.keysDown;
  13361. },
  13362. set: function (value) {
  13363. var keyboard = this.inputs.attached["keyboard"];
  13364. if (keyboard)
  13365. keyboard.keysDown = value;
  13366. },
  13367. enumerable: true,
  13368. configurable: true
  13369. });
  13370. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13371. get: function () {
  13372. var keyboard = this.inputs.attached["keyboard"];
  13373. if (keyboard)
  13374. return keyboard.keysLeft;
  13375. },
  13376. set: function (value) {
  13377. var keyboard = this.inputs.attached["keyboard"];
  13378. if (keyboard)
  13379. keyboard.keysLeft = value;
  13380. },
  13381. enumerable: true,
  13382. configurable: true
  13383. });
  13384. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13385. get: function () {
  13386. var keyboard = this.inputs.attached["keyboard"];
  13387. if (keyboard)
  13388. return keyboard.keysRight;
  13389. },
  13390. set: function (value) {
  13391. var keyboard = this.inputs.attached["keyboard"];
  13392. if (keyboard)
  13393. keyboard.keysRight = value;
  13394. },
  13395. enumerable: true,
  13396. configurable: true
  13397. });
  13398. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13399. get: function () {
  13400. var mousewheel = this.inputs.attached["mousewheel"];
  13401. if (mousewheel)
  13402. return mousewheel.wheelPrecision;
  13403. },
  13404. set: function (value) {
  13405. var mousewheel = this.inputs.attached["mousewheel"];
  13406. if (mousewheel)
  13407. mousewheel.wheelPrecision = value;
  13408. },
  13409. enumerable: true,
  13410. configurable: true
  13411. });
  13412. // Cache
  13413. ArcRotateCamera.prototype._initCache = function () {
  13414. _super.prototype._initCache.call(this);
  13415. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13416. this._cache.alpha = undefined;
  13417. this._cache.beta = undefined;
  13418. this._cache.radius = undefined;
  13419. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13420. };
  13421. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13422. if (!ignoreParentClass) {
  13423. _super.prototype._updateCache.call(this);
  13424. }
  13425. this._cache.target.copyFrom(this._getTargetPosition());
  13426. this._cache.alpha = this.alpha;
  13427. this._cache.beta = this.beta;
  13428. this._cache.radius = this.radius;
  13429. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13430. };
  13431. ArcRotateCamera.prototype._getTargetPosition = function () {
  13432. if (this.target.getAbsolutePosition) {
  13433. return this.target.getAbsolutePosition();
  13434. }
  13435. return this.target;
  13436. };
  13437. // Synchronized
  13438. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13439. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13440. return false;
  13441. return this._cache.target.equals(this.target)
  13442. && this._cache.alpha === this.alpha
  13443. && this._cache.beta === this.beta
  13444. && this._cache.radius === this.radius
  13445. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13446. };
  13447. // Methods
  13448. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13449. var _this = this;
  13450. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13451. this._useCtrlForPanning = useCtrlForPanning;
  13452. this.inputs.attachElement(element, noPreventDefault);
  13453. this._reset = function () {
  13454. _this.inertialAlphaOffset = 0;
  13455. _this.inertialBetaOffset = 0;
  13456. _this.inertialRadiusOffset = 0;
  13457. };
  13458. };
  13459. ArcRotateCamera.prototype.detachControl = function (element) {
  13460. this.inputs.detachElement(element);
  13461. if (this._reset) {
  13462. this._reset();
  13463. }
  13464. };
  13465. ArcRotateCamera.prototype._checkInputs = function () {
  13466. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13467. if (this._collisionTriggered) {
  13468. return;
  13469. }
  13470. this.inputs.checkInputs();
  13471. // Inertia
  13472. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13473. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13474. this.beta += this.inertialBetaOffset;
  13475. this.radius -= this.inertialRadiusOffset;
  13476. this.inertialAlphaOffset *= this.inertia;
  13477. this.inertialBetaOffset *= this.inertia;
  13478. this.inertialRadiusOffset *= this.inertia;
  13479. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13480. this.inertialAlphaOffset = 0;
  13481. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13482. this.inertialBetaOffset = 0;
  13483. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13484. this.inertialRadiusOffset = 0;
  13485. }
  13486. // Panning inertia
  13487. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13488. if (!this._localDirection) {
  13489. this._localDirection = BABYLON.Vector3.Zero();
  13490. this._transformedDirection = BABYLON.Vector3.Zero();
  13491. }
  13492. this.inertialPanningX *= this.inertia;
  13493. this.inertialPanningY *= this.inertia;
  13494. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13495. this.inertialPanningX = 0;
  13496. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13497. this.inertialPanningY = 0;
  13498. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13499. this._localDirection.multiplyInPlace(this.panningAxis);
  13500. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13501. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13502. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13503. if (!this.panningAxis.y) {
  13504. this._transformedDirection.y = 0;
  13505. }
  13506. this.target.addInPlace(this._transformedDirection);
  13507. }
  13508. // Limits
  13509. this._checkLimits();
  13510. _super.prototype._checkInputs.call(this);
  13511. };
  13512. ArcRotateCamera.prototype._checkLimits = function () {
  13513. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13514. if (this.allowUpsideDown && this.beta > Math.PI) {
  13515. this.beta = this.beta - (2 * Math.PI);
  13516. }
  13517. }
  13518. else {
  13519. if (this.beta < this.lowerBetaLimit) {
  13520. this.beta = this.lowerBetaLimit;
  13521. }
  13522. }
  13523. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13524. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13525. this.beta = this.beta + (2 * Math.PI);
  13526. }
  13527. }
  13528. else {
  13529. if (this.beta > this.upperBetaLimit) {
  13530. this.beta = this.upperBetaLimit;
  13531. }
  13532. }
  13533. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13534. this.alpha = this.lowerAlphaLimit;
  13535. }
  13536. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13537. this.alpha = this.upperAlphaLimit;
  13538. }
  13539. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13540. this.radius = this.lowerRadiusLimit;
  13541. }
  13542. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13543. this.radius = this.upperRadiusLimit;
  13544. }
  13545. };
  13546. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13547. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13548. this.radius = radiusv3.length();
  13549. // Alpha
  13550. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13551. if (radiusv3.z < 0) {
  13552. this.alpha = 2 * Math.PI - this.alpha;
  13553. }
  13554. // Beta
  13555. this.beta = Math.acos(radiusv3.y / this.radius);
  13556. this._checkLimits();
  13557. };
  13558. ArcRotateCamera.prototype.setPosition = function (position) {
  13559. if (this.position.equals(position)) {
  13560. return;
  13561. }
  13562. this.position = position;
  13563. this.rebuildAnglesAndRadius();
  13564. };
  13565. ArcRotateCamera.prototype.setTarget = function (target) {
  13566. if (this._getTargetPosition().equals(target)) {
  13567. return;
  13568. }
  13569. this.target = target;
  13570. this.rebuildAnglesAndRadius();
  13571. };
  13572. ArcRotateCamera.prototype._getViewMatrix = function () {
  13573. // Compute
  13574. var cosa = Math.cos(this.alpha);
  13575. var sina = Math.sin(this.alpha);
  13576. var cosb = Math.cos(this.beta);
  13577. var sinb = Math.sin(this.beta);
  13578. if (sinb === 0) {
  13579. sinb = 0.0001;
  13580. }
  13581. var target = this._getTargetPosition();
  13582. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13583. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13584. this._collider.radius = this.collisionRadius;
  13585. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13586. this._collisionTriggered = true;
  13587. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13588. }
  13589. else {
  13590. this.position.copyFrom(this._newPosition);
  13591. var up = this.upVector;
  13592. if (this.allowUpsideDown && this.beta < 0) {
  13593. up = up.clone();
  13594. up = up.negate();
  13595. }
  13596. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13597. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13598. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13599. }
  13600. return this._viewMatrix;
  13601. };
  13602. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13603. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13604. meshes = meshes || this.getScene().meshes;
  13605. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13606. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13607. this.radius = distance * this.zoomOnFactor;
  13608. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13609. };
  13610. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13611. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13612. var meshesOrMinMaxVector;
  13613. var distance;
  13614. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13615. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13616. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13617. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13618. }
  13619. else {
  13620. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13621. distance = meshesOrMinMaxVectorAndDistance.distance;
  13622. }
  13623. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13624. if (!doNotUpdateMaxZ) {
  13625. this.maxZ = distance * 2;
  13626. }
  13627. };
  13628. /**
  13629. * @override
  13630. * Override Camera.createRigCamera
  13631. */
  13632. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13633. switch (this.cameraRigMode) {
  13634. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13637. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13638. case BABYLON.Camera.RIG_MODE_VR:
  13639. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13640. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13641. rigCam._cameraRigParams = {};
  13642. return rigCam;
  13643. }
  13644. return null;
  13645. };
  13646. /**
  13647. * @override
  13648. * Override Camera._updateRigCameras
  13649. */
  13650. ArcRotateCamera.prototype._updateRigCameras = function () {
  13651. switch (this.cameraRigMode) {
  13652. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13653. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13656. case BABYLON.Camera.RIG_MODE_VR:
  13657. var camLeft = this._rigCameras[0];
  13658. var camRight = this._rigCameras[1];
  13659. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13660. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13661. camLeft.beta = camRight.beta = this.beta;
  13662. camLeft.radius = camRight.radius = this.radius;
  13663. break;
  13664. }
  13665. _super.prototype._updateRigCameras.call(this);
  13666. };
  13667. ArcRotateCamera.prototype.dispose = function () {
  13668. this.inputs.clear();
  13669. _super.prototype.dispose.call(this);
  13670. };
  13671. ArcRotateCamera.prototype.getTypeName = function () {
  13672. return "ArcRotateCamera";
  13673. };
  13674. __decorate([
  13675. BABYLON.serialize()
  13676. ], ArcRotateCamera.prototype, "alpha", void 0);
  13677. __decorate([
  13678. BABYLON.serialize()
  13679. ], ArcRotateCamera.prototype, "beta", void 0);
  13680. __decorate([
  13681. BABYLON.serialize()
  13682. ], ArcRotateCamera.prototype, "radius", void 0);
  13683. __decorate([
  13684. BABYLON.serializeAsVector3()
  13685. ], ArcRotateCamera.prototype, "target", void 0);
  13686. __decorate([
  13687. BABYLON.serialize()
  13688. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13689. __decorate([
  13690. BABYLON.serialize()
  13691. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13692. __decorate([
  13693. BABYLON.serialize()
  13694. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13695. __decorate([
  13696. BABYLON.serialize()
  13697. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13698. __decorate([
  13699. BABYLON.serialize()
  13700. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13701. __decorate([
  13702. BABYLON.serialize()
  13703. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13704. __decorate([
  13705. BABYLON.serialize()
  13706. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13707. __decorate([
  13708. BABYLON.serialize()
  13709. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13710. __decorate([
  13711. BABYLON.serialize()
  13712. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13713. __decorate([
  13714. BABYLON.serialize()
  13715. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13716. __decorate([
  13717. BABYLON.serialize()
  13718. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13719. __decorate([
  13720. BABYLON.serialize()
  13721. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13722. __decorate([
  13723. BABYLON.serialize()
  13724. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13725. return ArcRotateCamera;
  13726. }(BABYLON.TargetCamera));
  13727. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13728. })(BABYLON || (BABYLON = {}));
  13729. var BABYLON;
  13730. (function (BABYLON) {
  13731. var ArcRotateCameraInputsManager = (function (_super) {
  13732. __extends(ArcRotateCameraInputsManager, _super);
  13733. function ArcRotateCameraInputsManager(camera) {
  13734. _super.call(this, camera);
  13735. }
  13736. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13737. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13738. return this;
  13739. };
  13740. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13741. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13742. return this;
  13743. };
  13744. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13745. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13746. return this;
  13747. };
  13748. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13749. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13750. return this;
  13751. };
  13752. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13753. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13754. return this;
  13755. };
  13756. return ArcRotateCameraInputsManager;
  13757. }(BABYLON.CameraInputsManager));
  13758. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13759. })(BABYLON || (BABYLON = {}));
  13760. var BABYLON;
  13761. (function (BABYLON) {
  13762. var RenderingManager = (function () {
  13763. function RenderingManager(scene) {
  13764. this._renderingGroups = new Array();
  13765. this._scene = scene;
  13766. }
  13767. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13768. if (this._scene._activeParticleSystems.length === 0) {
  13769. return;
  13770. }
  13771. // Particles
  13772. var activeCamera = this._scene.activeCamera;
  13773. var beforeParticlesDate = BABYLON.Tools.Now;
  13774. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13775. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13776. if (particleSystem.renderingGroupId !== index) {
  13777. continue;
  13778. }
  13779. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13780. continue;
  13781. }
  13782. this._clearDepthBuffer();
  13783. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13784. this._scene._activeParticles += particleSystem.render();
  13785. }
  13786. }
  13787. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13788. };
  13789. RenderingManager.prototype._renderSprites = function (index) {
  13790. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13791. return;
  13792. }
  13793. // Sprites
  13794. var activeCamera = this._scene.activeCamera;
  13795. var beforeSpritessDate = BABYLON.Tools.Now;
  13796. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13797. var spriteManager = this._scene.spriteManagers[id];
  13798. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13799. this._clearDepthBuffer();
  13800. spriteManager.render();
  13801. }
  13802. }
  13803. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13804. };
  13805. RenderingManager.prototype._clearDepthBuffer = function () {
  13806. if (this._depthBufferAlreadyCleaned) {
  13807. return;
  13808. }
  13809. this._scene.getEngine().clear(0, false, true);
  13810. this._depthBufferAlreadyCleaned = true;
  13811. };
  13812. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13813. if (this._currentRenderSprites) {
  13814. this._renderSprites(this._currentIndex);
  13815. }
  13816. if (this._currentRenderParticles) {
  13817. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13818. }
  13819. };
  13820. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13821. this._currentActiveMeshes = activeMeshes;
  13822. this._currentRenderParticles = renderParticles;
  13823. this._currentRenderSprites = renderSprites;
  13824. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13825. this._depthBufferAlreadyCleaned = index == 0;
  13826. var renderingGroup = this._renderingGroups[index];
  13827. var needToStepBack = false;
  13828. this._currentIndex = index;
  13829. if (renderingGroup) {
  13830. this._clearDepthBuffer();
  13831. if (!renderingGroup.onBeforeTransparentRendering) {
  13832. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13833. }
  13834. if (!renderingGroup.render(customRenderFunction)) {
  13835. this._renderingGroups.splice(index, 1);
  13836. needToStepBack = true;
  13837. this._renderSpritesAndParticles();
  13838. }
  13839. }
  13840. else {
  13841. this._renderSpritesAndParticles();
  13842. }
  13843. if (needToStepBack) {
  13844. index--;
  13845. }
  13846. }
  13847. };
  13848. RenderingManager.prototype.reset = function () {
  13849. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13850. if (renderingGroup) {
  13851. renderingGroup.prepare();
  13852. }
  13853. });
  13854. };
  13855. RenderingManager.prototype.dispatch = function (subMesh) {
  13856. var mesh = subMesh.getMesh();
  13857. var renderingGroupId = mesh.renderingGroupId || 0;
  13858. if (!this._renderingGroups[renderingGroupId]) {
  13859. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13860. }
  13861. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13862. };
  13863. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13864. return RenderingManager;
  13865. }());
  13866. BABYLON.RenderingManager = RenderingManager;
  13867. })(BABYLON || (BABYLON = {}));
  13868. var BABYLON;
  13869. (function (BABYLON) {
  13870. var RenderingGroup = (function () {
  13871. function RenderingGroup(index, scene) {
  13872. this.index = index;
  13873. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13874. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13875. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13876. this._scene = scene;
  13877. }
  13878. RenderingGroup.prototype.render = function (customRenderFunction) {
  13879. if (customRenderFunction) {
  13880. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13881. return true;
  13882. }
  13883. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13884. if (this.onBeforeTransparentRendering) {
  13885. this.onBeforeTransparentRendering();
  13886. }
  13887. return false;
  13888. }
  13889. var engine = this._scene.getEngine();
  13890. // Opaque
  13891. var subIndex;
  13892. var submesh;
  13893. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13894. submesh = this._opaqueSubMeshes.data[subIndex];
  13895. submesh.render(false);
  13896. }
  13897. // Alpha test
  13898. engine.setAlphaTesting(true);
  13899. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13900. submesh = this._alphaTestSubMeshes.data[subIndex];
  13901. submesh.render(false);
  13902. }
  13903. engine.setAlphaTesting(false);
  13904. if (this.onBeforeTransparentRendering) {
  13905. this.onBeforeTransparentRendering();
  13906. }
  13907. // Transparent
  13908. if (this._transparentSubMeshes.length) {
  13909. // Sorting
  13910. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13911. submesh = this._transparentSubMeshes.data[subIndex];
  13912. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13913. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13914. }
  13915. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13916. sortedArray.sort(function (a, b) {
  13917. // Alpha index first
  13918. if (a._alphaIndex > b._alphaIndex) {
  13919. return 1;
  13920. }
  13921. if (a._alphaIndex < b._alphaIndex) {
  13922. return -1;
  13923. }
  13924. // Then distance to camera
  13925. if (a._distanceToCamera < b._distanceToCamera) {
  13926. return 1;
  13927. }
  13928. if (a._distanceToCamera > b._distanceToCamera) {
  13929. return -1;
  13930. }
  13931. return 0;
  13932. });
  13933. // Rendering
  13934. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13935. submesh = sortedArray[subIndex];
  13936. submesh.render(true);
  13937. }
  13938. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13939. }
  13940. return true;
  13941. };
  13942. RenderingGroup.prototype.prepare = function () {
  13943. this._opaqueSubMeshes.reset();
  13944. this._transparentSubMeshes.reset();
  13945. this._alphaTestSubMeshes.reset();
  13946. };
  13947. RenderingGroup.prototype.dispatch = function (subMesh) {
  13948. var material = subMesh.getMaterial();
  13949. var mesh = subMesh.getMesh();
  13950. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13951. this._transparentSubMeshes.push(subMesh);
  13952. }
  13953. else if (material.needAlphaTesting()) {
  13954. this._alphaTestSubMeshes.push(subMesh);
  13955. }
  13956. else {
  13957. this._opaqueSubMeshes.push(subMesh); // Opaque
  13958. }
  13959. };
  13960. return RenderingGroup;
  13961. }());
  13962. BABYLON.RenderingGroup = RenderingGroup;
  13963. })(BABYLON || (BABYLON = {}));
  13964. var BABYLON;
  13965. (function (BABYLON) {
  13966. /**
  13967. * Represents a scene to be rendered by the engine.
  13968. * @see http://doc.babylonjs.com/page.php?p=21911
  13969. */
  13970. var Scene = (function () {
  13971. /**
  13972. * @constructor
  13973. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  13974. */
  13975. function Scene(engine) {
  13976. // Members
  13977. this.autoClear = true;
  13978. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13979. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13980. this.forceWireframe = false;
  13981. this.forcePointsCloud = false;
  13982. this.forceShowBoundingBoxes = false;
  13983. this.animationsEnabled = true;
  13984. this.constantlyUpdateMeshUnderPointer = false;
  13985. // Events
  13986. /**
  13987. * An event triggered when the scene is disposed.
  13988. * @type {BABYLON.Observable}
  13989. */
  13990. this.onDisposeObservable = new BABYLON.Observable();
  13991. /**
  13992. * An event triggered before rendering the scene
  13993. * @type {BABYLON.Observable}
  13994. */
  13995. this.onBeforeRenderObservable = new BABYLON.Observable();
  13996. /**
  13997. * An event triggered after rendering the scene
  13998. * @type {BABYLON.Observable}
  13999. */
  14000. this.onAfterRenderObservable = new BABYLON.Observable();
  14001. /**
  14002. * An event triggered when the scene is ready
  14003. * @type {BABYLON.Observable}
  14004. */
  14005. this.onReadyObservable = new BABYLON.Observable();
  14006. /**
  14007. * An event triggered before rendering a camera
  14008. * @type {BABYLON.Observable}
  14009. */
  14010. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14011. /**
  14012. * An event triggered after rendering a camera
  14013. * @type {BABYLON.Observable}
  14014. */
  14015. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14016. /**
  14017. * An event triggered when a camera is created
  14018. * @type {BABYLON.Observable}
  14019. */
  14020. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14021. /**
  14022. * An event triggered when a camera is removed
  14023. * @type {BABYLON.Observable}
  14024. */
  14025. this.onCameraRemovedObservable = new BABYLON.Observable();
  14026. /**
  14027. * An event triggered when a light is created
  14028. * @type {BABYLON.Observable}
  14029. */
  14030. this.onNewLightAddedObservable = new BABYLON.Observable();
  14031. /**
  14032. * An event triggered when a light is removed
  14033. * @type {BABYLON.Observable}
  14034. */
  14035. this.onLightRemovedObservable = new BABYLON.Observable();
  14036. /**
  14037. * An event triggered when a geometry is created
  14038. * @type {BABYLON.Observable}
  14039. */
  14040. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14041. /**
  14042. * An event triggered when a geometry is removed
  14043. * @type {BABYLON.Observable}
  14044. */
  14045. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14046. /**
  14047. * An event triggered when a mesh is created
  14048. * @type {BABYLON.Observable}
  14049. */
  14050. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14051. /**
  14052. * An event triggered when a mesh is removed
  14053. * @type {BABYLON.Observable}
  14054. */
  14055. this.onMeshRemovedObservable = new BABYLON.Observable();
  14056. // Animations
  14057. this.animations = [];
  14058. 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
  14059. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14060. this._startingPointerTime = 0;
  14061. // Fog
  14062. /**
  14063. * is fog enabled on this scene.
  14064. * @type {boolean}
  14065. */
  14066. this.fogEnabled = true;
  14067. this.fogMode = Scene.FOGMODE_NONE;
  14068. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14069. this.fogDensity = 0.1;
  14070. this.fogStart = 0;
  14071. this.fogEnd = 1000.0;
  14072. // Lights
  14073. /**
  14074. * is shadow enabled on this scene.
  14075. * @type {boolean}
  14076. */
  14077. this.shadowsEnabled = true;
  14078. /**
  14079. * is light enabled on this scene.
  14080. * @type {boolean}
  14081. */
  14082. this.lightsEnabled = true;
  14083. /**
  14084. * All of the lights added to this scene.
  14085. * @see BABYLON.Light
  14086. * @type {BABYLON.Light[]}
  14087. */
  14088. this.lights = new Array();
  14089. // Cameras
  14090. /**
  14091. * All of the cameras added to this scene.
  14092. * @see BABYLON.Camera
  14093. * @type {BABYLON.Camera[]}
  14094. */
  14095. this.cameras = new Array();
  14096. this.activeCameras = new Array();
  14097. // Meshes
  14098. /**
  14099. * All of the (abstract) meshes added to this scene.
  14100. * @see BABYLON.AbstractMesh
  14101. * @type {BABYLON.AbstractMesh[]}
  14102. */
  14103. this.meshes = new Array();
  14104. // Geometries
  14105. this._geometries = new Array();
  14106. this.materials = new Array();
  14107. this.multiMaterials = new Array();
  14108. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14109. // Textures
  14110. this.texturesEnabled = true;
  14111. this.textures = new Array();
  14112. // Particles
  14113. this.particlesEnabled = true;
  14114. this.particleSystems = new Array();
  14115. // Sprites
  14116. this.spritesEnabled = true;
  14117. this.spriteManagers = new Array();
  14118. // Layers
  14119. this.layers = new Array();
  14120. // Skeletons
  14121. this.skeletonsEnabled = true;
  14122. this.skeletons = new Array();
  14123. // Lens flares
  14124. this.lensFlaresEnabled = true;
  14125. this.lensFlareSystems = new Array();
  14126. // Collisions
  14127. this.collisionsEnabled = true;
  14128. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14129. // Postprocesses
  14130. this.postProcessesEnabled = true;
  14131. // Customs render targets
  14132. this.renderTargetsEnabled = true;
  14133. this.dumpNextRenderTargets = false;
  14134. this.customRenderTargets = new Array();
  14135. // Imported meshes
  14136. this.importedMeshesFiles = new Array();
  14137. // Probes
  14138. this.probesEnabled = true;
  14139. this.reflectionProbes = new Array();
  14140. this._actionManagers = new Array();
  14141. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14142. // Procedural textures
  14143. this.proceduralTexturesEnabled = true;
  14144. this._proceduralTextures = new Array();
  14145. this.soundTracks = new Array();
  14146. this._audioEnabled = true;
  14147. this._headphone = false;
  14148. this._totalVertices = 0;
  14149. this._activeIndices = 0;
  14150. this._activeParticles = 0;
  14151. this._lastFrameDuration = 0;
  14152. this._evaluateActiveMeshesDuration = 0;
  14153. this._renderTargetsDuration = 0;
  14154. this._particlesDuration = 0;
  14155. this._renderDuration = 0;
  14156. this._spritesDuration = 0;
  14157. this._animationRatio = 0;
  14158. this._renderId = 0;
  14159. this._executeWhenReadyTimeoutId = -1;
  14160. this._intermediateRendering = false;
  14161. this._toBeDisposed = new BABYLON.SmartArray(256);
  14162. this._pendingData = []; //ANY
  14163. this._activeMeshes = new BABYLON.SmartArray(256);
  14164. this._processedMaterials = new BABYLON.SmartArray(256);
  14165. this._renderTargets = new BABYLON.SmartArray(256);
  14166. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14167. this._activeSkeletons = new BABYLON.SmartArray(32);
  14168. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14169. this._activeBones = 0;
  14170. this._activeAnimatables = new Array();
  14171. this._transformMatrix = BABYLON.Matrix.Zero();
  14172. this._edgesRenderers = new BABYLON.SmartArray(16);
  14173. this._uniqueIdCounter = 0;
  14174. this._engine = engine;
  14175. engine.scenes.push(this);
  14176. this._renderingManager = new BABYLON.RenderingManager(this);
  14177. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14178. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14179. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14180. if (BABYLON.OutlineRenderer) {
  14181. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14182. }
  14183. this.attachControl();
  14184. this._debugLayer = new BABYLON.DebugLayer(this);
  14185. if (BABYLON.SoundTrack) {
  14186. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14187. }
  14188. //simplification queue
  14189. if (BABYLON.SimplificationQueue) {
  14190. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14191. }
  14192. //collision coordinator initialization. For now legacy per default.
  14193. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14194. }
  14195. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14196. get: function () {
  14197. return Scene._FOGMODE_NONE;
  14198. },
  14199. enumerable: true,
  14200. configurable: true
  14201. });
  14202. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14203. get: function () {
  14204. return Scene._FOGMODE_EXP;
  14205. },
  14206. enumerable: true,
  14207. configurable: true
  14208. });
  14209. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14210. get: function () {
  14211. return Scene._FOGMODE_EXP2;
  14212. },
  14213. enumerable: true,
  14214. configurable: true
  14215. });
  14216. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14217. get: function () {
  14218. return Scene._FOGMODE_LINEAR;
  14219. },
  14220. enumerable: true,
  14221. configurable: true
  14222. });
  14223. Object.defineProperty(Scene.prototype, "onDispose", {
  14224. set: function (callback) {
  14225. if (this._onDisposeObserver) {
  14226. this.onDisposeObservable.remove(this._onDisposeObserver);
  14227. }
  14228. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14229. },
  14230. enumerable: true,
  14231. configurable: true
  14232. });
  14233. Object.defineProperty(Scene.prototype, "beforeRender", {
  14234. set: function (callback) {
  14235. if (this._onBeforeRenderObserver) {
  14236. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14237. }
  14238. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14239. },
  14240. enumerable: true,
  14241. configurable: true
  14242. });
  14243. Object.defineProperty(Scene.prototype, "afterRender", {
  14244. set: function (callback) {
  14245. if (this._onAfterRenderObserver) {
  14246. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14247. }
  14248. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14249. },
  14250. enumerable: true,
  14251. configurable: true
  14252. });
  14253. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14254. set: function (callback) {
  14255. if (this._onBeforeCameraRenderObserver) {
  14256. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14257. }
  14258. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14259. },
  14260. enumerable: true,
  14261. configurable: true
  14262. });
  14263. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14264. set: function (callback) {
  14265. if (this._onAfterCameraRenderObserver) {
  14266. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14267. }
  14268. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14269. },
  14270. enumerable: true,
  14271. configurable: true
  14272. });
  14273. Object.defineProperty(Scene.prototype, "debugLayer", {
  14274. // Properties
  14275. get: function () {
  14276. return this._debugLayer;
  14277. },
  14278. enumerable: true,
  14279. configurable: true
  14280. });
  14281. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14282. get: function () {
  14283. return this._workerCollisions;
  14284. },
  14285. set: function (enabled) {
  14286. enabled = (enabled && !!Worker);
  14287. this._workerCollisions = enabled;
  14288. if (this.collisionCoordinator) {
  14289. this.collisionCoordinator.destroy();
  14290. }
  14291. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14292. this.collisionCoordinator.init(this);
  14293. },
  14294. enumerable: true,
  14295. configurable: true
  14296. });
  14297. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14298. get: function () {
  14299. return this._selectionOctree;
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14305. /**
  14306. * The mesh that is currently under the pointer.
  14307. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14308. */
  14309. get: function () {
  14310. return this._pointerOverMesh;
  14311. },
  14312. enumerable: true,
  14313. configurable: true
  14314. });
  14315. Object.defineProperty(Scene.prototype, "pointerX", {
  14316. /**
  14317. * Current on-screen X position of the pointer
  14318. * @return {number} X position of the pointer
  14319. */
  14320. get: function () {
  14321. return this._pointerX;
  14322. },
  14323. enumerable: true,
  14324. configurable: true
  14325. });
  14326. Object.defineProperty(Scene.prototype, "pointerY", {
  14327. /**
  14328. * Current on-screen Y position of the pointer
  14329. * @return {number} Y position of the pointer
  14330. */
  14331. get: function () {
  14332. return this._pointerY;
  14333. },
  14334. enumerable: true,
  14335. configurable: true
  14336. });
  14337. Scene.prototype.getCachedMaterial = function () {
  14338. return this._cachedMaterial;
  14339. };
  14340. Scene.prototype.getBoundingBoxRenderer = function () {
  14341. return this._boundingBoxRenderer;
  14342. };
  14343. Scene.prototype.getOutlineRenderer = function () {
  14344. return this._outlineRenderer;
  14345. };
  14346. Scene.prototype.getEngine = function () {
  14347. return this._engine;
  14348. };
  14349. Scene.prototype.getTotalVertices = function () {
  14350. return this._totalVertices;
  14351. };
  14352. Scene.prototype.getActiveIndices = function () {
  14353. return this._activeIndices;
  14354. };
  14355. Scene.prototype.getActiveParticles = function () {
  14356. return this._activeParticles;
  14357. };
  14358. Scene.prototype.getActiveBones = function () {
  14359. return this._activeBones;
  14360. };
  14361. // Stats
  14362. Scene.prototype.getLastFrameDuration = function () {
  14363. return this._lastFrameDuration;
  14364. };
  14365. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14366. return this._evaluateActiveMeshesDuration;
  14367. };
  14368. Scene.prototype.getActiveMeshes = function () {
  14369. return this._activeMeshes;
  14370. };
  14371. Scene.prototype.getRenderTargetsDuration = function () {
  14372. return this._renderTargetsDuration;
  14373. };
  14374. Scene.prototype.getRenderDuration = function () {
  14375. return this._renderDuration;
  14376. };
  14377. Scene.prototype.getParticlesDuration = function () {
  14378. return this._particlesDuration;
  14379. };
  14380. Scene.prototype.getSpritesDuration = function () {
  14381. return this._spritesDuration;
  14382. };
  14383. Scene.prototype.getAnimationRatio = function () {
  14384. return this._animationRatio;
  14385. };
  14386. Scene.prototype.getRenderId = function () {
  14387. return this._renderId;
  14388. };
  14389. Scene.prototype.incrementRenderId = function () {
  14390. this._renderId++;
  14391. };
  14392. Scene.prototype._updatePointerPosition = function (evt) {
  14393. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14394. this._pointerX = evt.clientX - canvasRect.left;
  14395. this._pointerY = evt.clientY - canvasRect.top;
  14396. this._unTranslatedPointerX = this._pointerX;
  14397. this._unTranslatedPointerY = this._pointerY;
  14398. if (this.cameraToUseForPointers) {
  14399. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14400. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14401. }
  14402. };
  14403. // Pointers handling
  14404. /**
  14405. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14406. * @param attachUp defines if you want to attach events to pointerup
  14407. * @param attachDown defines if you want to attach events to pointerdown
  14408. * @param attachMove defines if you want to attach events to pointermove
  14409. */
  14410. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14411. var _this = this;
  14412. if (attachUp === void 0) { attachUp = true; }
  14413. if (attachDown === void 0) { attachDown = true; }
  14414. if (attachMove === void 0) { attachMove = true; }
  14415. var spritePredicate = function (sprite) {
  14416. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14417. };
  14418. this._onPointerMove = function (evt) {
  14419. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14420. return;
  14421. }
  14422. var canvas = _this._engine.getRenderingCanvas();
  14423. _this._updatePointerPosition(evt);
  14424. if (!_this.pointerMovePredicate) {
  14425. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14426. }
  14427. // Meshes
  14428. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14429. if (pickResult.hit && pickResult.pickedMesh) {
  14430. _this.setPointerOverSprite(null);
  14431. _this.setPointerOverMesh(pickResult.pickedMesh);
  14432. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14433. canvas.style.cursor = "pointer";
  14434. }
  14435. else {
  14436. canvas.style.cursor = "";
  14437. }
  14438. }
  14439. else {
  14440. _this.setPointerOverMesh(null);
  14441. // Sprites
  14442. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14443. if (pickResult.hit && pickResult.pickedSprite) {
  14444. canvas.style.cursor = "pointer";
  14445. _this.setPointerOverSprite(pickResult.pickedSprite);
  14446. }
  14447. else {
  14448. _this.setPointerOverSprite(null);
  14449. // Restore pointer
  14450. canvas.style.cursor = "";
  14451. }
  14452. }
  14453. if (_this.onPointerMove) {
  14454. _this.onPointerMove(evt, pickResult);
  14455. }
  14456. };
  14457. this._onPointerDown = function (evt) {
  14458. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14459. return;
  14460. }
  14461. _this._updatePointerPosition(evt);
  14462. _this._startingPointerPosition.x = _this._pointerX;
  14463. _this._startingPointerPosition.y = _this._pointerY;
  14464. _this._startingPointerTime = new Date().getTime();
  14465. if (!_this.pointerDownPredicate) {
  14466. _this.pointerDownPredicate = function (mesh) {
  14467. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14468. };
  14469. }
  14470. // Meshes
  14471. _this._pickedDownMesh = null;
  14472. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14473. if (pickResult.hit && pickResult.pickedMesh) {
  14474. if (pickResult.pickedMesh.actionManager) {
  14475. _this._pickedDownMesh = pickResult.pickedMesh;
  14476. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14477. switch (evt.button) {
  14478. case 0:
  14479. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14480. break;
  14481. case 1:
  14482. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14483. break;
  14484. case 2:
  14485. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14486. break;
  14487. }
  14488. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14489. }
  14490. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14491. var that = _this;
  14492. window.setTimeout(function () {
  14493. 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);
  14494. if (pickResult.hit && pickResult.pickedMesh) {
  14495. if (pickResult.pickedMesh.actionManager) {
  14496. 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)) {
  14497. that._startingPointerTime = 0;
  14498. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14499. }
  14500. }
  14501. }
  14502. }, BABYLON.ActionManager.LongPressDelay);
  14503. }
  14504. }
  14505. }
  14506. if (_this.onPointerDown) {
  14507. _this.onPointerDown(evt, pickResult);
  14508. }
  14509. // Sprites
  14510. _this._pickedDownSprite = null;
  14511. if (_this.spriteManagers.length > 0) {
  14512. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14513. if (pickResult.hit && pickResult.pickedSprite) {
  14514. if (pickResult.pickedSprite.actionManager) {
  14515. _this._pickedDownSprite = pickResult.pickedSprite;
  14516. switch (evt.button) {
  14517. case 0:
  14518. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14519. break;
  14520. case 1:
  14521. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14522. break;
  14523. case 2:
  14524. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14525. break;
  14526. }
  14527. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14528. }
  14529. }
  14530. }
  14531. };
  14532. this._onPointerUp = function (evt) {
  14533. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14534. return;
  14535. }
  14536. _this._updatePointerPosition(evt);
  14537. if (!_this.pointerUpPredicate) {
  14538. _this.pointerUpPredicate = function (mesh) {
  14539. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14540. };
  14541. }
  14542. // Meshes
  14543. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14544. if (pickResult.hit && pickResult.pickedMesh) {
  14545. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14546. _this.onPointerPick(evt, pickResult);
  14547. }
  14548. if (pickResult.pickedMesh.actionManager) {
  14549. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14550. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14551. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14552. }
  14553. }
  14554. }
  14555. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14556. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14557. }
  14558. if (_this.onPointerUp) {
  14559. _this.onPointerUp(evt, pickResult);
  14560. }
  14561. _this._startingPointerTime = 0;
  14562. // Sprites
  14563. if (_this.spriteManagers.length > 0) {
  14564. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14565. if (pickResult.hit && pickResult.pickedSprite) {
  14566. if (pickResult.pickedSprite.actionManager) {
  14567. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14568. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14569. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14570. }
  14571. }
  14572. }
  14573. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14574. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14575. }
  14576. }
  14577. };
  14578. this._onKeyDown = function (evt) {
  14579. if (_this.actionManager) {
  14580. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14581. }
  14582. };
  14583. this._onKeyUp = function (evt) {
  14584. if (_this.actionManager) {
  14585. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14586. }
  14587. };
  14588. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14589. if (attachMove) {
  14590. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14591. // Wheel
  14592. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14593. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14594. }
  14595. if (attachDown) {
  14596. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14597. }
  14598. if (attachUp) {
  14599. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14600. }
  14601. BABYLON.Tools.RegisterTopRootEvents([
  14602. { name: "keydown", handler: this._onKeyDown },
  14603. { name: "keyup", handler: this._onKeyUp }
  14604. ]);
  14605. };
  14606. Scene.prototype.detachControl = function () {
  14607. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14608. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14609. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14610. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14611. // Wheel
  14612. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14613. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14614. BABYLON.Tools.UnregisterTopRootEvents([
  14615. { name: "keydown", handler: this._onKeyDown },
  14616. { name: "keyup", handler: this._onKeyUp }
  14617. ]);
  14618. };
  14619. // Ready
  14620. Scene.prototype.isReady = function () {
  14621. if (this._pendingData.length > 0) {
  14622. return false;
  14623. }
  14624. var index;
  14625. for (index = 0; index < this._geometries.length; index++) {
  14626. var geometry = this._geometries[index];
  14627. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14628. return false;
  14629. }
  14630. }
  14631. for (index = 0; index < this.meshes.length; index++) {
  14632. var mesh = this.meshes[index];
  14633. if (!mesh.isReady()) {
  14634. return false;
  14635. }
  14636. var mat = mesh.material;
  14637. if (mat) {
  14638. if (!mat.isReady(mesh)) {
  14639. return false;
  14640. }
  14641. }
  14642. }
  14643. return true;
  14644. };
  14645. Scene.prototype.resetCachedMaterial = function () {
  14646. this._cachedMaterial = null;
  14647. };
  14648. Scene.prototype.registerBeforeRender = function (func) {
  14649. this.onBeforeRenderObservable.add(func);
  14650. };
  14651. Scene.prototype.unregisterBeforeRender = function (func) {
  14652. this.onBeforeRenderObservable.removeCallback(func);
  14653. };
  14654. Scene.prototype.registerAfterRender = function (func) {
  14655. this.onAfterRenderObservable.add(func);
  14656. };
  14657. Scene.prototype.unregisterAfterRender = function (func) {
  14658. this.onAfterRenderObservable.removeCallback(func);
  14659. };
  14660. Scene.prototype._addPendingData = function (data) {
  14661. this._pendingData.push(data);
  14662. };
  14663. Scene.prototype._removePendingData = function (data) {
  14664. var index = this._pendingData.indexOf(data);
  14665. if (index !== -1) {
  14666. this._pendingData.splice(index, 1);
  14667. }
  14668. };
  14669. Scene.prototype.getWaitingItemsCount = function () {
  14670. return this._pendingData.length;
  14671. };
  14672. /**
  14673. * Registers a function to be executed when the scene is ready.
  14674. * @param {Function} func - the function to be executed.
  14675. */
  14676. Scene.prototype.executeWhenReady = function (func) {
  14677. var _this = this;
  14678. this.onReadyObservable.add(func);
  14679. if (this._executeWhenReadyTimeoutId !== -1) {
  14680. return;
  14681. }
  14682. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14683. _this._checkIsReady();
  14684. }, 150);
  14685. };
  14686. Scene.prototype._checkIsReady = function () {
  14687. var _this = this;
  14688. if (this.isReady()) {
  14689. this.onReadyObservable.notifyObservers(this);
  14690. this.onReadyObservable.clear();
  14691. this._executeWhenReadyTimeoutId = -1;
  14692. return;
  14693. }
  14694. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14695. _this._checkIsReady();
  14696. }, 150);
  14697. };
  14698. // Animations
  14699. /**
  14700. * Will start the animation sequence of a given target
  14701. * @param target - the target
  14702. * @param {number} from - from which frame should animation start
  14703. * @param {number} to - till which frame should animation run.
  14704. * @param {boolean} [loop] - should the animation loop
  14705. * @param {number} [speedRatio] - the speed in which to run the animation
  14706. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14707. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14708. * @return {BABYLON.Animatable} the animatable object created for this animation
  14709. * @see BABYLON.Animatable
  14710. * @see http://doc.babylonjs.com/page.php?p=22081
  14711. */
  14712. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14713. if (speedRatio === void 0) { speedRatio = 1.0; }
  14714. this.stopAnimation(target);
  14715. if (!animatable) {
  14716. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14717. }
  14718. // Local animations
  14719. if (target.animations) {
  14720. animatable.appendAnimations(target, target.animations);
  14721. }
  14722. // Children animations
  14723. if (target.getAnimatables) {
  14724. var animatables = target.getAnimatables();
  14725. for (var index = 0; index < animatables.length; index++) {
  14726. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14727. }
  14728. }
  14729. animatable.reset();
  14730. return animatable;
  14731. };
  14732. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14733. if (speedRatio === undefined) {
  14734. speedRatio = 1.0;
  14735. }
  14736. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14737. return animatable;
  14738. };
  14739. Scene.prototype.getAnimatableByTarget = function (target) {
  14740. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14741. if (this._activeAnimatables[index].target === target) {
  14742. return this._activeAnimatables[index];
  14743. }
  14744. }
  14745. return null;
  14746. };
  14747. Object.defineProperty(Scene.prototype, "Animatables", {
  14748. get: function () {
  14749. return this._activeAnimatables;
  14750. },
  14751. enumerable: true,
  14752. configurable: true
  14753. });
  14754. /**
  14755. * Will stop the animation of the given target
  14756. * @param target - the target
  14757. * @see beginAnimation
  14758. */
  14759. Scene.prototype.stopAnimation = function (target) {
  14760. var animatable = this.getAnimatableByTarget(target);
  14761. if (animatable) {
  14762. animatable.stop();
  14763. }
  14764. };
  14765. Scene.prototype._animate = function () {
  14766. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14767. return;
  14768. }
  14769. if (!this._animationStartDate) {
  14770. if (this._pendingData.length > 0) {
  14771. return;
  14772. }
  14773. this._animationStartDate = BABYLON.Tools.Now;
  14774. }
  14775. // Getting time
  14776. var now = BABYLON.Tools.Now;
  14777. var delay = now - this._animationStartDate;
  14778. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14779. this._activeAnimatables[index]._animate(delay);
  14780. }
  14781. };
  14782. // Matrix
  14783. Scene.prototype.getViewMatrix = function () {
  14784. return this._viewMatrix;
  14785. };
  14786. Scene.prototype.getProjectionMatrix = function () {
  14787. return this._projectionMatrix;
  14788. };
  14789. Scene.prototype.getTransformMatrix = function () {
  14790. return this._transformMatrix;
  14791. };
  14792. Scene.prototype.setTransformMatrix = function (view, projection) {
  14793. this._viewMatrix = view;
  14794. this._projectionMatrix = projection;
  14795. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14796. };
  14797. // Methods
  14798. Scene.prototype.addMesh = function (newMesh) {
  14799. newMesh.uniqueId = this._uniqueIdCounter++;
  14800. var position = this.meshes.push(newMesh);
  14801. //notify the collision coordinator
  14802. this.collisionCoordinator.onMeshAdded(newMesh);
  14803. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  14804. };
  14805. Scene.prototype.removeMesh = function (toRemove) {
  14806. var index = this.meshes.indexOf(toRemove);
  14807. if (index !== -1) {
  14808. // Remove from the scene if mesh found
  14809. this.meshes.splice(index, 1);
  14810. }
  14811. //notify the collision coordinator
  14812. this.collisionCoordinator.onMeshRemoved(toRemove);
  14813. this.onMeshRemovedObservable.notifyObservers(toRemove);
  14814. return index;
  14815. };
  14816. Scene.prototype.removeSkeleton = function (toRemove) {
  14817. var index = this.skeletons.indexOf(toRemove);
  14818. if (index !== -1) {
  14819. // Remove from the scene if mesh found
  14820. this.skeletons.splice(index, 1);
  14821. }
  14822. return index;
  14823. };
  14824. Scene.prototype.removeLight = function (toRemove) {
  14825. var index = this.lights.indexOf(toRemove);
  14826. if (index !== -1) {
  14827. // Remove from the scene if mesh found
  14828. this.lights.splice(index, 1);
  14829. }
  14830. this.onLightRemovedObservable.notifyObservers(toRemove);
  14831. return index;
  14832. };
  14833. Scene.prototype.removeCamera = function (toRemove) {
  14834. var index = this.cameras.indexOf(toRemove);
  14835. if (index !== -1) {
  14836. // Remove from the scene if mesh found
  14837. this.cameras.splice(index, 1);
  14838. }
  14839. // Remove from activeCameras
  14840. var index2 = this.activeCameras.indexOf(toRemove);
  14841. if (index2 !== -1) {
  14842. // Remove from the scene if mesh found
  14843. this.activeCameras.splice(index2, 1);
  14844. }
  14845. // Reset the activeCamera
  14846. if (this.activeCamera === toRemove) {
  14847. if (this.cameras.length > 0) {
  14848. this.activeCamera = this.cameras[0];
  14849. }
  14850. else {
  14851. this.activeCamera = null;
  14852. }
  14853. }
  14854. this.onCameraRemovedObservable.notifyObservers(toRemove);
  14855. return index;
  14856. };
  14857. Scene.prototype.addLight = function (newLight) {
  14858. newLight.uniqueId = this._uniqueIdCounter++;
  14859. var position = this.lights.push(newLight);
  14860. this.onNewLightAddedObservable.notifyObservers(newLight);
  14861. };
  14862. Scene.prototype.addCamera = function (newCamera) {
  14863. newCamera.uniqueId = this._uniqueIdCounter++;
  14864. var position = this.cameras.push(newCamera);
  14865. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  14866. };
  14867. /**
  14868. * Switch active camera
  14869. * @param {Camera} newCamera - new active camera
  14870. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14871. */
  14872. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14873. if (attachControl === void 0) { attachControl = true; }
  14874. var canvas = this._engine.getRenderingCanvas();
  14875. this.activeCamera.detachControl(canvas);
  14876. this.activeCamera = newCamera;
  14877. if (attachControl) {
  14878. newCamera.attachControl(canvas);
  14879. }
  14880. };
  14881. /**
  14882. * sets the active camera of the scene using its ID
  14883. * @param {string} id - the camera's ID
  14884. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14885. * @see activeCamera
  14886. */
  14887. Scene.prototype.setActiveCameraByID = function (id) {
  14888. var camera = this.getCameraByID(id);
  14889. if (camera) {
  14890. this.activeCamera = camera;
  14891. return camera;
  14892. }
  14893. return null;
  14894. };
  14895. /**
  14896. * sets the active camera of the scene using its name
  14897. * @param {string} name - the camera's name
  14898. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14899. * @see activeCamera
  14900. */
  14901. Scene.prototype.setActiveCameraByName = function (name) {
  14902. var camera = this.getCameraByName(name);
  14903. if (camera) {
  14904. this.activeCamera = camera;
  14905. return camera;
  14906. }
  14907. return null;
  14908. };
  14909. /**
  14910. * get a material using its id
  14911. * @param {string} the material's ID
  14912. * @return {BABYLON.Material|null} the material or null if none found.
  14913. */
  14914. Scene.prototype.getMaterialByID = function (id) {
  14915. for (var index = 0; index < this.materials.length; index++) {
  14916. if (this.materials[index].id === id) {
  14917. return this.materials[index];
  14918. }
  14919. }
  14920. return null;
  14921. };
  14922. /**
  14923. * get a material using its name
  14924. * @param {string} the material's name
  14925. * @return {BABYLON.Material|null} the material or null if none found.
  14926. */
  14927. Scene.prototype.getMaterialByName = function (name) {
  14928. for (var index = 0; index < this.materials.length; index++) {
  14929. if (this.materials[index].name === name) {
  14930. return this.materials[index];
  14931. }
  14932. }
  14933. return null;
  14934. };
  14935. Scene.prototype.getLensFlareSystemByName = function (name) {
  14936. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  14937. if (this.lensFlareSystems[index].name === name) {
  14938. return this.lensFlareSystems[index];
  14939. }
  14940. }
  14941. return null;
  14942. };
  14943. Scene.prototype.getCameraByID = function (id) {
  14944. for (var index = 0; index < this.cameras.length; index++) {
  14945. if (this.cameras[index].id === id) {
  14946. return this.cameras[index];
  14947. }
  14948. }
  14949. return null;
  14950. };
  14951. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  14952. for (var index = 0; index < this.cameras.length; index++) {
  14953. if (this.cameras[index].uniqueId === uniqueId) {
  14954. return this.cameras[index];
  14955. }
  14956. }
  14957. return null;
  14958. };
  14959. /**
  14960. * get a camera using its name
  14961. * @param {string} the camera's name
  14962. * @return {BABYLON.Camera|null} the camera or null if none found.
  14963. */
  14964. Scene.prototype.getCameraByName = function (name) {
  14965. for (var index = 0; index < this.cameras.length; index++) {
  14966. if (this.cameras[index].name === name) {
  14967. return this.cameras[index];
  14968. }
  14969. }
  14970. return null;
  14971. };
  14972. /**
  14973. * get a bone using its id
  14974. * @param {string} the bone's id
  14975. * @return {BABYLON.Bone|null} the bone or null if not found
  14976. */
  14977. Scene.prototype.getBoneByID = function (id) {
  14978. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14979. var skeleton = this.skeletons[skeletonIndex];
  14980. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14981. if (skeleton.bones[boneIndex].id === id) {
  14982. return skeleton.bones[boneIndex];
  14983. }
  14984. }
  14985. }
  14986. return null;
  14987. };
  14988. /**
  14989. * get a bone using its id
  14990. * @param {string} the bone's name
  14991. * @return {BABYLON.Bone|null} the bone or null if not found
  14992. */
  14993. Scene.prototype.getBoneByName = function (name) {
  14994. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14995. var skeleton = this.skeletons[skeletonIndex];
  14996. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14997. if (skeleton.bones[boneIndex].name === name) {
  14998. return skeleton.bones[boneIndex];
  14999. }
  15000. }
  15001. }
  15002. return null;
  15003. };
  15004. /**
  15005. * get a light node using its name
  15006. * @param {string} the light's name
  15007. * @return {BABYLON.Light|null} the light or null if none found.
  15008. */
  15009. Scene.prototype.getLightByName = function (name) {
  15010. for (var index = 0; index < this.lights.length; index++) {
  15011. if (this.lights[index].name === name) {
  15012. return this.lights[index];
  15013. }
  15014. }
  15015. return null;
  15016. };
  15017. /**
  15018. * get a light node using its ID
  15019. * @param {string} the light's id
  15020. * @return {BABYLON.Light|null} the light or null if none found.
  15021. */
  15022. Scene.prototype.getLightByID = function (id) {
  15023. for (var index = 0; index < this.lights.length; index++) {
  15024. if (this.lights[index].id === id) {
  15025. return this.lights[index];
  15026. }
  15027. }
  15028. return null;
  15029. };
  15030. /**
  15031. * get a light node using its scene-generated unique ID
  15032. * @param {number} the light's unique id
  15033. * @return {BABYLON.Light|null} the light or null if none found.
  15034. */
  15035. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15036. for (var index = 0; index < this.lights.length; index++) {
  15037. if (this.lights[index].uniqueId === uniqueId) {
  15038. return this.lights[index];
  15039. }
  15040. }
  15041. return null;
  15042. };
  15043. /**
  15044. * get a particle system by id
  15045. * @param id {number} the particle system id
  15046. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15047. */
  15048. Scene.prototype.getParticleSystemByID = function (id) {
  15049. for (var index = 0; index < this.particleSystems.length; index++) {
  15050. if (this.particleSystems[index].id === id) {
  15051. return this.particleSystems[index];
  15052. }
  15053. }
  15054. return null;
  15055. };
  15056. /**
  15057. * get a geometry using its ID
  15058. * @param {string} the geometry's id
  15059. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15060. */
  15061. Scene.prototype.getGeometryByID = function (id) {
  15062. for (var index = 0; index < this._geometries.length; index++) {
  15063. if (this._geometries[index].id === id) {
  15064. return this._geometries[index];
  15065. }
  15066. }
  15067. return null;
  15068. };
  15069. /**
  15070. * add a new geometry to this scene.
  15071. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15072. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15073. * @return {boolean} was the geometry added or not
  15074. */
  15075. Scene.prototype.pushGeometry = function (geometry, force) {
  15076. if (!force && this.getGeometryByID(geometry.id)) {
  15077. return false;
  15078. }
  15079. this._geometries.push(geometry);
  15080. //notify the collision coordinator
  15081. this.collisionCoordinator.onGeometryAdded(geometry);
  15082. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15083. return true;
  15084. };
  15085. /**
  15086. * Removes an existing geometry
  15087. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15088. * @return {boolean} was the geometry removed or not
  15089. */
  15090. Scene.prototype.removeGeometry = function (geometry) {
  15091. var index = this._geometries.indexOf(geometry);
  15092. if (index > -1) {
  15093. this._geometries.splice(index, 1);
  15094. //notify the collision coordinator
  15095. this.collisionCoordinator.onGeometryDeleted(geometry);
  15096. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15097. return true;
  15098. }
  15099. return false;
  15100. };
  15101. Scene.prototype.getGeometries = function () {
  15102. return this._geometries;
  15103. };
  15104. /**
  15105. * Get the first added mesh found of a given ID
  15106. * @param {string} id - the id to search for
  15107. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15108. */
  15109. Scene.prototype.getMeshByID = function (id) {
  15110. for (var index = 0; index < this.meshes.length; index++) {
  15111. if (this.meshes[index].id === id) {
  15112. return this.meshes[index];
  15113. }
  15114. }
  15115. return null;
  15116. };
  15117. /**
  15118. * Get a mesh with its auto-generated unique id
  15119. * @param {number} uniqueId - the unique id to search for
  15120. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15121. */
  15122. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15123. for (var index = 0; index < this.meshes.length; index++) {
  15124. if (this.meshes[index].uniqueId === uniqueId) {
  15125. return this.meshes[index];
  15126. }
  15127. }
  15128. return null;
  15129. };
  15130. /**
  15131. * Get a the last added mesh found of a given ID
  15132. * @param {string} id - the id to search for
  15133. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15134. */
  15135. Scene.prototype.getLastMeshByID = function (id) {
  15136. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15137. if (this.meshes[index].id === id) {
  15138. return this.meshes[index];
  15139. }
  15140. }
  15141. return null;
  15142. };
  15143. /**
  15144. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15145. * @param {string} id - the id to search for
  15146. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15147. */
  15148. Scene.prototype.getLastEntryByID = function (id) {
  15149. var index;
  15150. for (index = this.meshes.length - 1; index >= 0; index--) {
  15151. if (this.meshes[index].id === id) {
  15152. return this.meshes[index];
  15153. }
  15154. }
  15155. for (index = this.cameras.length - 1; index >= 0; index--) {
  15156. if (this.cameras[index].id === id) {
  15157. return this.cameras[index];
  15158. }
  15159. }
  15160. for (index = this.lights.length - 1; index >= 0; index--) {
  15161. if (this.lights[index].id === id) {
  15162. return this.lights[index];
  15163. }
  15164. }
  15165. return null;
  15166. };
  15167. Scene.prototype.getNodeByID = function (id) {
  15168. var mesh = this.getMeshByID(id);
  15169. if (mesh) {
  15170. return mesh;
  15171. }
  15172. var light = this.getLightByID(id);
  15173. if (light) {
  15174. return light;
  15175. }
  15176. var camera = this.getCameraByID(id);
  15177. if (camera) {
  15178. return camera;
  15179. }
  15180. var bone = this.getBoneByID(id);
  15181. return bone;
  15182. };
  15183. Scene.prototype.getNodeByName = function (name) {
  15184. var mesh = this.getMeshByName(name);
  15185. if (mesh) {
  15186. return mesh;
  15187. }
  15188. var light = this.getLightByName(name);
  15189. if (light) {
  15190. return light;
  15191. }
  15192. var camera = this.getCameraByName(name);
  15193. if (camera) {
  15194. return camera;
  15195. }
  15196. var bone = this.getBoneByName(name);
  15197. return bone;
  15198. };
  15199. Scene.prototype.getMeshByName = function (name) {
  15200. for (var index = 0; index < this.meshes.length; index++) {
  15201. if (this.meshes[index].name === name) {
  15202. return this.meshes[index];
  15203. }
  15204. }
  15205. return null;
  15206. };
  15207. Scene.prototype.getSoundByName = function (name) {
  15208. var index;
  15209. if (BABYLON.AudioEngine) {
  15210. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15211. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15212. return this.mainSoundTrack.soundCollection[index];
  15213. }
  15214. }
  15215. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15216. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15217. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15218. return this.soundTracks[sdIndex].soundCollection[index];
  15219. }
  15220. }
  15221. }
  15222. }
  15223. return null;
  15224. };
  15225. Scene.prototype.getLastSkeletonByID = function (id) {
  15226. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15227. if (this.skeletons[index].id === id) {
  15228. return this.skeletons[index];
  15229. }
  15230. }
  15231. return null;
  15232. };
  15233. Scene.prototype.getSkeletonById = function (id) {
  15234. for (var index = 0; index < this.skeletons.length; index++) {
  15235. if (this.skeletons[index].id === id) {
  15236. return this.skeletons[index];
  15237. }
  15238. }
  15239. return null;
  15240. };
  15241. Scene.prototype.getSkeletonByName = function (name) {
  15242. for (var index = 0; index < this.skeletons.length; index++) {
  15243. if (this.skeletons[index].name === name) {
  15244. return this.skeletons[index];
  15245. }
  15246. }
  15247. return null;
  15248. };
  15249. Scene.prototype.isActiveMesh = function (mesh) {
  15250. return (this._activeMeshes.indexOf(mesh) !== -1);
  15251. };
  15252. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15253. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15254. var material = subMesh.getMaterial();
  15255. if (mesh.showSubMeshesBoundingBox) {
  15256. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15257. }
  15258. if (material) {
  15259. // Render targets
  15260. if (material.getRenderTargetTextures) {
  15261. if (this._processedMaterials.indexOf(material) === -1) {
  15262. this._processedMaterials.push(material);
  15263. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15264. }
  15265. }
  15266. // Dispatch
  15267. this._activeIndices += subMesh.indexCount;
  15268. this._renderingManager.dispatch(subMesh);
  15269. }
  15270. }
  15271. };
  15272. Scene.prototype._isInIntermediateRendering = function () {
  15273. return this._intermediateRendering;
  15274. };
  15275. Scene.prototype._evaluateActiveMeshes = function () {
  15276. this.activeCamera._activeMeshes.reset();
  15277. this._activeMeshes.reset();
  15278. this._renderingManager.reset();
  15279. this._processedMaterials.reset();
  15280. this._activeParticleSystems.reset();
  15281. this._activeSkeletons.reset();
  15282. this._softwareSkinnedMeshes.reset();
  15283. this._boundingBoxRenderer.reset();
  15284. this._edgesRenderers.reset();
  15285. if (!this._frustumPlanes) {
  15286. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15287. }
  15288. else {
  15289. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15290. }
  15291. // Meshes
  15292. var meshes;
  15293. var len;
  15294. if (this._selectionOctree) {
  15295. var selection = this._selectionOctree.select(this._frustumPlanes);
  15296. meshes = selection.data;
  15297. len = selection.length;
  15298. }
  15299. else {
  15300. len = this.meshes.length;
  15301. meshes = this.meshes;
  15302. }
  15303. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15304. var mesh = meshes[meshIndex];
  15305. if (mesh.isBlocked) {
  15306. continue;
  15307. }
  15308. this._totalVertices += mesh.getTotalVertices();
  15309. if (!mesh.isReady() || !mesh.isEnabled()) {
  15310. continue;
  15311. }
  15312. mesh.computeWorldMatrix();
  15313. // Intersections
  15314. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15315. this._meshesForIntersections.pushNoDuplicate(mesh);
  15316. }
  15317. // Switch to current LOD
  15318. var meshLOD = mesh.getLOD(this.activeCamera);
  15319. if (!meshLOD) {
  15320. continue;
  15321. }
  15322. mesh._preActivate();
  15323. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15324. this._activeMeshes.push(mesh);
  15325. this.activeCamera._activeMeshes.push(mesh);
  15326. mesh._activate(this._renderId);
  15327. this._activeMesh(meshLOD);
  15328. }
  15329. }
  15330. // Particle systems
  15331. var beforeParticlesDate = BABYLON.Tools.Now;
  15332. if (this.particlesEnabled) {
  15333. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15334. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15335. var particleSystem = this.particleSystems[particleIndex];
  15336. if (!particleSystem.isStarted()) {
  15337. continue;
  15338. }
  15339. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15340. this._activeParticleSystems.push(particleSystem);
  15341. particleSystem.animate();
  15342. }
  15343. }
  15344. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15345. }
  15346. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15347. };
  15348. Scene.prototype._activeMesh = function (mesh) {
  15349. if (mesh.skeleton && this.skeletonsEnabled) {
  15350. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15351. if (!mesh.computeBonesUsingShaders) {
  15352. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15353. }
  15354. }
  15355. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15356. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15357. }
  15358. if (mesh._edgesRenderer) {
  15359. this._edgesRenderers.push(mesh._edgesRenderer);
  15360. }
  15361. if (mesh && mesh.subMeshes) {
  15362. // Submeshes Octrees
  15363. var len;
  15364. var subMeshes;
  15365. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15366. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15367. len = intersections.length;
  15368. subMeshes = intersections.data;
  15369. }
  15370. else {
  15371. subMeshes = mesh.subMeshes;
  15372. len = subMeshes.length;
  15373. }
  15374. for (var subIndex = 0; subIndex < len; subIndex++) {
  15375. var subMesh = subMeshes[subIndex];
  15376. this._evaluateSubMesh(subMesh, mesh);
  15377. }
  15378. }
  15379. };
  15380. Scene.prototype.updateTransformMatrix = function (force) {
  15381. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15382. };
  15383. Scene.prototype._renderForCamera = function (camera) {
  15384. var engine = this._engine;
  15385. this.activeCamera = camera;
  15386. if (!this.activeCamera)
  15387. throw new Error("Active camera not set");
  15388. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15389. // Viewport
  15390. engine.setViewport(this.activeCamera.viewport);
  15391. // Camera
  15392. this.resetCachedMaterial();
  15393. this._renderId++;
  15394. this.updateTransformMatrix();
  15395. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15396. // Meshes
  15397. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15398. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15399. this._evaluateActiveMeshes();
  15400. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15401. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15402. // Skeletons
  15403. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15404. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15405. skeleton.prepare();
  15406. }
  15407. // Software skinning
  15408. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15409. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15410. mesh.applySkeleton(mesh.skeleton);
  15411. }
  15412. // Render targets
  15413. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15414. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15415. this._intermediateRendering = true;
  15416. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15417. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15418. var renderTarget = this._renderTargets.data[renderIndex];
  15419. if (renderTarget._shouldRender()) {
  15420. this._renderId++;
  15421. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15422. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15423. }
  15424. }
  15425. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15426. this._intermediateRendering = false;
  15427. this._renderId++;
  15428. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15429. }
  15430. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15431. // Prepare Frame
  15432. this.postProcessManager._prepareFrame();
  15433. var beforeRenderDate = BABYLON.Tools.Now;
  15434. // Backgrounds
  15435. var layerIndex;
  15436. var layer;
  15437. if (this.layers.length) {
  15438. engine.setDepthBuffer(false);
  15439. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15440. layer = this.layers[layerIndex];
  15441. if (layer.isBackground) {
  15442. layer.render();
  15443. }
  15444. }
  15445. engine.setDepthBuffer(true);
  15446. }
  15447. // Render
  15448. BABYLON.Tools.StartPerformanceCounter("Main render");
  15449. this._renderingManager.render(null, null, true, true);
  15450. BABYLON.Tools.EndPerformanceCounter("Main render");
  15451. // Bounding boxes
  15452. this._boundingBoxRenderer.render();
  15453. // Edges
  15454. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15455. this._edgesRenderers.data[edgesRendererIndex].render();
  15456. }
  15457. // Lens flares
  15458. if (this.lensFlaresEnabled) {
  15459. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15460. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15461. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15462. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15463. lensFlareSystem.render();
  15464. }
  15465. }
  15466. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15467. }
  15468. // Foregrounds
  15469. if (this.layers.length) {
  15470. engine.setDepthBuffer(false);
  15471. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15472. layer = this.layers[layerIndex];
  15473. if (!layer.isBackground) {
  15474. layer.render();
  15475. }
  15476. }
  15477. engine.setDepthBuffer(true);
  15478. }
  15479. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15480. // Finalize frame
  15481. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15482. // Update camera
  15483. this.activeCamera._updateFromScene();
  15484. // Reset some special arrays
  15485. this._renderTargets.reset();
  15486. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15487. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15488. };
  15489. Scene.prototype._processSubCameras = function (camera) {
  15490. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15491. this._renderForCamera(camera);
  15492. return;
  15493. }
  15494. // rig cameras
  15495. for (var index = 0; index < camera._rigCameras.length; index++) {
  15496. this._renderForCamera(camera._rigCameras[index]);
  15497. }
  15498. this.activeCamera = camera;
  15499. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15500. // Update camera
  15501. this.activeCamera._updateFromScene();
  15502. };
  15503. Scene.prototype._checkIntersections = function () {
  15504. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15505. var sourceMesh = this._meshesForIntersections.data[index];
  15506. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15507. var action = sourceMesh.actionManager.actions[actionIndex];
  15508. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15509. var parameters = action.getTriggerParameter();
  15510. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15511. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15512. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15513. if (areIntersecting && currentIntersectionInProgress === -1) {
  15514. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15515. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15516. sourceMesh._intersectionsInProgress.push(otherMesh);
  15517. }
  15518. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15519. sourceMesh._intersectionsInProgress.push(otherMesh);
  15520. }
  15521. }
  15522. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15523. //They intersected, and now they don't.
  15524. //is this trigger an exit trigger? execute an event.
  15525. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15526. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15527. }
  15528. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15529. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15530. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15531. }
  15532. }
  15533. }
  15534. }
  15535. }
  15536. };
  15537. Scene.prototype.render = function () {
  15538. var startDate = BABYLON.Tools.Now;
  15539. this._particlesDuration = 0;
  15540. this._spritesDuration = 0;
  15541. this._activeParticles = 0;
  15542. this._renderDuration = 0;
  15543. this._renderTargetsDuration = 0;
  15544. this._evaluateActiveMeshesDuration = 0;
  15545. this._totalVertices = 0;
  15546. this._activeIndices = 0;
  15547. this._activeBones = 0;
  15548. this.getEngine().resetDrawCalls();
  15549. this._meshesForIntersections.reset();
  15550. this.resetCachedMaterial();
  15551. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15552. // Actions
  15553. if (this.actionManager) {
  15554. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15555. }
  15556. //Simplification Queue
  15557. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15558. this.simplificationQueue.executeNext();
  15559. }
  15560. // Animations
  15561. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15562. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15563. this._animate();
  15564. // Physics
  15565. if (this._physicsEngine) {
  15566. BABYLON.Tools.StartPerformanceCounter("Physics");
  15567. this._physicsEngine._step(deltaTime / 1000.0);
  15568. BABYLON.Tools.EndPerformanceCounter("Physics");
  15569. }
  15570. // Before render
  15571. this.onBeforeRenderObservable.notifyObservers(this);
  15572. // Customs render targets
  15573. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15574. var engine = this.getEngine();
  15575. var currentActiveCamera = this.activeCamera;
  15576. if (this.renderTargetsEnabled) {
  15577. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15578. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15579. var renderTarget = this.customRenderTargets[customIndex];
  15580. if (renderTarget._shouldRender()) {
  15581. this._renderId++;
  15582. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15583. if (!this.activeCamera)
  15584. throw new Error("Active camera not set");
  15585. // Viewport
  15586. engine.setViewport(this.activeCamera.viewport);
  15587. // Camera
  15588. this.updateTransformMatrix();
  15589. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15590. }
  15591. }
  15592. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15593. this._renderId++;
  15594. }
  15595. if (this.customRenderTargets.length > 0) {
  15596. engine.restoreDefaultFramebuffer();
  15597. }
  15598. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15599. this.activeCamera = currentActiveCamera;
  15600. // Procedural textures
  15601. if (this.proceduralTexturesEnabled) {
  15602. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15603. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15604. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15605. if (proceduralTexture._shouldRender()) {
  15606. proceduralTexture.render();
  15607. }
  15608. }
  15609. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15610. }
  15611. // Clear
  15612. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15613. // Shadows
  15614. if (this.shadowsEnabled) {
  15615. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15616. var light = this.lights[lightIndex];
  15617. var shadowGenerator = light.getShadowGenerator();
  15618. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15619. this._renderTargets.push(shadowGenerator.getShadowMap());
  15620. }
  15621. }
  15622. }
  15623. // Depth renderer
  15624. if (this._depthRenderer) {
  15625. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15626. }
  15627. // RenderPipeline
  15628. this.postProcessRenderPipelineManager.update();
  15629. // Multi-cameras?
  15630. if (this.activeCameras.length > 0) {
  15631. var currentRenderId = this._renderId;
  15632. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15633. this._renderId = currentRenderId;
  15634. if (cameraIndex > 0) {
  15635. this._engine.clear(0, false, true);
  15636. }
  15637. this._processSubCameras(this.activeCameras[cameraIndex]);
  15638. }
  15639. }
  15640. else {
  15641. if (!this.activeCamera) {
  15642. throw new Error("No camera defined");
  15643. }
  15644. this._processSubCameras(this.activeCamera);
  15645. }
  15646. // Intersection checks
  15647. this._checkIntersections();
  15648. // Update the audio listener attached to the camera
  15649. if (BABYLON.AudioEngine) {
  15650. this._updateAudioParameters();
  15651. }
  15652. // After render
  15653. if (this.afterRender) {
  15654. this.afterRender();
  15655. }
  15656. this.onAfterRenderObservable.notifyObservers(this);
  15657. // Cleaning
  15658. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15659. this._toBeDisposed.data[index].dispose();
  15660. this._toBeDisposed[index] = null;
  15661. }
  15662. this._toBeDisposed.reset();
  15663. if (this.dumpNextRenderTargets) {
  15664. this.dumpNextRenderTargets = false;
  15665. }
  15666. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15667. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15668. };
  15669. Scene.prototype._updateAudioParameters = function () {
  15670. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15671. return;
  15672. }
  15673. var listeningCamera;
  15674. var audioEngine = BABYLON.Engine.audioEngine;
  15675. if (this.activeCameras.length > 0) {
  15676. listeningCamera = this.activeCameras[0];
  15677. }
  15678. else {
  15679. listeningCamera = this.activeCamera;
  15680. }
  15681. if (listeningCamera && audioEngine.canUseWebAudio) {
  15682. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15683. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15684. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15685. cameraDirection.normalize();
  15686. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15687. var i;
  15688. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15689. var sound = this.mainSoundTrack.soundCollection[i];
  15690. if (sound.useCustomAttenuation) {
  15691. sound.updateDistanceFromListener();
  15692. }
  15693. }
  15694. for (i = 0; i < this.soundTracks.length; i++) {
  15695. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15696. sound = this.soundTracks[i].soundCollection[j];
  15697. if (sound.useCustomAttenuation) {
  15698. sound.updateDistanceFromListener();
  15699. }
  15700. }
  15701. }
  15702. }
  15703. };
  15704. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15705. // Audio
  15706. get: function () {
  15707. return this._audioEnabled;
  15708. },
  15709. set: function (value) {
  15710. this._audioEnabled = value;
  15711. if (BABYLON.AudioEngine) {
  15712. if (this._audioEnabled) {
  15713. this._enableAudio();
  15714. }
  15715. else {
  15716. this._disableAudio();
  15717. }
  15718. }
  15719. },
  15720. enumerable: true,
  15721. configurable: true
  15722. });
  15723. Scene.prototype._disableAudio = function () {
  15724. var i;
  15725. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15726. this.mainSoundTrack.soundCollection[i].pause();
  15727. }
  15728. for (i = 0; i < this.soundTracks.length; i++) {
  15729. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15730. this.soundTracks[i].soundCollection[j].pause();
  15731. }
  15732. }
  15733. };
  15734. Scene.prototype._enableAudio = function () {
  15735. var i;
  15736. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15737. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15738. this.mainSoundTrack.soundCollection[i].play();
  15739. }
  15740. }
  15741. for (i = 0; i < this.soundTracks.length; i++) {
  15742. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15743. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15744. this.soundTracks[i].soundCollection[j].play();
  15745. }
  15746. }
  15747. }
  15748. };
  15749. Object.defineProperty(Scene.prototype, "headphone", {
  15750. get: function () {
  15751. return this._headphone;
  15752. },
  15753. set: function (value) {
  15754. this._headphone = value;
  15755. if (BABYLON.AudioEngine) {
  15756. if (this._headphone) {
  15757. this._switchAudioModeForHeadphones();
  15758. }
  15759. else {
  15760. this._switchAudioModeForNormalSpeakers();
  15761. }
  15762. }
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. Scene.prototype._switchAudioModeForHeadphones = function () {
  15768. this.mainSoundTrack.switchPanningModelToHRTF();
  15769. for (var i = 0; i < this.soundTracks.length; i++) {
  15770. this.soundTracks[i].switchPanningModelToHRTF();
  15771. }
  15772. };
  15773. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15774. this.mainSoundTrack.switchPanningModelToEqualPower();
  15775. for (var i = 0; i < this.soundTracks.length; i++) {
  15776. this.soundTracks[i].switchPanningModelToEqualPower();
  15777. }
  15778. };
  15779. Scene.prototype.enableDepthRenderer = function () {
  15780. if (this._depthRenderer) {
  15781. return this._depthRenderer;
  15782. }
  15783. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15784. return this._depthRenderer;
  15785. };
  15786. Scene.prototype.disableDepthRenderer = function () {
  15787. if (!this._depthRenderer) {
  15788. return;
  15789. }
  15790. this._depthRenderer.dispose();
  15791. this._depthRenderer = null;
  15792. };
  15793. Scene.prototype.freezeMaterials = function () {
  15794. for (var i = 0; i < this.materials.length; i++) {
  15795. this.materials[i].freeze();
  15796. }
  15797. };
  15798. Scene.prototype.unfreezeMaterials = function () {
  15799. for (var i = 0; i < this.materials.length; i++) {
  15800. this.materials[i].unfreeze();
  15801. }
  15802. };
  15803. Scene.prototype.dispose = function () {
  15804. this.beforeRender = null;
  15805. this.afterRender = null;
  15806. this.skeletons = [];
  15807. this._boundingBoxRenderer.dispose();
  15808. if (this._depthRenderer) {
  15809. this._depthRenderer.dispose();
  15810. }
  15811. // Debug layer
  15812. this.debugLayer.hide();
  15813. // Events
  15814. if (this.onDispose) {
  15815. this.onDispose();
  15816. }
  15817. this.onBeforeRenderObservable.clear();
  15818. this.onAfterRenderObservable.clear();
  15819. this.detachControl();
  15820. // Release sounds & sounds tracks
  15821. if (BABYLON.AudioEngine) {
  15822. this.disposeSounds();
  15823. }
  15824. // Detach cameras
  15825. var canvas = this._engine.getRenderingCanvas();
  15826. var index;
  15827. for (index = 0; index < this.cameras.length; index++) {
  15828. this.cameras[index].detachControl(canvas);
  15829. }
  15830. // Release lights
  15831. while (this.lights.length) {
  15832. this.lights[0].dispose();
  15833. }
  15834. // Release meshes
  15835. while (this.meshes.length) {
  15836. this.meshes[0].dispose(true);
  15837. }
  15838. // Release cameras
  15839. while (this.cameras.length) {
  15840. this.cameras[0].dispose();
  15841. }
  15842. // Release materials
  15843. while (this.materials.length) {
  15844. this.materials[0].dispose();
  15845. }
  15846. // Release particles
  15847. while (this.particleSystems.length) {
  15848. this.particleSystems[0].dispose();
  15849. }
  15850. // Release sprites
  15851. while (this.spriteManagers.length) {
  15852. this.spriteManagers[0].dispose();
  15853. }
  15854. // Release layers
  15855. while (this.layers.length) {
  15856. this.layers[0].dispose();
  15857. }
  15858. // Release textures
  15859. while (this.textures.length) {
  15860. this.textures[0].dispose();
  15861. }
  15862. // Post-processes
  15863. this.postProcessManager.dispose();
  15864. // Physics
  15865. if (this._physicsEngine) {
  15866. this.disablePhysicsEngine();
  15867. }
  15868. // Remove from engine
  15869. index = this._engine.scenes.indexOf(this);
  15870. if (index > -1) {
  15871. this._engine.scenes.splice(index, 1);
  15872. }
  15873. this._engine.wipeCaches();
  15874. };
  15875. // Release sounds & sounds tracks
  15876. Scene.prototype.disposeSounds = function () {
  15877. this.mainSoundTrack.dispose();
  15878. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15879. this.soundTracks[scIndex].dispose();
  15880. }
  15881. };
  15882. // Octrees
  15883. Scene.prototype.getWorldExtends = function () {
  15884. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15885. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15886. for (var index = 0; index < this.meshes.length; index++) {
  15887. var mesh = this.meshes[index];
  15888. mesh.computeWorldMatrix(true);
  15889. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  15890. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  15891. BABYLON.Tools.CheckExtends(minBox, min, max);
  15892. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15893. }
  15894. return {
  15895. min: min,
  15896. max: max
  15897. };
  15898. };
  15899. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  15900. if (maxCapacity === void 0) { maxCapacity = 64; }
  15901. if (maxDepth === void 0) { maxDepth = 2; }
  15902. if (!this._selectionOctree) {
  15903. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  15904. }
  15905. var worldExtends = this.getWorldExtends();
  15906. // Update octree
  15907. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  15908. return this._selectionOctree;
  15909. };
  15910. // Picking
  15911. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  15912. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  15913. var engine = this._engine;
  15914. if (!camera) {
  15915. if (!this.activeCamera)
  15916. throw new Error("Active camera not set");
  15917. camera = this.activeCamera;
  15918. }
  15919. var cameraViewport = camera.viewport;
  15920. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15921. // Moving coordinates to local viewport world
  15922. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15923. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15924. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  15925. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  15926. };
  15927. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  15928. var engine = this._engine;
  15929. if (!camera) {
  15930. if (!this.activeCamera)
  15931. throw new Error("Active camera not set");
  15932. camera = this.activeCamera;
  15933. }
  15934. var cameraViewport = camera.viewport;
  15935. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15936. var identity = BABYLON.Matrix.Identity();
  15937. // Moving coordinates to local viewport world
  15938. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15939. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15940. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  15941. };
  15942. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  15943. var pickingInfo = null;
  15944. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  15945. var mesh = this.meshes[meshIndex];
  15946. if (predicate) {
  15947. if (!predicate(mesh)) {
  15948. continue;
  15949. }
  15950. }
  15951. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  15952. continue;
  15953. }
  15954. var world = mesh.getWorldMatrix();
  15955. var ray = rayFunction(world);
  15956. var result = mesh.intersects(ray, fastCheck);
  15957. if (!result || !result.hit)
  15958. continue;
  15959. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15960. continue;
  15961. pickingInfo = result;
  15962. if (fastCheck) {
  15963. break;
  15964. }
  15965. }
  15966. return pickingInfo || new BABYLON.PickingInfo();
  15967. };
  15968. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  15969. var pickingInfo = null;
  15970. camera = camera || this.activeCamera;
  15971. if (this.spriteManagers.length > 0) {
  15972. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  15973. var spriteManager = this.spriteManagers[spriteIndex];
  15974. if (!spriteManager.isPickable) {
  15975. continue;
  15976. }
  15977. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  15978. if (!result || !result.hit)
  15979. continue;
  15980. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15981. continue;
  15982. pickingInfo = result;
  15983. if (fastCheck) {
  15984. break;
  15985. }
  15986. }
  15987. }
  15988. return pickingInfo || new BABYLON.PickingInfo();
  15989. };
  15990. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  15991. var _this = this;
  15992. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15993. /// <param name="x">X position on screen</param>
  15994. /// <param name="y">Y position on screen</param>
  15995. /// <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>
  15996. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15997. /// <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>
  15998. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  15999. };
  16000. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16001. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16002. /// <param name="x">X position on screen</param>
  16003. /// <param name="y">Y position on screen</param>
  16004. /// <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>
  16005. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16006. /// <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>
  16007. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16008. };
  16009. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16010. var _this = this;
  16011. return this._internalPick(function (world) {
  16012. if (!_this._pickWithRayInverseMatrix) {
  16013. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16014. }
  16015. world.invertToRef(_this._pickWithRayInverseMatrix);
  16016. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16017. }, predicate, fastCheck);
  16018. };
  16019. Scene.prototype.setPointerOverMesh = function (mesh) {
  16020. if (this._pointerOverMesh === mesh) {
  16021. return;
  16022. }
  16023. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16024. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16025. }
  16026. this._pointerOverMesh = mesh;
  16027. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16028. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16029. }
  16030. };
  16031. Scene.prototype.getPointerOverMesh = function () {
  16032. return this._pointerOverMesh;
  16033. };
  16034. Scene.prototype.setPointerOverSprite = function (sprite) {
  16035. if (this._pointerOverSprite === sprite) {
  16036. return;
  16037. }
  16038. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16039. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16040. }
  16041. this._pointerOverSprite = sprite;
  16042. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16043. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16044. }
  16045. };
  16046. Scene.prototype.getPointerOverSprite = function () {
  16047. return this._pointerOverSprite;
  16048. };
  16049. // Physics
  16050. Scene.prototype.getPhysicsEngine = function () {
  16051. return this._physicsEngine;
  16052. };
  16053. /**
  16054. * Enables physics to the current scene
  16055. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16056. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16057. * @return {boolean} was the physics engine initialized
  16058. */
  16059. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16060. if (this._physicsEngine) {
  16061. return true;
  16062. }
  16063. try {
  16064. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16065. return true;
  16066. }
  16067. catch (e) {
  16068. BABYLON.Tools.Error(e.message);
  16069. return false;
  16070. }
  16071. };
  16072. Scene.prototype.disablePhysicsEngine = function () {
  16073. if (!this._physicsEngine) {
  16074. return;
  16075. }
  16076. this._physicsEngine.dispose();
  16077. this._physicsEngine = undefined;
  16078. };
  16079. Scene.prototype.isPhysicsEnabled = function () {
  16080. return this._physicsEngine !== undefined;
  16081. };
  16082. /**
  16083. *
  16084. * Sets the gravity of the physics engine (and NOT of the scene)
  16085. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16086. */
  16087. Scene.prototype.setGravity = function (gravity) {
  16088. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16089. if (!this._physicsEngine) {
  16090. return;
  16091. }
  16092. this._physicsEngine.setGravity(gravity);
  16093. };
  16094. /**
  16095. * Legacy support, using the new API
  16096. * @Deprecated
  16097. */
  16098. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16099. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16100. if (parts.parts) {
  16101. options = parts;
  16102. parts = parts.parts;
  16103. }
  16104. var mainMesh = parts[0].mesh;
  16105. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16106. for (var index = 1; index < parts.length; index++) {
  16107. var mesh = parts[index].mesh;
  16108. if (mesh.parent !== mainMesh) {
  16109. mesh.position = mesh.position.subtract(mainMesh.position);
  16110. mesh.parent = mainMesh;
  16111. }
  16112. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16113. }
  16114. mainMesh.physicsImpostor.forceUpdate();
  16115. };
  16116. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16117. var mesh = compound.parts[0].mesh;
  16118. mesh.physicsImpostor.dispose();
  16119. mesh.physicsImpostor = null;
  16120. };
  16121. // Misc.
  16122. Scene.prototype.createDefaultCameraOrLight = function () {
  16123. // Light
  16124. if (this.lights.length === 0) {
  16125. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16126. }
  16127. // Camera
  16128. if (!this.activeCamera) {
  16129. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16130. // Compute position
  16131. var worldExtends = this.getWorldExtends();
  16132. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16133. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16134. camera.setTarget(worldCenter);
  16135. this.activeCamera = camera;
  16136. }
  16137. };
  16138. // Tags
  16139. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16140. if (tagsQuery === undefined) {
  16141. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16142. return list;
  16143. }
  16144. var listByTags = [];
  16145. forEach = forEach || (function (item) { return; });
  16146. for (var i in list) {
  16147. var item = list[i];
  16148. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16149. listByTags.push(item);
  16150. forEach(item);
  16151. }
  16152. }
  16153. return listByTags;
  16154. };
  16155. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16156. return this._getByTags(this.meshes, tagsQuery, forEach);
  16157. };
  16158. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16159. return this._getByTags(this.cameras, tagsQuery, forEach);
  16160. };
  16161. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16162. return this._getByTags(this.lights, tagsQuery, forEach);
  16163. };
  16164. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16165. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16166. };
  16167. // Statics
  16168. Scene._FOGMODE_NONE = 0;
  16169. Scene._FOGMODE_EXP = 1;
  16170. Scene._FOGMODE_EXP2 = 2;
  16171. Scene._FOGMODE_LINEAR = 3;
  16172. Scene.MinDeltaTime = 1.0;
  16173. Scene.MaxDeltaTime = 1000.0;
  16174. return Scene;
  16175. }());
  16176. BABYLON.Scene = Scene;
  16177. })(BABYLON || (BABYLON = {}));
  16178. var BABYLON;
  16179. (function (BABYLON) {
  16180. var VertexBuffer = (function () {
  16181. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16182. if (engine instanceof BABYLON.Mesh) {
  16183. this._engine = engine.getScene().getEngine();
  16184. }
  16185. else {
  16186. this._engine = engine;
  16187. }
  16188. this._updatable = updatable;
  16189. this._data = data;
  16190. if (!postponeInternalCreation) {
  16191. this.create();
  16192. }
  16193. this._kind = kind;
  16194. if (stride) {
  16195. this._strideSize = stride;
  16196. return;
  16197. }
  16198. // Deduce stride from kind
  16199. switch (kind) {
  16200. case VertexBuffer.PositionKind:
  16201. this._strideSize = 3;
  16202. break;
  16203. case VertexBuffer.NormalKind:
  16204. this._strideSize = 3;
  16205. break;
  16206. case VertexBuffer.UVKind:
  16207. case VertexBuffer.UV2Kind:
  16208. case VertexBuffer.UV3Kind:
  16209. case VertexBuffer.UV4Kind:
  16210. case VertexBuffer.UV5Kind:
  16211. case VertexBuffer.UV6Kind:
  16212. this._strideSize = 2;
  16213. break;
  16214. case VertexBuffer.ColorKind:
  16215. this._strideSize = 4;
  16216. break;
  16217. case VertexBuffer.MatricesIndicesKind:
  16218. case VertexBuffer.MatricesIndicesExtraKind:
  16219. this._strideSize = 4;
  16220. break;
  16221. case VertexBuffer.MatricesWeightsKind:
  16222. case VertexBuffer.MatricesWeightsExtraKind:
  16223. this._strideSize = 4;
  16224. break;
  16225. }
  16226. }
  16227. // Properties
  16228. VertexBuffer.prototype.isUpdatable = function () {
  16229. return this._updatable;
  16230. };
  16231. VertexBuffer.prototype.getData = function () {
  16232. return this._data;
  16233. };
  16234. VertexBuffer.prototype.getBuffer = function () {
  16235. return this._buffer;
  16236. };
  16237. VertexBuffer.prototype.getStrideSize = function () {
  16238. return this._strideSize;
  16239. };
  16240. // Methods
  16241. VertexBuffer.prototype.create = function (data) {
  16242. if (!data && this._buffer) {
  16243. return; // nothing to do
  16244. }
  16245. data = data || this._data;
  16246. if (!this._buffer) {
  16247. if (this._updatable) {
  16248. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16249. }
  16250. else {
  16251. this._buffer = this._engine.createVertexBuffer(data);
  16252. }
  16253. }
  16254. if (this._updatable) {
  16255. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16256. this._data = data;
  16257. }
  16258. };
  16259. VertexBuffer.prototype.update = function (data) {
  16260. this.create(data);
  16261. };
  16262. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16263. if (!this._buffer) {
  16264. return;
  16265. }
  16266. if (this._updatable) {
  16267. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16268. this._data = null;
  16269. }
  16270. };
  16271. VertexBuffer.prototype.dispose = function () {
  16272. if (!this._buffer) {
  16273. return;
  16274. }
  16275. if (this._engine._releaseBuffer(this._buffer)) {
  16276. this._buffer = null;
  16277. }
  16278. };
  16279. Object.defineProperty(VertexBuffer, "PositionKind", {
  16280. get: function () {
  16281. return VertexBuffer._PositionKind;
  16282. },
  16283. enumerable: true,
  16284. configurable: true
  16285. });
  16286. Object.defineProperty(VertexBuffer, "NormalKind", {
  16287. get: function () {
  16288. return VertexBuffer._NormalKind;
  16289. },
  16290. enumerable: true,
  16291. configurable: true
  16292. });
  16293. Object.defineProperty(VertexBuffer, "UVKind", {
  16294. get: function () {
  16295. return VertexBuffer._UVKind;
  16296. },
  16297. enumerable: true,
  16298. configurable: true
  16299. });
  16300. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16301. get: function () {
  16302. return VertexBuffer._UV2Kind;
  16303. },
  16304. enumerable: true,
  16305. configurable: true
  16306. });
  16307. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16308. get: function () {
  16309. return VertexBuffer._UV3Kind;
  16310. },
  16311. enumerable: true,
  16312. configurable: true
  16313. });
  16314. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16315. get: function () {
  16316. return VertexBuffer._UV4Kind;
  16317. },
  16318. enumerable: true,
  16319. configurable: true
  16320. });
  16321. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16322. get: function () {
  16323. return VertexBuffer._UV5Kind;
  16324. },
  16325. enumerable: true,
  16326. configurable: true
  16327. });
  16328. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16329. get: function () {
  16330. return VertexBuffer._UV6Kind;
  16331. },
  16332. enumerable: true,
  16333. configurable: true
  16334. });
  16335. Object.defineProperty(VertexBuffer, "ColorKind", {
  16336. get: function () {
  16337. return VertexBuffer._ColorKind;
  16338. },
  16339. enumerable: true,
  16340. configurable: true
  16341. });
  16342. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16343. get: function () {
  16344. return VertexBuffer._MatricesIndicesKind;
  16345. },
  16346. enumerable: true,
  16347. configurable: true
  16348. });
  16349. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16350. get: function () {
  16351. return VertexBuffer._MatricesWeightsKind;
  16352. },
  16353. enumerable: true,
  16354. configurable: true
  16355. });
  16356. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16357. get: function () {
  16358. return VertexBuffer._MatricesIndicesExtraKind;
  16359. },
  16360. enumerable: true,
  16361. configurable: true
  16362. });
  16363. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16364. get: function () {
  16365. return VertexBuffer._MatricesWeightsExtraKind;
  16366. },
  16367. enumerable: true,
  16368. configurable: true
  16369. });
  16370. // Enums
  16371. VertexBuffer._PositionKind = "position";
  16372. VertexBuffer._NormalKind = "normal";
  16373. VertexBuffer._UVKind = "uv";
  16374. VertexBuffer._UV2Kind = "uv2";
  16375. VertexBuffer._UV3Kind = "uv3";
  16376. VertexBuffer._UV4Kind = "uv4";
  16377. VertexBuffer._UV5Kind = "uv5";
  16378. VertexBuffer._UV6Kind = "uv6";
  16379. VertexBuffer._ColorKind = "color";
  16380. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16381. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16382. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16383. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16384. return VertexBuffer;
  16385. }());
  16386. BABYLON.VertexBuffer = VertexBuffer;
  16387. })(BABYLON || (BABYLON = {}));
  16388. var BABYLON;
  16389. (function (BABYLON) {
  16390. /**
  16391. * Creates an instance based on a source mesh.
  16392. */
  16393. var InstancedMesh = (function (_super) {
  16394. __extends(InstancedMesh, _super);
  16395. function InstancedMesh(name, source) {
  16396. _super.call(this, name, source.getScene());
  16397. source.instances.push(this);
  16398. this._sourceMesh = source;
  16399. this.position.copyFrom(source.position);
  16400. this.rotation.copyFrom(source.rotation);
  16401. this.scaling.copyFrom(source.scaling);
  16402. if (source.rotationQuaternion) {
  16403. this.rotationQuaternion = source.rotationQuaternion.clone();
  16404. }
  16405. this.infiniteDistance = source.infiniteDistance;
  16406. this.setPivotMatrix(source.getPivotMatrix());
  16407. this.refreshBoundingInfo();
  16408. this._syncSubMeshes();
  16409. }
  16410. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16411. // Methods
  16412. get: function () {
  16413. return this._sourceMesh.receiveShadows;
  16414. },
  16415. enumerable: true,
  16416. configurable: true
  16417. });
  16418. Object.defineProperty(InstancedMesh.prototype, "material", {
  16419. get: function () {
  16420. return this._sourceMesh.material;
  16421. },
  16422. enumerable: true,
  16423. configurable: true
  16424. });
  16425. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16426. get: function () {
  16427. return this._sourceMesh.visibility;
  16428. },
  16429. enumerable: true,
  16430. configurable: true
  16431. });
  16432. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16433. get: function () {
  16434. return this._sourceMesh.skeleton;
  16435. },
  16436. enumerable: true,
  16437. configurable: true
  16438. });
  16439. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16440. get: function () {
  16441. return this._sourceMesh.renderingGroupId;
  16442. },
  16443. enumerable: true,
  16444. configurable: true
  16445. });
  16446. InstancedMesh.prototype.getTotalVertices = function () {
  16447. return this._sourceMesh.getTotalVertices();
  16448. };
  16449. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16450. get: function () {
  16451. return this._sourceMesh;
  16452. },
  16453. enumerable: true,
  16454. configurable: true
  16455. });
  16456. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16457. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16458. };
  16459. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16460. return this._sourceMesh.isVerticesDataPresent(kind);
  16461. };
  16462. InstancedMesh.prototype.getIndices = function () {
  16463. return this._sourceMesh.getIndices();
  16464. };
  16465. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16466. get: function () {
  16467. return this._sourceMesh._positions;
  16468. },
  16469. enumerable: true,
  16470. configurable: true
  16471. });
  16472. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16473. var meshBB = this._sourceMesh.getBoundingInfo();
  16474. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16475. this._updateBoundingInfo();
  16476. };
  16477. InstancedMesh.prototype._preActivate = function () {
  16478. if (this._currentLOD) {
  16479. this._currentLOD._preActivate();
  16480. }
  16481. };
  16482. InstancedMesh.prototype._activate = function (renderId) {
  16483. if (this._currentLOD) {
  16484. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16485. }
  16486. };
  16487. InstancedMesh.prototype.getLOD = function (camera) {
  16488. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16489. if (this._currentLOD === this.sourceMesh) {
  16490. return this;
  16491. }
  16492. return this._currentLOD;
  16493. };
  16494. InstancedMesh.prototype._syncSubMeshes = function () {
  16495. this.releaseSubMeshes();
  16496. if (this._sourceMesh.subMeshes) {
  16497. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16498. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16499. }
  16500. }
  16501. };
  16502. InstancedMesh.prototype._generatePointsArray = function () {
  16503. return this._sourceMesh._generatePointsArray();
  16504. };
  16505. // Clone
  16506. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16507. var result = this._sourceMesh.createInstance(name);
  16508. // Deep copy
  16509. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16510. // Bounding info
  16511. this.refreshBoundingInfo();
  16512. // Parent
  16513. if (newParent) {
  16514. result.parent = newParent;
  16515. }
  16516. if (!doNotCloneChildren) {
  16517. // Children
  16518. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16519. var mesh = this.getScene().meshes[index];
  16520. if (mesh.parent === this) {
  16521. mesh.clone(mesh.name, result);
  16522. }
  16523. }
  16524. }
  16525. result.computeWorldMatrix(true);
  16526. return result;
  16527. };
  16528. // Dispoe
  16529. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16530. // Remove from mesh
  16531. var index = this._sourceMesh.instances.indexOf(this);
  16532. this._sourceMesh.instances.splice(index, 1);
  16533. _super.prototype.dispose.call(this, doNotRecurse);
  16534. };
  16535. return InstancedMesh;
  16536. }(BABYLON.AbstractMesh));
  16537. BABYLON.InstancedMesh = InstancedMesh;
  16538. })(BABYLON || (BABYLON = {}));
  16539. var BABYLON;
  16540. (function (BABYLON) {
  16541. var _InstancesBatch = (function () {
  16542. function _InstancesBatch() {
  16543. this.mustReturn = false;
  16544. this.visibleInstances = new Array();
  16545. this.renderSelf = new Array();
  16546. }
  16547. return _InstancesBatch;
  16548. }());
  16549. BABYLON._InstancesBatch = _InstancesBatch;
  16550. var Mesh = (function (_super) {
  16551. __extends(Mesh, _super);
  16552. /**
  16553. * @constructor
  16554. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16555. * @param {Scene} scene - The scene to add this mesh to.
  16556. * @param {Node} parent - The parent of this mesh, if it has one
  16557. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16558. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16559. * When false, achieved by calling a clone(), also passing False.
  16560. * This will make creation of children, recursive.
  16561. */
  16562. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16563. if (parent === void 0) { parent = null; }
  16564. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16565. _super.call(this, name, scene);
  16566. // Events
  16567. /**
  16568. * An event triggered before rendering the mesh
  16569. * @type {BABYLON.Observable}
  16570. */
  16571. this.onBeforeRenderObservable = new BABYLON.Observable();
  16572. /**
  16573. * An event triggered after rendering the mesh
  16574. * @type {BABYLON.Observable}
  16575. */
  16576. this.onAfterRenderObservable = new BABYLON.Observable();
  16577. /**
  16578. * An event triggered before drawing the mesh
  16579. * @type {BABYLON.Observable}
  16580. */
  16581. this.onBeforeDrawObservable = new BABYLON.Observable();
  16582. // Members
  16583. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16584. this.instances = new Array();
  16585. this._LODLevels = new Array();
  16586. this._visibleInstances = {};
  16587. this._renderIdForInstances = new Array();
  16588. this._batchCache = new _InstancesBatch();
  16589. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16590. this._sideOrientation = Mesh._DEFAULTSIDE;
  16591. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16592. if (source) {
  16593. // Geometry
  16594. if (source._geometry) {
  16595. source._geometry.applyToMesh(this);
  16596. }
  16597. // Deep copy
  16598. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16599. // Pivot
  16600. this.setPivotMatrix(source.getPivotMatrix());
  16601. this.id = name + "." + source.id;
  16602. // Material
  16603. this.material = source.material;
  16604. var index;
  16605. if (!doNotCloneChildren) {
  16606. // Children
  16607. for (index = 0; index < scene.meshes.length; index++) {
  16608. var mesh = scene.meshes[index];
  16609. if (mesh.parent === source) {
  16610. // doNotCloneChildren is always going to be False
  16611. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16612. }
  16613. }
  16614. }
  16615. // Physics clone
  16616. var physicsEngine = this.getScene().getPhysicsEngine();
  16617. if (clonePhysicsImpostor && physicsEngine) {
  16618. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16619. if (impostor) {
  16620. this.physicsImpostor = impostor.clone(this);
  16621. }
  16622. }
  16623. // Particles
  16624. for (index = 0; index < scene.particleSystems.length; index++) {
  16625. var system = scene.particleSystems[index];
  16626. if (system.emitter === source) {
  16627. system.clone(system.name, this);
  16628. }
  16629. }
  16630. this.computeWorldMatrix(true);
  16631. }
  16632. // Parent
  16633. if (parent !== null) {
  16634. this.parent = parent;
  16635. }
  16636. }
  16637. Object.defineProperty(Mesh, "FRONTSIDE", {
  16638. /**
  16639. * Mesh side orientation : usually the external or front surface
  16640. */
  16641. get: function () {
  16642. return Mesh._FRONTSIDE;
  16643. },
  16644. enumerable: true,
  16645. configurable: true
  16646. });
  16647. Object.defineProperty(Mesh, "BACKSIDE", {
  16648. /**
  16649. * Mesh side orientation : usually the internal or back surface
  16650. */
  16651. get: function () {
  16652. return Mesh._BACKSIDE;
  16653. },
  16654. enumerable: true,
  16655. configurable: true
  16656. });
  16657. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16658. /**
  16659. * Mesh side orientation : both internal and external or front and back surfaces
  16660. */
  16661. get: function () {
  16662. return Mesh._DOUBLESIDE;
  16663. },
  16664. enumerable: true,
  16665. configurable: true
  16666. });
  16667. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16668. /**
  16669. * Mesh side orientation : by default, `FRONTSIDE`
  16670. */
  16671. get: function () {
  16672. return Mesh._DEFAULTSIDE;
  16673. },
  16674. enumerable: true,
  16675. configurable: true
  16676. });
  16677. Object.defineProperty(Mesh, "NO_CAP", {
  16678. /**
  16679. * Mesh cap setting : no cap
  16680. */
  16681. get: function () {
  16682. return Mesh._NO_CAP;
  16683. },
  16684. enumerable: true,
  16685. configurable: true
  16686. });
  16687. Object.defineProperty(Mesh, "CAP_START", {
  16688. /**
  16689. * Mesh cap setting : one cap at the beginning of the mesh
  16690. */
  16691. get: function () {
  16692. return Mesh._CAP_START;
  16693. },
  16694. enumerable: true,
  16695. configurable: true
  16696. });
  16697. Object.defineProperty(Mesh, "CAP_END", {
  16698. /**
  16699. * Mesh cap setting : one cap at the end of the mesh
  16700. */
  16701. get: function () {
  16702. return Mesh._CAP_END;
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. Object.defineProperty(Mesh, "CAP_ALL", {
  16708. /**
  16709. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16710. */
  16711. get: function () {
  16712. return Mesh._CAP_ALL;
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16718. set: function (callback) {
  16719. if (this._onBeforeDrawObserver) {
  16720. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16721. }
  16722. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16723. },
  16724. enumerable: true,
  16725. configurable: true
  16726. });
  16727. // Methods
  16728. /**
  16729. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16730. */
  16731. Mesh.prototype.toString = function (fullDetails) {
  16732. var ret = _super.prototype.toString.call(this, fullDetails);
  16733. ret += ", n vertices: " + this.getTotalVertices();
  16734. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16735. if (this.animations) {
  16736. for (var i = 0; i < this.animations.length; i++) {
  16737. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16738. }
  16739. }
  16740. if (fullDetails) {
  16741. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16742. }
  16743. return ret;
  16744. };
  16745. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16746. get: function () {
  16747. return this._LODLevels.length > 0;
  16748. },
  16749. enumerable: true,
  16750. configurable: true
  16751. });
  16752. Mesh.prototype._sortLODLevels = function () {
  16753. this._LODLevels.sort(function (a, b) {
  16754. if (a.distance < b.distance) {
  16755. return 1;
  16756. }
  16757. if (a.distance > b.distance) {
  16758. return -1;
  16759. }
  16760. return 0;
  16761. });
  16762. };
  16763. /**
  16764. * Add a mesh as LOD level triggered at the given distance.
  16765. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16766. * @param {number} distance - the distance from the center of the object to show this level
  16767. * @param {Mesh} mesh - the mesh to be added as LOD level
  16768. * @return {Mesh} this mesh (for chaining)
  16769. */
  16770. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16771. if (mesh && mesh._masterMesh) {
  16772. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16773. return this;
  16774. }
  16775. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16776. this._LODLevels.push(level);
  16777. if (mesh) {
  16778. mesh._masterMesh = this;
  16779. }
  16780. this._sortLODLevels();
  16781. return this;
  16782. };
  16783. /**
  16784. * Returns the LOD level mesh at the passed distance or null if not found.
  16785. * It is related to the method `addLODLevel(distance, mesh)`.
  16786. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16787. */
  16788. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16789. for (var index = 0; index < this._LODLevels.length; index++) {
  16790. var level = this._LODLevels[index];
  16791. if (level.distance === distance) {
  16792. return level.mesh;
  16793. }
  16794. }
  16795. return null;
  16796. };
  16797. /**
  16798. * Remove a mesh from the LOD array
  16799. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16800. * @param {Mesh} mesh - the mesh to be removed.
  16801. * @return {Mesh} this mesh (for chaining)
  16802. */
  16803. Mesh.prototype.removeLODLevel = function (mesh) {
  16804. for (var index = 0; index < this._LODLevels.length; index++) {
  16805. if (this._LODLevels[index].mesh === mesh) {
  16806. this._LODLevels.splice(index, 1);
  16807. if (mesh) {
  16808. mesh._masterMesh = null;
  16809. }
  16810. }
  16811. }
  16812. this._sortLODLevels();
  16813. return this;
  16814. };
  16815. /**
  16816. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  16817. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16818. */
  16819. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16820. if (!this._LODLevels || this._LODLevels.length === 0) {
  16821. return this;
  16822. }
  16823. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  16824. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16825. if (this.onLODLevelSelection) {
  16826. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16827. }
  16828. return this;
  16829. }
  16830. for (var index = 0; index < this._LODLevels.length; index++) {
  16831. var level = this._LODLevels[index];
  16832. if (level.distance < distanceToCamera) {
  16833. if (level.mesh) {
  16834. level.mesh._preActivate();
  16835. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16836. }
  16837. if (this.onLODLevelSelection) {
  16838. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16839. }
  16840. return level.mesh;
  16841. }
  16842. }
  16843. if (this.onLODLevelSelection) {
  16844. this.onLODLevelSelection(distanceToCamera, this, this);
  16845. }
  16846. return this;
  16847. };
  16848. Object.defineProperty(Mesh.prototype, "geometry", {
  16849. /**
  16850. * Returns the mesh internal `Geometry` object.
  16851. */
  16852. get: function () {
  16853. return this._geometry;
  16854. },
  16855. enumerable: true,
  16856. configurable: true
  16857. });
  16858. /**
  16859. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  16860. */
  16861. Mesh.prototype.getTotalVertices = function () {
  16862. if (!this._geometry) {
  16863. return 0;
  16864. }
  16865. return this._geometry.getTotalVertices();
  16866. };
  16867. /**
  16868. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  16869. * If `copywhenShared` is true (default false) and if the mesh has submeshes, the submesh data are duplicated in the returned array.
  16870. * Returns null if the mesh has no geometry or no vertex buffer.
  16871. * Possible `kind` values :
  16872. * - BABYLON.VertexBuffer.PositionKind
  16873. * - BABYLON.VertexBuffer.UVKind
  16874. * - BABYLON.VertexBuffer.UV2Kind
  16875. * - BABYLON.VertexBuffer.UV3Kind
  16876. * - BABYLON.VertexBuffer.UV4Kind
  16877. * - BABYLON.VertexBuffer.UV5Kind
  16878. * - BABYLON.VertexBuffer.UV6Kind
  16879. * - BABYLON.VertexBuffer.ColorKind
  16880. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16881. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16882. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16883. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16884. */
  16885. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16886. if (!this._geometry) {
  16887. return null;
  16888. }
  16889. return this._geometry.getVerticesData(kind, copyWhenShared);
  16890. };
  16891. /**
  16892. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  16893. * Returns `undefined` if the mesh has no geometry.
  16894. * Possible `kind` values :
  16895. * - BABYLON.VertexBuffer.PositionKind
  16896. * - BABYLON.VertexBuffer.UVKind
  16897. * - BABYLON.VertexBuffer.UV2Kind
  16898. * - BABYLON.VertexBuffer.UV3Kind
  16899. * - BABYLON.VertexBuffer.UV4Kind
  16900. * - BABYLON.VertexBuffer.UV5Kind
  16901. * - BABYLON.VertexBuffer.UV6Kind
  16902. * - BABYLON.VertexBuffer.ColorKind
  16903. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16904. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16905. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16906. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16907. */
  16908. Mesh.prototype.getVertexBuffer = function (kind) {
  16909. if (!this._geometry) {
  16910. return undefined;
  16911. }
  16912. return this._geometry.getVertexBuffer(kind);
  16913. };
  16914. /**
  16915. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  16916. * Possible `kind` values :
  16917. * - BABYLON.VertexBuffer.PositionKind
  16918. * - BABYLON.VertexBuffer.UVKind
  16919. * - BABYLON.VertexBuffer.UV2Kind
  16920. * - BABYLON.VertexBuffer.UV3Kind
  16921. * - BABYLON.VertexBuffer.UV4Kind
  16922. * - BABYLON.VertexBuffer.UV5Kind
  16923. * - BABYLON.VertexBuffer.UV6Kind
  16924. * - BABYLON.VertexBuffer.ColorKind
  16925. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16926. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16927. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16928. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16929. */
  16930. Mesh.prototype.isVerticesDataPresent = function (kind) {
  16931. if (!this._geometry) {
  16932. if (this._delayInfo) {
  16933. return this._delayInfo.indexOf(kind) !== -1;
  16934. }
  16935. return false;
  16936. }
  16937. return this._geometry.isVerticesDataPresent(kind);
  16938. };
  16939. /**
  16940. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  16941. * Possible `kind` values :
  16942. * - BABYLON.VertexBuffer.PositionKind
  16943. * - BABYLON.VertexBuffer.UVKind
  16944. * - BABYLON.VertexBuffer.UV2Kind
  16945. * - BABYLON.VertexBuffer.UV3Kind
  16946. * - BABYLON.VertexBuffer.UV4Kind
  16947. * - BABYLON.VertexBuffer.UV5Kind
  16948. * - BABYLON.VertexBuffer.UV6Kind
  16949. * - BABYLON.VertexBuffer.ColorKind
  16950. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16951. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16952. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16953. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16954. */
  16955. Mesh.prototype.getVerticesDataKinds = function () {
  16956. if (!this._geometry) {
  16957. var result = [];
  16958. if (this._delayInfo) {
  16959. for (var kind in this._delayInfo) {
  16960. result.push(kind);
  16961. }
  16962. }
  16963. return result;
  16964. }
  16965. return this._geometry.getVerticesDataKinds();
  16966. };
  16967. /**
  16968. * Returns a positive integer : the total number of indices in this mesh geometry.
  16969. * Returns zero if the mesh has no geometry.
  16970. */
  16971. Mesh.prototype.getTotalIndices = function () {
  16972. if (!this._geometry) {
  16973. return 0;
  16974. }
  16975. return this._geometry.getTotalIndices();
  16976. };
  16977. /**
  16978. * Returns an array of integers or a Int32Array populated with the mesh indices.
  16979. * If the parameter `copyWhenShared` is true (default false) and if the mesh has submeshes, the submesh indices are duplicated in the returned array.
  16980. * Returns an empty array if the mesh has no geometry.
  16981. */
  16982. Mesh.prototype.getIndices = function (copyWhenShared) {
  16983. if (!this._geometry) {
  16984. return [];
  16985. }
  16986. return this._geometry.getIndices(copyWhenShared);
  16987. };
  16988. Object.defineProperty(Mesh.prototype, "isBlocked", {
  16989. get: function () {
  16990. return this._masterMesh !== null && this._masterMesh !== undefined;
  16991. },
  16992. enumerable: true,
  16993. configurable: true
  16994. });
  16995. /**
  16996. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  16997. */
  16998. Mesh.prototype.isReady = function () {
  16999. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17000. return false;
  17001. }
  17002. return _super.prototype.isReady.call(this);
  17003. };
  17004. /**
  17005. * Boolean : true if the mesh has been disposed.
  17006. */
  17007. Mesh.prototype.isDisposed = function () {
  17008. return this._isDisposed;
  17009. };
  17010. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17011. get: function () {
  17012. return this._sideOrientation;
  17013. },
  17014. /**
  17015. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17016. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17017. */
  17018. set: function (sideO) {
  17019. this._sideOrientation = sideO;
  17020. },
  17021. enumerable: true,
  17022. configurable: true
  17023. });
  17024. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17025. /**
  17026. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17027. * This property is pertinent only for updatable parametric shapes.
  17028. */
  17029. get: function () {
  17030. return this._areNormalsFrozen;
  17031. },
  17032. enumerable: true,
  17033. configurable: true
  17034. });
  17035. /**
  17036. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17037. * It has no effect at all on other shapes.
  17038. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17039. */
  17040. Mesh.prototype.freezeNormals = function () {
  17041. this._areNormalsFrozen = true;
  17042. };
  17043. /**
  17044. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17045. * It has no effect at all on other shapes.
  17046. * It reactivates the mesh normals computation if it was previously frozen.
  17047. */
  17048. Mesh.prototype.unfreezeNormals = function () {
  17049. this._areNormalsFrozen = false;
  17050. };
  17051. // Methods
  17052. Mesh.prototype._preActivate = function () {
  17053. var sceneRenderId = this.getScene().getRenderId();
  17054. if (this._preActivateId === sceneRenderId) {
  17055. return;
  17056. }
  17057. this._preActivateId = sceneRenderId;
  17058. this._visibleInstances = null;
  17059. };
  17060. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17061. if (this._visibleInstances) {
  17062. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17063. }
  17064. };
  17065. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17066. if (!this._visibleInstances) {
  17067. this._visibleInstances = {};
  17068. this._visibleInstances.defaultRenderId = renderId;
  17069. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17070. }
  17071. if (!this._visibleInstances[renderId]) {
  17072. this._visibleInstances[renderId] = new Array();
  17073. }
  17074. this._visibleInstances[renderId].push(instance);
  17075. };
  17076. /**
  17077. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17078. * This means the mesh underlying bounding box and shpere are recomputed.
  17079. */
  17080. Mesh.prototype.refreshBoundingInfo = function () {
  17081. if (this._boundingInfo.isLocked) {
  17082. return;
  17083. }
  17084. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17085. if (data) {
  17086. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17087. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17088. }
  17089. if (this.subMeshes) {
  17090. for (var index = 0; index < this.subMeshes.length; index++) {
  17091. this.subMeshes[index].refreshBoundingInfo();
  17092. }
  17093. }
  17094. this._updateBoundingInfo();
  17095. };
  17096. Mesh.prototype._createGlobalSubMesh = function () {
  17097. var totalVertices = this.getTotalVertices();
  17098. if (!totalVertices || !this.getIndices()) {
  17099. return null;
  17100. }
  17101. this.releaseSubMeshes();
  17102. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17103. };
  17104. Mesh.prototype.subdivide = function (count) {
  17105. if (count < 1) {
  17106. return;
  17107. }
  17108. var totalIndices = this.getTotalIndices();
  17109. var subdivisionSize = (totalIndices / count) | 0;
  17110. var offset = 0;
  17111. // Ensure that subdivisionSize is a multiple of 3
  17112. while (subdivisionSize % 3 !== 0) {
  17113. subdivisionSize++;
  17114. }
  17115. this.releaseSubMeshes();
  17116. for (var index = 0; index < count; index++) {
  17117. if (offset >= totalIndices) {
  17118. break;
  17119. }
  17120. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17121. offset += subdivisionSize;
  17122. }
  17123. this.synchronizeInstances();
  17124. };
  17125. /**
  17126. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17127. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17128. * The `data` are either a numeric array either a Float32Array.
  17129. * 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).
  17130. * Note that a new underlying `VertexBuffer` object is created each call.
  17131. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17132. * The same for the mesh submeshes if any.
  17133. *
  17134. * Possible `kind` values :
  17135. * - BABYLON.VertexBuffer.PositionKind
  17136. * - BABYLON.VertexBuffer.UVKind
  17137. * - BABYLON.VertexBuffer.UV2Kind
  17138. * - BABYLON.VertexBuffer.UV3Kind
  17139. * - BABYLON.VertexBuffer.UV4Kind
  17140. * - BABYLON.VertexBuffer.UV5Kind
  17141. * - BABYLON.VertexBuffer.UV6Kind
  17142. * - BABYLON.VertexBuffer.ColorKind
  17143. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17144. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17145. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17146. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17147. */
  17148. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17149. if (!this._geometry) {
  17150. var vertexData = new BABYLON.VertexData();
  17151. vertexData.set(data, kind);
  17152. var scene = this.getScene();
  17153. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17154. }
  17155. else {
  17156. this._geometry.setVerticesData(kind, data, updatable, stride);
  17157. }
  17158. };
  17159. /**
  17160. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17161. * If the mesh has no geometry, it is simply returned as it is.
  17162. * The `data` are either a numeric array either a Float32Array.
  17163. * No new underlying `VertexBuffer` object is created.
  17164. * 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.
  17165. * The same for the mesh submeshes if any.
  17166. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17167. *
  17168. * Possible `kind` values :
  17169. * - BABYLON.VertexBuffer.PositionKind
  17170. * - BABYLON.VertexBuffer.UVKind
  17171. * - BABYLON.VertexBuffer.UV2Kind
  17172. * - BABYLON.VertexBuffer.UV3Kind
  17173. * - BABYLON.VertexBuffer.UV4Kind
  17174. * - BABYLON.VertexBuffer.UV5Kind
  17175. * - BABYLON.VertexBuffer.UV6Kind
  17176. * - BABYLON.VertexBuffer.ColorKind
  17177. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17178. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17179. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17180. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17181. */
  17182. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17183. if (!this._geometry) {
  17184. return;
  17185. }
  17186. if (!makeItUnique) {
  17187. this._geometry.updateVerticesData(kind, data, updateExtends);
  17188. }
  17189. else {
  17190. this.makeGeometryUnique();
  17191. this.updateVerticesData(kind, data, updateExtends, false);
  17192. }
  17193. };
  17194. /**
  17195. * Deprecated since BabylonJS v2.3
  17196. */
  17197. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17198. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17199. if (!this._geometry) {
  17200. return;
  17201. }
  17202. if (!makeItUnique) {
  17203. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17204. }
  17205. else {
  17206. this.makeGeometryUnique();
  17207. this.updateVerticesDataDirectly(kind, data, offset, false);
  17208. }
  17209. };
  17210. /**
  17211. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17212. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17213. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17214. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17215. */
  17216. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17217. if (computeNormals === void 0) { computeNormals = true; }
  17218. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17219. positionFunction(positions);
  17220. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17221. if (computeNormals) {
  17222. var indices = this.getIndices();
  17223. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17224. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17225. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17226. }
  17227. };
  17228. Mesh.prototype.makeGeometryUnique = function () {
  17229. if (!this._geometry) {
  17230. return;
  17231. }
  17232. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17233. geometry.applyToMesh(this);
  17234. };
  17235. /**
  17236. * Sets the mesh indices.
  17237. * Expects an array populated with integers or a Int32Array.
  17238. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17239. * This method creates a new index buffer each call.
  17240. */
  17241. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17242. if (!this._geometry) {
  17243. var vertexData = new BABYLON.VertexData();
  17244. vertexData.indices = indices;
  17245. var scene = this.getScene();
  17246. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17247. }
  17248. else {
  17249. this._geometry.setIndices(indices, totalVertices);
  17250. }
  17251. };
  17252. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17253. var engine = this.getScene().getEngine();
  17254. // Wireframe
  17255. var indexToBind;
  17256. if (this._unIndexed) {
  17257. indexToBind = null;
  17258. }
  17259. else {
  17260. switch (fillMode) {
  17261. case BABYLON.Material.PointFillMode:
  17262. indexToBind = null;
  17263. break;
  17264. case BABYLON.Material.WireFrameFillMode:
  17265. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17266. break;
  17267. default:
  17268. case BABYLON.Material.TriangleFillMode:
  17269. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17270. break;
  17271. }
  17272. }
  17273. // VBOs
  17274. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17275. };
  17276. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17277. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17278. return;
  17279. }
  17280. this.onBeforeDrawObservable.notifyObservers(this);
  17281. var engine = this.getScene().getEngine();
  17282. // Draw order
  17283. switch (fillMode) {
  17284. case BABYLON.Material.PointFillMode:
  17285. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17286. break;
  17287. case BABYLON.Material.WireFrameFillMode:
  17288. if (this._unIndexed) {
  17289. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17290. }
  17291. else {
  17292. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17293. }
  17294. break;
  17295. default:
  17296. if (this._unIndexed) {
  17297. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17298. }
  17299. else {
  17300. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17301. }
  17302. }
  17303. };
  17304. /**
  17305. * Registers a javascript function for this mesh that will be called just before the rendering process.
  17306. * This function is passed the current mesh and doesn't return anything.
  17307. */
  17308. Mesh.prototype.registerBeforeRender = function (func) {
  17309. this.onBeforeRenderObservable.add(func);
  17310. };
  17311. /**
  17312. * Disposes a previously registered javascript function called before the rendering.
  17313. * This function is passed the current mesh and doesn't return anything.
  17314. */
  17315. Mesh.prototype.unregisterBeforeRender = function (func) {
  17316. this.onBeforeRenderObservable.removeCallback(func);
  17317. };
  17318. /**
  17319. * Registers a javascript function for this mesh that will be called just after the rendering is complete.
  17320. * This function is passed the current mesh and doesn't return anything.
  17321. */
  17322. Mesh.prototype.registerAfterRender = function (func) {
  17323. this.onAfterRenderObservable.add(func);
  17324. };
  17325. /**
  17326. * Disposes a previously registered javascript function called after the rendering.
  17327. * This function is passed the current mesh and doesn't return anything.
  17328. */
  17329. Mesh.prototype.unregisterAfterRender = function (func) {
  17330. this.onAfterRenderObservable.removeCallback(func);
  17331. };
  17332. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17333. var scene = this.getScene();
  17334. this._batchCache.mustReturn = false;
  17335. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17336. this._batchCache.visibleInstances[subMeshId] = null;
  17337. if (this._visibleInstances) {
  17338. var currentRenderId = scene.getRenderId();
  17339. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17340. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17341. var selfRenderId = this._renderId;
  17342. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17343. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17344. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17345. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17346. }
  17347. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17348. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17349. this._batchCache.mustReturn = true;
  17350. return this._batchCache;
  17351. }
  17352. if (currentRenderId !== selfRenderId) {
  17353. this._batchCache.renderSelf[subMeshId] = false;
  17354. }
  17355. }
  17356. this._renderIdForInstances[subMeshId] = currentRenderId;
  17357. }
  17358. return this._batchCache;
  17359. };
  17360. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17361. var visibleInstances = batch.visibleInstances[subMesh._id];
  17362. var matricesCount = visibleInstances.length + 1;
  17363. var bufferSize = matricesCount * 16 * 4;
  17364. while (this._instancesBufferSize < bufferSize) {
  17365. this._instancesBufferSize *= 2;
  17366. }
  17367. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17368. if (this._worldMatricesInstancesBuffer) {
  17369. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17370. }
  17371. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17372. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17373. }
  17374. var offset = 0;
  17375. var instancesCount = 0;
  17376. var world = this.getWorldMatrix();
  17377. if (batch.renderSelf[subMesh._id]) {
  17378. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17379. offset += 16;
  17380. instancesCount++;
  17381. }
  17382. if (visibleInstances) {
  17383. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17384. var instance = visibleInstances[instanceIndex];
  17385. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17386. offset += 16;
  17387. instancesCount++;
  17388. }
  17389. }
  17390. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17391. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17392. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17393. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17394. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17395. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17396. this._draw(subMesh, fillMode, instancesCount);
  17397. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17398. };
  17399. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17400. var scene = this.getScene();
  17401. var engine = scene.getEngine();
  17402. if (hardwareInstancedRendering) {
  17403. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17404. }
  17405. else {
  17406. if (batch.renderSelf[subMesh._id]) {
  17407. // Draw
  17408. if (onBeforeDraw) {
  17409. onBeforeDraw(false, this.getWorldMatrix());
  17410. }
  17411. this._draw(subMesh, fillMode);
  17412. }
  17413. if (batch.visibleInstances[subMesh._id]) {
  17414. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17415. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17416. // World
  17417. var world = instance.getWorldMatrix();
  17418. if (onBeforeDraw) {
  17419. onBeforeDraw(true, world);
  17420. }
  17421. // Draw
  17422. this._draw(subMesh, fillMode);
  17423. }
  17424. }
  17425. }
  17426. };
  17427. /**
  17428. * Triggers the draw call for the mesh.
  17429. * You don't need to call this method by your own usually because the mesh rendering is handled by the scene rendering manager.
  17430. */
  17431. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17432. var scene = this.getScene();
  17433. // Managing instances
  17434. var batch = this._getInstancesRenderList(subMesh._id);
  17435. if (batch.mustReturn) {
  17436. return;
  17437. }
  17438. // Checking geometry state
  17439. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17440. return;
  17441. }
  17442. var callbackIndex;
  17443. this.onBeforeRenderObservable.notifyObservers(this);
  17444. var engine = scene.getEngine();
  17445. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17446. // Material
  17447. var effectiveMaterial = subMesh.getMaterial();
  17448. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17449. return;
  17450. }
  17451. // Outline - step 1
  17452. var savedDepthWrite = engine.getDepthWrite();
  17453. if (this.renderOutline) {
  17454. engine.setDepthWrite(false);
  17455. scene.getOutlineRenderer().render(subMesh, batch);
  17456. engine.setDepthWrite(savedDepthWrite);
  17457. }
  17458. effectiveMaterial._preBind();
  17459. var effect = effectiveMaterial.getEffect();
  17460. // Bind
  17461. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17462. this._bind(subMesh, effect, fillMode);
  17463. var world = this.getWorldMatrix();
  17464. effectiveMaterial.bind(world, this);
  17465. // Alpha mode
  17466. if (enableAlphaMode) {
  17467. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17468. }
  17469. // Draw
  17470. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17471. if (isInstance) {
  17472. effectiveMaterial.bindOnlyWorldMatrix(world);
  17473. }
  17474. });
  17475. // Unbind
  17476. effectiveMaterial.unbind();
  17477. // Outline - step 2
  17478. if (this.renderOutline && savedDepthWrite) {
  17479. engine.setDepthWrite(true);
  17480. engine.setColorWrite(false);
  17481. scene.getOutlineRenderer().render(subMesh, batch);
  17482. engine.setColorWrite(true);
  17483. }
  17484. // Overlay
  17485. if (this.renderOverlay) {
  17486. var currentMode = engine.getAlphaMode();
  17487. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17488. scene.getOutlineRenderer().render(subMesh, batch, true);
  17489. engine.setAlphaMode(currentMode);
  17490. }
  17491. this.onAfterRenderObservable.notifyObservers(this);
  17492. };
  17493. /**
  17494. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17495. */
  17496. Mesh.prototype.getEmittedParticleSystems = function () {
  17497. var results = new Array();
  17498. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17499. var particleSystem = this.getScene().particleSystems[index];
  17500. if (particleSystem.emitter === this) {
  17501. results.push(particleSystem);
  17502. }
  17503. }
  17504. return results;
  17505. };
  17506. /**
  17507. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17508. */
  17509. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17510. var results = new Array();
  17511. var descendants = this.getDescendants();
  17512. descendants.push(this);
  17513. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17514. var particleSystem = this.getScene().particleSystems[index];
  17515. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17516. results.push(particleSystem);
  17517. }
  17518. }
  17519. return results;
  17520. };
  17521. Mesh.prototype._checkDelayState = function () {
  17522. var _this = this;
  17523. var that = this;
  17524. var scene = this.getScene();
  17525. if (this._geometry) {
  17526. this._geometry.load(scene);
  17527. }
  17528. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17529. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17530. scene._addPendingData(that);
  17531. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17532. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17533. if (data instanceof ArrayBuffer) {
  17534. _this._delayLoadingFunction(data, _this);
  17535. }
  17536. else {
  17537. _this._delayLoadingFunction(JSON.parse(data), _this);
  17538. }
  17539. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17540. scene._removePendingData(_this);
  17541. }, function () { }, scene.database, getBinaryData);
  17542. }
  17543. };
  17544. /**
  17545. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17546. */
  17547. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17548. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17549. return false;
  17550. }
  17551. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17552. return false;
  17553. }
  17554. this._checkDelayState();
  17555. return true;
  17556. };
  17557. Mesh.prototype.setMaterialByID = function (id) {
  17558. var materials = this.getScene().materials;
  17559. var index;
  17560. for (index = 0; index < materials.length; index++) {
  17561. if (materials[index].id === id) {
  17562. this.material = materials[index];
  17563. return;
  17564. }
  17565. }
  17566. // Multi
  17567. var multiMaterials = this.getScene().multiMaterials;
  17568. for (index = 0; index < multiMaterials.length; index++) {
  17569. if (multiMaterials[index].id === id) {
  17570. this.material = multiMaterials[index];
  17571. return;
  17572. }
  17573. }
  17574. };
  17575. Mesh.prototype.getAnimatables = function () {
  17576. var results = [];
  17577. if (this.material) {
  17578. results.push(this.material);
  17579. }
  17580. if (this.skeleton) {
  17581. results.push(this.skeleton);
  17582. }
  17583. return results;
  17584. };
  17585. // Geometry
  17586. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17587. // Position
  17588. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17589. return;
  17590. }
  17591. this._resetPointsArrayCache();
  17592. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17593. var temp = [];
  17594. var index;
  17595. for (index = 0; index < data.length; index += 3) {
  17596. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17597. }
  17598. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17599. // Normals
  17600. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17601. return;
  17602. }
  17603. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17604. temp = [];
  17605. for (index = 0; index < data.length; index += 3) {
  17606. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17607. }
  17608. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17609. // flip faces?
  17610. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17611. this.flipFaces();
  17612. }
  17613. };
  17614. // Will apply current transform to mesh and reset world matrix
  17615. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17616. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17617. this.scaling.copyFromFloats(1, 1, 1);
  17618. this.position.copyFromFloats(0, 0, 0);
  17619. this.rotation.copyFromFloats(0, 0, 0);
  17620. //only if quaternion is already set
  17621. if (this.rotationQuaternion) {
  17622. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17623. }
  17624. this._worldMatrix = BABYLON.Matrix.Identity();
  17625. };
  17626. // Cache
  17627. Mesh.prototype._resetPointsArrayCache = function () {
  17628. this._positions = null;
  17629. };
  17630. Mesh.prototype._generatePointsArray = function () {
  17631. if (this._positions)
  17632. return true;
  17633. this._positions = [];
  17634. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17635. if (!data) {
  17636. return false;
  17637. }
  17638. for (var index = 0; index < data.length; index += 3) {
  17639. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17640. }
  17641. return true;
  17642. };
  17643. // Clone
  17644. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17645. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17646. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17647. };
  17648. // Dispose
  17649. Mesh.prototype.dispose = function (doNotRecurse) {
  17650. if (this._geometry) {
  17651. this._geometry.releaseForMesh(this, true);
  17652. }
  17653. // Instances
  17654. if (this._worldMatricesInstancesBuffer) {
  17655. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17656. this._worldMatricesInstancesBuffer = null;
  17657. }
  17658. while (this.instances.length) {
  17659. this.instances[0].dispose();
  17660. }
  17661. _super.prototype.dispose.call(this, doNotRecurse);
  17662. };
  17663. // Geometric tools
  17664. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17665. var _this = this;
  17666. var scene = this.getScene();
  17667. var onload = function (img) {
  17668. // Getting height map data
  17669. var canvas = document.createElement("canvas");
  17670. var context = canvas.getContext("2d");
  17671. var heightMapWidth = img.width;
  17672. var heightMapHeight = img.height;
  17673. canvas.width = heightMapWidth;
  17674. canvas.height = heightMapHeight;
  17675. context.drawImage(img, 0, 0);
  17676. // Create VertexData from map data
  17677. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17678. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17679. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17680. //execute success callback, if set
  17681. if (onSuccess) {
  17682. onSuccess(_this);
  17683. }
  17684. };
  17685. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17686. };
  17687. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17688. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17689. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17690. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17691. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17692. return;
  17693. }
  17694. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17695. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17696. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17697. var position = BABYLON.Vector3.Zero();
  17698. var normal = BABYLON.Vector3.Zero();
  17699. var uv = BABYLON.Vector2.Zero();
  17700. for (var index = 0; index < positions.length; index += 3) {
  17701. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17702. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17703. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17704. // Compute height
  17705. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17706. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17707. var pos = (u + v * heightMapWidth) * 4;
  17708. var r = buffer[pos] / 255.0;
  17709. var g = buffer[pos + 1] / 255.0;
  17710. var b = buffer[pos + 2] / 255.0;
  17711. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17712. normal.normalize();
  17713. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17714. position = position.add(normal);
  17715. position.toArray(positions, index);
  17716. }
  17717. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  17718. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  17719. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17720. };
  17721. /**
  17722. * Modify the mesh to get a flat shading rendering.
  17723. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  17724. * Warning : the mesh is really modified.
  17725. */
  17726. Mesh.prototype.convertToFlatShadedMesh = function () {
  17727. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  17728. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17729. var kinds = this.getVerticesDataKinds();
  17730. var vbs = [];
  17731. var data = [];
  17732. var newdata = [];
  17733. var updatableNormals = false;
  17734. var kindIndex;
  17735. var kind;
  17736. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17737. kind = kinds[kindIndex];
  17738. var vertexBuffer = this.getVertexBuffer(kind);
  17739. if (kind === BABYLON.VertexBuffer.NormalKind) {
  17740. updatableNormals = vertexBuffer.isUpdatable();
  17741. kinds.splice(kindIndex, 1);
  17742. kindIndex--;
  17743. continue;
  17744. }
  17745. vbs[kind] = vertexBuffer;
  17746. data[kind] = vbs[kind].getData();
  17747. newdata[kind] = [];
  17748. }
  17749. // Save previous submeshes
  17750. var previousSubmeshes = this.subMeshes.slice(0);
  17751. var indices = this.getIndices();
  17752. var totalIndices = this.getTotalIndices();
  17753. // Generating unique vertices per face
  17754. var index;
  17755. for (index = 0; index < totalIndices; index++) {
  17756. var vertexIndex = indices[index];
  17757. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17758. kind = kinds[kindIndex];
  17759. var stride = vbs[kind].getStrideSize();
  17760. for (var offset = 0; offset < stride; offset++) {
  17761. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17762. }
  17763. }
  17764. }
  17765. // Updating faces & normal
  17766. var normals = [];
  17767. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17768. for (index = 0; index < totalIndices; index += 3) {
  17769. indices[index] = index;
  17770. indices[index + 1] = index + 1;
  17771. indices[index + 2] = index + 2;
  17772. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17773. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17774. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17775. var p1p2 = p1.subtract(p2);
  17776. var p3p2 = p3.subtract(p2);
  17777. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17778. // Store same normals for every vertex
  17779. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17780. normals.push(normal.x);
  17781. normals.push(normal.y);
  17782. normals.push(normal.z);
  17783. }
  17784. }
  17785. this.setIndices(indices);
  17786. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17787. // Updating vertex buffers
  17788. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17789. kind = kinds[kindIndex];
  17790. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17791. }
  17792. // Updating submeshes
  17793. this.releaseSubMeshes();
  17794. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17795. var previousOne = previousSubmeshes[submeshIndex];
  17796. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17797. }
  17798. this.synchronizeInstances();
  17799. };
  17800. /**
  17801. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  17802. * In other words, more vertices, no more indices and a single bigger VBO.
  17803. */
  17804. Mesh.prototype.convertToUnIndexedMesh = function () {
  17805. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17806. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17807. var kinds = this.getVerticesDataKinds();
  17808. var vbs = [];
  17809. var data = [];
  17810. var newdata = [];
  17811. var updatableNormals = false;
  17812. var kindIndex;
  17813. var kind;
  17814. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17815. kind = kinds[kindIndex];
  17816. var vertexBuffer = this.getVertexBuffer(kind);
  17817. vbs[kind] = vertexBuffer;
  17818. data[kind] = vbs[kind].getData();
  17819. newdata[kind] = [];
  17820. }
  17821. // Save previous submeshes
  17822. var previousSubmeshes = this.subMeshes.slice(0);
  17823. var indices = this.getIndices();
  17824. var totalIndices = this.getTotalIndices();
  17825. // Generating unique vertices per face
  17826. var index;
  17827. for (index = 0; index < totalIndices; index++) {
  17828. var vertexIndex = indices[index];
  17829. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17830. kind = kinds[kindIndex];
  17831. var stride = vbs[kind].getStrideSize();
  17832. for (var offset = 0; offset < stride; offset++) {
  17833. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17834. }
  17835. }
  17836. }
  17837. // Updating indices
  17838. for (index = 0; index < totalIndices; index += 3) {
  17839. indices[index] = index;
  17840. indices[index + 1] = index + 1;
  17841. indices[index + 2] = index + 2;
  17842. }
  17843. this.setIndices(indices);
  17844. // Updating vertex buffers
  17845. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17846. kind = kinds[kindIndex];
  17847. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17848. }
  17849. // Updating submeshes
  17850. this.releaseSubMeshes();
  17851. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17852. var previousOne = previousSubmeshes[submeshIndex];
  17853. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17854. }
  17855. this._unIndexed = true;
  17856. this.synchronizeInstances();
  17857. };
  17858. /**
  17859. * Inverses facet orientations and inverts also the normals with `flipNormals` (default false) if true.
  17860. * Warning : the mesh is really modified.
  17861. */
  17862. Mesh.prototype.flipFaces = function (flipNormals) {
  17863. if (flipNormals === void 0) { flipNormals = false; }
  17864. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17865. var i;
  17866. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17867. for (i = 0; i < vertex_data.normals.length; i++) {
  17868. vertex_data.normals[i] *= -1;
  17869. }
  17870. }
  17871. var temp;
  17872. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17873. // reassign indices
  17874. temp = vertex_data.indices[i + 1];
  17875. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17876. vertex_data.indices[i + 2] = temp;
  17877. }
  17878. vertex_data.applyToMesh(this);
  17879. };
  17880. // Instances
  17881. /**
  17882. * Creates a new `InstancedMesh` object from the mesh model.
  17883. */
  17884. Mesh.prototype.createInstance = function (name) {
  17885. return new BABYLON.InstancedMesh(name, this);
  17886. };
  17887. Mesh.prototype.synchronizeInstances = function () {
  17888. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17889. var instance = this.instances[instanceIndex];
  17890. instance._syncSubMeshes();
  17891. }
  17892. };
  17893. /**
  17894. * Simplify the mesh according to the given array of settings.
  17895. * Function will return immediately and will simplify async.
  17896. * @param settings a collection of simplification settings.
  17897. * @param parallelProcessing should all levels calculate parallel or one after the other.
  17898. * @param type the type of simplification to run.
  17899. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  17900. */
  17901. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  17902. if (parallelProcessing === void 0) { parallelProcessing = true; }
  17903. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  17904. this.getScene().simplificationQueue.addTask({
  17905. settings: settings,
  17906. parallelProcessing: parallelProcessing,
  17907. mesh: this,
  17908. simplificationType: simplificationType,
  17909. successCallback: successCallback
  17910. });
  17911. };
  17912. /**
  17913. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  17914. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  17915. * This should be used together with the simplification to avoid disappearing triangles.
  17916. * @param successCallback an optional success callback to be called after the optimization finished.
  17917. */
  17918. Mesh.prototype.optimizeIndices = function (successCallback) {
  17919. var _this = this;
  17920. var indices = this.getIndices();
  17921. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17922. var vectorPositions = [];
  17923. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  17924. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  17925. }
  17926. var dupes = [];
  17927. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  17928. var realPos = vectorPositions.length - 1 - iteration;
  17929. var testedPosition = vectorPositions[realPos];
  17930. for (var j = 0; j < realPos; ++j) {
  17931. var againstPosition = vectorPositions[j];
  17932. if (testedPosition.equals(againstPosition)) {
  17933. dupes[realPos] = j;
  17934. break;
  17935. }
  17936. }
  17937. }, function () {
  17938. for (var i = 0; i < indices.length; ++i) {
  17939. indices[i] = dupes[indices[i]] || indices[i];
  17940. }
  17941. //indices are now reordered
  17942. var originalSubMeshes = _this.subMeshes.slice(0);
  17943. _this.setIndices(indices);
  17944. _this.subMeshes = originalSubMeshes;
  17945. if (successCallback) {
  17946. successCallback(_this);
  17947. }
  17948. });
  17949. };
  17950. // Statics
  17951. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  17952. var mesh = new Mesh(parsedMesh.name, scene);
  17953. mesh.id = parsedMesh.id;
  17954. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17955. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17956. if (parsedMesh.rotationQuaternion) {
  17957. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17958. }
  17959. else if (parsedMesh.rotation) {
  17960. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17961. }
  17962. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17963. if (parsedMesh.localMatrix) {
  17964. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17965. }
  17966. else if (parsedMesh.pivotMatrix) {
  17967. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17968. }
  17969. mesh.setEnabled(parsedMesh.isEnabled);
  17970. mesh.isVisible = parsedMesh.isVisible;
  17971. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17972. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17973. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17974. if (parsedMesh.applyFog !== undefined) {
  17975. mesh.applyFog = parsedMesh.applyFog;
  17976. }
  17977. if (parsedMesh.pickable !== undefined) {
  17978. mesh.isPickable = parsedMesh.pickable;
  17979. }
  17980. if (parsedMesh.alphaIndex !== undefined) {
  17981. mesh.alphaIndex = parsedMesh.alphaIndex;
  17982. }
  17983. mesh.receiveShadows = parsedMesh.receiveShadows;
  17984. mesh.billboardMode = parsedMesh.billboardMode;
  17985. if (parsedMesh.visibility !== undefined) {
  17986. mesh.visibility = parsedMesh.visibility;
  17987. }
  17988. mesh.checkCollisions = parsedMesh.checkCollisions;
  17989. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17990. // freezeWorldMatrix
  17991. if (parsedMesh.freezeWorldMatrix) {
  17992. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  17993. }
  17994. // Parent
  17995. if (parsedMesh.parentId) {
  17996. mesh._waitingParentId = parsedMesh.parentId;
  17997. }
  17998. // Actions
  17999. if (parsedMesh.actions !== undefined) {
  18000. mesh._waitingActions = parsedMesh.actions;
  18001. }
  18002. // Geometry
  18003. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18004. if (parsedMesh.delayLoadingFile) {
  18005. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18006. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18007. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18008. if (parsedMesh._binaryInfo) {
  18009. mesh._binaryInfo = parsedMesh._binaryInfo;
  18010. }
  18011. mesh._delayInfo = [];
  18012. if (parsedMesh.hasUVs) {
  18013. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18014. }
  18015. if (parsedMesh.hasUVs2) {
  18016. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18017. }
  18018. if (parsedMesh.hasUVs3) {
  18019. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18020. }
  18021. if (parsedMesh.hasUVs4) {
  18022. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18023. }
  18024. if (parsedMesh.hasUVs5) {
  18025. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18026. }
  18027. if (parsedMesh.hasUVs6) {
  18028. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18029. }
  18030. if (parsedMesh.hasColors) {
  18031. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18032. }
  18033. if (parsedMesh.hasMatricesIndices) {
  18034. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18035. }
  18036. if (parsedMesh.hasMatricesWeights) {
  18037. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18038. }
  18039. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18040. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18041. mesh._checkDelayState();
  18042. }
  18043. }
  18044. else {
  18045. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18046. }
  18047. // Material
  18048. if (parsedMesh.materialId) {
  18049. mesh.setMaterialByID(parsedMesh.materialId);
  18050. }
  18051. else {
  18052. mesh.material = null;
  18053. }
  18054. // Skeleton
  18055. if (parsedMesh.skeletonId > -1) {
  18056. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18057. if (parsedMesh.numBoneInfluencers) {
  18058. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18059. }
  18060. }
  18061. // Animations
  18062. if (parsedMesh.animations) {
  18063. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18064. var parsedAnimation = parsedMesh.animations[animationIndex];
  18065. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18066. }
  18067. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18068. }
  18069. if (parsedMesh.autoAnimate) {
  18070. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18071. }
  18072. // Layer Mask
  18073. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18074. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18075. }
  18076. else {
  18077. mesh.layerMask = 0x0FFFFFFF;
  18078. }
  18079. //(Deprecated) physics
  18080. if (parsedMesh.physicsImpostor) {
  18081. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18082. mass: parsedMesh.physicsMass,
  18083. friction: parsedMesh.physicsFriction,
  18084. restitution: parsedMesh.physicsRestitution
  18085. }, scene);
  18086. }
  18087. // Instances
  18088. if (parsedMesh.instances) {
  18089. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18090. var parsedInstance = parsedMesh.instances[index];
  18091. var instance = mesh.createInstance(parsedInstance.name);
  18092. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18093. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18094. if (parsedInstance.rotationQuaternion) {
  18095. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18096. }
  18097. else if (parsedInstance.rotation) {
  18098. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18099. }
  18100. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18101. instance.checkCollisions = mesh.checkCollisions;
  18102. if (parsedMesh.animations) {
  18103. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18104. parsedAnimation = parsedMesh.animations[animationIndex];
  18105. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18106. }
  18107. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18108. }
  18109. }
  18110. }
  18111. return mesh;
  18112. };
  18113. /**
  18114. * Creates a ribbon mesh.
  18115. * Please consider using the same method from the `MeshBuilder` class instead.
  18116. * 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.
  18117. *
  18118. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18119. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18120. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18121. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18122. * 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.
  18123. * 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.
  18124. * 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
  18125. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18126. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18127. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18128. */
  18129. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18130. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18131. pathArray: pathArray,
  18132. closeArray: closeArray,
  18133. closePath: closePath,
  18134. offset: offset,
  18135. updatable: updatable,
  18136. sideOrientation: sideOrientation,
  18137. instance: instance
  18138. }, scene);
  18139. };
  18140. /**
  18141. * Creates a plane polygonal mesh. By default, this is a disc.
  18142. * Please consider using the same method from the `MeshBuilder` class instead.
  18143. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18144. * 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.
  18145. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18146. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18148. */
  18149. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18150. var options = {
  18151. radius: radius,
  18152. tessellation: tessellation,
  18153. sideOrientation: sideOrientation,
  18154. updatable: updatable
  18155. };
  18156. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18157. };
  18158. /**
  18159. * Creates a box mesh.
  18160. * Please consider using the same method from the `MeshBuilder` class instead.
  18161. * The parameter `size` sets the size (float) of each box side (default 1).
  18162. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18163. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18164. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18165. */
  18166. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18167. var options = {
  18168. size: size,
  18169. sideOrientation: sideOrientation,
  18170. updatable: updatable
  18171. };
  18172. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18173. };
  18174. /**
  18175. * Creates a sphere mesh.
  18176. * Please consider using the same method from the `MeshBuilder` class instead.
  18177. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18178. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18182. */
  18183. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18184. var options = {
  18185. segments: segments,
  18186. diameterX: diameter,
  18187. diameterY: diameter,
  18188. diameterZ: diameter,
  18189. sideOrientation: sideOrientation,
  18190. updatable: updatable
  18191. };
  18192. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18193. };
  18194. /**
  18195. * Creates a cylinder or a cone mesh.
  18196. * Please consider using the same method from the `MeshBuilder` class instead.
  18197. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18198. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18199. * 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.
  18200. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18201. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18202. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18203. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18205. */
  18206. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18207. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18208. if (scene !== undefined) {
  18209. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18210. updatable = scene;
  18211. }
  18212. scene = subdivisions;
  18213. subdivisions = 1;
  18214. }
  18215. var options = {
  18216. height: height,
  18217. diameterTop: diameterTop,
  18218. diameterBottom: diameterBottom,
  18219. tessellation: tessellation,
  18220. subdivisions: subdivisions,
  18221. sideOrientation: sideOrientation,
  18222. updatable: updatable
  18223. };
  18224. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18225. };
  18226. // Torus (Code from SharpDX.org)
  18227. /**
  18228. * Creates a torus mesh.
  18229. * Please consider using the same method from the `MeshBuilder` class instead.
  18230. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18231. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18232. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18236. */
  18237. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18238. var options = {
  18239. diameter: diameter,
  18240. thickness: thickness,
  18241. tessellation: tessellation,
  18242. sideOrientation: sideOrientation,
  18243. updatable: updatable
  18244. };
  18245. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18246. };
  18247. /**
  18248. * Creates a torus knot mesh.
  18249. * Please consider using the same method from the `MeshBuilder` class instead.
  18250. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18251. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18252. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18253. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18254. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18255. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18256. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18257. */
  18258. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18259. var options = {
  18260. radius: radius,
  18261. tube: tube,
  18262. radialSegments: radialSegments,
  18263. tubularSegments: tubularSegments,
  18264. p: p,
  18265. q: q,
  18266. sideOrientation: sideOrientation,
  18267. updatable: updatable
  18268. };
  18269. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18270. };
  18271. /**
  18272. * Creates a line mesh.
  18273. * Please consider using the same method from the `MeshBuilder` class instead.
  18274. * 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.
  18275. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18276. * The parameter `points` is an array successive Vector3.
  18277. * 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
  18278. * When updating an instance, remember that only point positions can change, not the number of points.
  18279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18280. */
  18281. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18282. var options = {
  18283. points: points,
  18284. updatable: updatable,
  18285. instance: instance
  18286. };
  18287. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18288. };
  18289. /**
  18290. * Creates a dashed line mesh.
  18291. * Please consider using the same method from the `MeshBuilder` class instead.
  18292. * 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.
  18293. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18294. * The parameter `points` is an array successive Vector3.
  18295. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18296. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18297. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18298. * 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
  18299. * When updating an instance, remember that only point positions can change, not the number of points.
  18300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18301. */
  18302. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18303. var options = {
  18304. points: points,
  18305. dashSize: dashSize,
  18306. gapSize: gapSize,
  18307. dashNb: dashNb,
  18308. updatable: updatable
  18309. };
  18310. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18311. };
  18312. /**
  18313. * Creates an extruded shape mesh.
  18314. * 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.
  18315. * Please consider using the same method from the `MeshBuilder` class instead.
  18316. *
  18317. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18318. * 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
  18319. * extruded along the Z axis.
  18320. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18321. * 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.
  18322. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18323. * 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
  18324. * 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
  18325. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18326. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18327. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18329. */
  18330. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18331. var options = {
  18332. shape: shape,
  18333. path: path,
  18334. scale: scale,
  18335. rotation: rotation,
  18336. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18337. sideOrientation: sideOrientation,
  18338. instance: instance,
  18339. updatable: updatable
  18340. };
  18341. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18342. };
  18343. /**
  18344. * Creates an custom extruded shape mesh.
  18345. * 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.
  18346. * Please consider using the same method from the `MeshBuilder` class instead.
  18347. *
  18348. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18349. * 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
  18350. * extruded along the Z axis.
  18351. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18352. * 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
  18353. * and the distance of this point from the begining of the path :
  18354. * ```rotationFunction = function(i, distance) {
  18355. * // do things
  18356. * return rotationValue; }```
  18357. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18358. * 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
  18359. * and the distance of this point from the begining of the path :
  18360. * ````scaleFunction = function(i, distance) {
  18361. * // do things
  18362. * return scaleValue;}```
  18363. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18364. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18365. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18366. * 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
  18367. * 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
  18368. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18370. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18372. */
  18373. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18374. var options = {
  18375. shape: shape,
  18376. path: path,
  18377. scaleFunction: scaleFunction,
  18378. rotationFunction: rotationFunction,
  18379. ribbonCloseArray: ribbonCloseArray,
  18380. ribbonClosePath: ribbonClosePath,
  18381. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18382. sideOrientation: sideOrientation,
  18383. instance: instance,
  18384. updatable: updatable
  18385. };
  18386. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18387. };
  18388. /**
  18389. * Creates lathe mesh.
  18390. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18391. * Please consider using the same method from the `MeshBuilder` class instead.
  18392. *
  18393. * 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
  18394. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18395. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18396. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18397. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18398. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18399. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18400. */
  18401. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18402. var options = {
  18403. shape: shape,
  18404. radius: radius,
  18405. tessellation: tessellation,
  18406. sideOrientation: sideOrientation,
  18407. updatable: updatable
  18408. };
  18409. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18410. };
  18411. /**
  18412. * Creates a plane mesh.
  18413. * Please consider using the same method from the `MeshBuilder` class instead.
  18414. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18415. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18416. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18418. */
  18419. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18420. var options = {
  18421. size: size,
  18422. width: size,
  18423. height: size,
  18424. sideOrientation: sideOrientation,
  18425. updatable: updatable
  18426. };
  18427. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18428. };
  18429. /**
  18430. * Creates a ground mesh.
  18431. * Please consider using the same method from the `MeshBuilder` class instead.
  18432. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18433. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18435. */
  18436. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18437. var options = {
  18438. width: width,
  18439. height: height,
  18440. subdivisions: subdivisions,
  18441. updatable: updatable
  18442. };
  18443. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18444. };
  18445. /**
  18446. * Creates a tiled ground mesh.
  18447. * Please consider using the same method from the `MeshBuilder` class instead.
  18448. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18449. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18450. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18451. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18452. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18453. * numbers of subdivisions on the ground width and height of each tile.
  18454. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18455. */
  18456. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18457. var options = {
  18458. xmin: xmin,
  18459. zmin: zmin,
  18460. xmax: xmax,
  18461. zmax: zmax,
  18462. subdivisions: subdivisions,
  18463. precision: precision,
  18464. updatable: updatable
  18465. };
  18466. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18467. };
  18468. /**
  18469. * Creates a ground mesh from a height map.
  18470. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18471. * Please consider using the same method from the `MeshBuilder` class instead.
  18472. * The parameter `url` sets the URL of the height map image resource.
  18473. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18474. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18475. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18476. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18477. * 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).
  18478. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18479. * return; }```
  18480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18481. */
  18482. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18483. var options = {
  18484. width: width,
  18485. height: height,
  18486. subdivisions: subdivisions,
  18487. minHeight: minHeight,
  18488. maxHeight: maxHeight,
  18489. updatable: updatable,
  18490. onReady: onReady
  18491. };
  18492. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18493. };
  18494. /**
  18495. * Creates a tube mesh.
  18496. * 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.
  18497. *
  18498. * Please consider using the same method from the `MeshBuilder` class instead.
  18499. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18500. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18501. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18502. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18503. * 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.
  18504. * It must return a radius value (positive float) :
  18505. * ```var radiusFunction = function(i, distance) {
  18506. * // do things
  18507. * return radius; }```
  18508. * 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
  18509. * 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
  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.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18515. var options = {
  18516. path: path,
  18517. radius: radius,
  18518. tessellation: tessellation,
  18519. radiusFunction: radiusFunction,
  18520. arc: 1,
  18521. cap: cap,
  18522. updatable: updatable,
  18523. sideOrientation: sideOrientation,
  18524. instance: instance
  18525. };
  18526. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18527. };
  18528. /**
  18529. * Creates a polyhedron mesh.
  18530. *
  18531. * Please consider using the same method from the `MeshBuilder` class instead.
  18532. * 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
  18533. * to choose the wanted type.
  18534. * The parameter `size` (positive float, default 1) sets the polygon size.
  18535. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18536. * 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`.
  18537. * 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
  18538. * 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)`).
  18539. * 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
  18540. * 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.
  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.CreatePolyhedron = function (name, options, scene) {
  18546. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18547. };
  18548. /**
  18549. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18550. * Please consider using the same method from the `MeshBuilder` class instead.
  18551. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18552. * 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`).
  18553. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18554. * 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.
  18555. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18556. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18558. */
  18559. Mesh.CreateIcoSphere = function (name, options, scene) {
  18560. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18561. };
  18562. /**
  18563. * Creates a decal mesh.
  18564. * Please consider using the same method from the `MeshBuilder` class instead.
  18565. * 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.
  18566. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18567. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18568. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18569. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18570. */
  18571. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18572. var options = {
  18573. position: position,
  18574. normal: normal,
  18575. size: size,
  18576. angle: angle
  18577. };
  18578. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18579. };
  18580. // Skeletons
  18581. /**
  18582. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18583. */
  18584. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18585. var source;
  18586. if (!this._sourcePositions) {
  18587. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18588. this._sourcePositions = new Float32Array(source);
  18589. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18590. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18591. }
  18592. }
  18593. return this._sourcePositions;
  18594. };
  18595. /**
  18596. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18597. */
  18598. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18599. var source;
  18600. if (!this._sourceNormals) {
  18601. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18602. this._sourceNormals = new Float32Array(source);
  18603. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18604. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18605. }
  18606. }
  18607. return this._sourceNormals;
  18608. };
  18609. /**
  18610. * Update the vertex buffers by applying transformation from the bones
  18611. * @param {skeleton} skeleton to apply
  18612. */
  18613. Mesh.prototype.applySkeleton = function (skeleton) {
  18614. if (!this.geometry) {
  18615. return;
  18616. }
  18617. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18618. return;
  18619. }
  18620. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18621. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18622. return this;
  18623. }
  18624. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18625. return this;
  18626. }
  18627. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18628. return this;
  18629. }
  18630. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18631. return this;
  18632. }
  18633. if (!this._sourcePositions) {
  18634. this.setPositionsForCPUSkinning();
  18635. }
  18636. if (!this._sourceNormals) {
  18637. this.setNormalsForCPUSkinning();
  18638. }
  18639. // positionsData checks for not being Float32Array will only pass at most once
  18640. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18641. if (!(positionsData instanceof Float32Array)) {
  18642. positionsData = new Float32Array(positionsData);
  18643. }
  18644. // normalsData checks for not being Float32Array will only pass at most once
  18645. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18646. if (!(normalsData instanceof Float32Array)) {
  18647. normalsData = new Float32Array(normalsData);
  18648. }
  18649. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18650. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18651. var needExtras = this.numBoneInfluencers > 4;
  18652. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18653. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18654. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18655. var tempVector3 = BABYLON.Vector3.Zero();
  18656. var finalMatrix = new BABYLON.Matrix();
  18657. var tempMatrix = new BABYLON.Matrix();
  18658. var matWeightIdx = 0;
  18659. var inf;
  18660. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18661. var weight;
  18662. for (inf = 0; inf < 4; inf++) {
  18663. weight = matricesWeightsData[matWeightIdx + inf];
  18664. if (weight > 0) {
  18665. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18666. finalMatrix.addToSelf(tempMatrix);
  18667. }
  18668. else
  18669. break;
  18670. }
  18671. if (needExtras) {
  18672. for (inf = 0; inf < 4; inf++) {
  18673. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18674. if (weight > 0) {
  18675. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18676. finalMatrix.addToSelf(tempMatrix);
  18677. }
  18678. else
  18679. break;
  18680. }
  18681. }
  18682. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18683. tempVector3.toArray(positionsData, index);
  18684. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18685. tempVector3.toArray(normalsData, index);
  18686. finalMatrix.reset();
  18687. }
  18688. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18689. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18690. return this;
  18691. };
  18692. // Tools
  18693. Mesh.MinMax = function (meshes) {
  18694. var minVector = null;
  18695. var maxVector = null;
  18696. for (var i in meshes) {
  18697. var mesh = meshes[i];
  18698. var boundingBox = mesh.getBoundingInfo().boundingBox;
  18699. if (!minVector) {
  18700. minVector = boundingBox.minimumWorld;
  18701. maxVector = boundingBox.maximumWorld;
  18702. continue;
  18703. }
  18704. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  18705. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  18706. }
  18707. return {
  18708. min: minVector,
  18709. max: maxVector
  18710. };
  18711. };
  18712. Mesh.Center = function (meshesOrMinMaxVector) {
  18713. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  18714. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  18715. };
  18716. /**
  18717. * Merge the array of meshes into a single mesh for performance reasons.
  18718. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  18719. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  18720. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  18721. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  18722. */
  18723. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  18724. if (disposeSource === void 0) { disposeSource = true; }
  18725. var index;
  18726. if (!allow32BitsIndices) {
  18727. var totalVertices = 0;
  18728. // Counting vertices
  18729. for (index = 0; index < meshes.length; index++) {
  18730. if (meshes[index]) {
  18731. totalVertices += meshes[index].getTotalVertices();
  18732. if (totalVertices > 65536) {
  18733. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  18734. return null;
  18735. }
  18736. }
  18737. }
  18738. }
  18739. // Merge
  18740. var vertexData;
  18741. var otherVertexData;
  18742. var source;
  18743. for (index = 0; index < meshes.length; index++) {
  18744. if (meshes[index]) {
  18745. meshes[index].computeWorldMatrix(true);
  18746. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  18747. otherVertexData.transform(meshes[index].getWorldMatrix());
  18748. if (vertexData) {
  18749. vertexData.merge(otherVertexData);
  18750. }
  18751. else {
  18752. vertexData = otherVertexData;
  18753. source = meshes[index];
  18754. }
  18755. }
  18756. }
  18757. if (!meshSubclass) {
  18758. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  18759. }
  18760. vertexData.applyToMesh(meshSubclass);
  18761. // Setting properties
  18762. meshSubclass.material = source.material;
  18763. meshSubclass.checkCollisions = source.checkCollisions;
  18764. // Cleaning
  18765. if (disposeSource) {
  18766. for (index = 0; index < meshes.length; index++) {
  18767. if (meshes[index]) {
  18768. meshes[index].dispose();
  18769. }
  18770. }
  18771. }
  18772. return meshSubclass;
  18773. };
  18774. // Consts
  18775. Mesh._FRONTSIDE = 0;
  18776. Mesh._BACKSIDE = 1;
  18777. Mesh._DOUBLESIDE = 2;
  18778. Mesh._DEFAULTSIDE = 0;
  18779. Mesh._NO_CAP = 0;
  18780. Mesh._CAP_START = 1;
  18781. Mesh._CAP_END = 2;
  18782. Mesh._CAP_ALL = 3;
  18783. return Mesh;
  18784. }(BABYLON.AbstractMesh));
  18785. BABYLON.Mesh = Mesh;
  18786. })(BABYLON || (BABYLON = {}));
  18787. var BABYLON;
  18788. (function (BABYLON) {
  18789. var SubMesh = (function () {
  18790. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  18791. if (createBoundingBox === void 0) { createBoundingBox = true; }
  18792. this.materialIndex = materialIndex;
  18793. this.verticesStart = verticesStart;
  18794. this.verticesCount = verticesCount;
  18795. this.indexStart = indexStart;
  18796. this.indexCount = indexCount;
  18797. this._renderId = 0;
  18798. this._mesh = mesh;
  18799. this._renderingMesh = renderingMesh || mesh;
  18800. mesh.subMeshes.push(this);
  18801. this._trianglePlanes = [];
  18802. this._id = mesh.subMeshes.length - 1;
  18803. if (createBoundingBox) {
  18804. this.refreshBoundingInfo();
  18805. mesh.computeWorldMatrix(true);
  18806. }
  18807. }
  18808. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  18809. get: function () {
  18810. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  18811. },
  18812. enumerable: true,
  18813. configurable: true
  18814. });
  18815. SubMesh.prototype.getBoundingInfo = function () {
  18816. if (this.IsGlobal) {
  18817. return this._mesh.getBoundingInfo();
  18818. }
  18819. return this._boundingInfo;
  18820. };
  18821. SubMesh.prototype.getMesh = function () {
  18822. return this._mesh;
  18823. };
  18824. SubMesh.prototype.getRenderingMesh = function () {
  18825. return this._renderingMesh;
  18826. };
  18827. SubMesh.prototype.getMaterial = function () {
  18828. var rootMaterial = this._renderingMesh.material;
  18829. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  18830. var multiMaterial = rootMaterial;
  18831. return multiMaterial.getSubMaterial(this.materialIndex);
  18832. }
  18833. if (!rootMaterial) {
  18834. return this._mesh.getScene().defaultMaterial;
  18835. }
  18836. return rootMaterial;
  18837. };
  18838. // Methods
  18839. SubMesh.prototype.refreshBoundingInfo = function () {
  18840. this._lastColliderWorldVertices = null;
  18841. if (this.IsGlobal) {
  18842. return;
  18843. }
  18844. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18845. if (!data) {
  18846. this._boundingInfo = this._mesh._boundingInfo;
  18847. return;
  18848. }
  18849. var indices = this._renderingMesh.getIndices();
  18850. var extend;
  18851. //is this the only submesh?
  18852. if (this.indexStart === 0 && this.indexCount === indices.length) {
  18853. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  18854. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  18855. }
  18856. else {
  18857. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  18858. }
  18859. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18860. };
  18861. SubMesh.prototype._checkCollision = function (collider) {
  18862. return this.getBoundingInfo()._checkCollision(collider);
  18863. };
  18864. SubMesh.prototype.updateBoundingInfo = function (world) {
  18865. if (!this.getBoundingInfo()) {
  18866. this.refreshBoundingInfo();
  18867. }
  18868. this.getBoundingInfo().update(world);
  18869. };
  18870. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  18871. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  18872. };
  18873. SubMesh.prototype.render = function (enableAlphaMode) {
  18874. this._renderingMesh.render(this, enableAlphaMode);
  18875. };
  18876. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  18877. if (!this._linesIndexBuffer) {
  18878. var linesIndices = [];
  18879. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  18880. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  18881. }
  18882. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  18883. this.linesIndexCount = linesIndices.length;
  18884. }
  18885. return this._linesIndexBuffer;
  18886. };
  18887. SubMesh.prototype.canIntersects = function (ray) {
  18888. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  18889. };
  18890. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  18891. var intersectInfo = null;
  18892. // LineMesh first as it's also a Mesh...
  18893. if (this._mesh instanceof BABYLON.LinesMesh) {
  18894. var lineMesh = this._mesh;
  18895. // Line test
  18896. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  18897. var p0 = positions[indices[index]];
  18898. var p1 = positions[indices[index + 1]];
  18899. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  18900. if (length < 0) {
  18901. continue;
  18902. }
  18903. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  18904. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  18905. if (fastCheck) {
  18906. break;
  18907. }
  18908. }
  18909. }
  18910. }
  18911. else {
  18912. // Triangles test
  18913. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  18914. var p0 = positions[indices[index]];
  18915. var p1 = positions[indices[index + 1]];
  18916. var p2 = positions[indices[index + 2]];
  18917. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  18918. if (currentIntersectInfo) {
  18919. if (currentIntersectInfo.distance < 0) {
  18920. continue;
  18921. }
  18922. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18923. intersectInfo = currentIntersectInfo;
  18924. intersectInfo.faceId = index / 3;
  18925. if (fastCheck) {
  18926. break;
  18927. }
  18928. }
  18929. }
  18930. }
  18931. }
  18932. return intersectInfo;
  18933. };
  18934. // Clone
  18935. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  18936. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  18937. if (!this.IsGlobal) {
  18938. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  18939. }
  18940. return result;
  18941. };
  18942. // Dispose
  18943. SubMesh.prototype.dispose = function () {
  18944. if (this._linesIndexBuffer) {
  18945. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  18946. this._linesIndexBuffer = null;
  18947. }
  18948. // Remove from mesh
  18949. var index = this._mesh.subMeshes.indexOf(this);
  18950. this._mesh.subMeshes.splice(index, 1);
  18951. };
  18952. // Statics
  18953. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  18954. var minVertexIndex = Number.MAX_VALUE;
  18955. var maxVertexIndex = -Number.MAX_VALUE;
  18956. renderingMesh = renderingMesh || mesh;
  18957. var indices = renderingMesh.getIndices();
  18958. for (var index = startIndex; index < startIndex + indexCount; index++) {
  18959. var vertexIndex = indices[index];
  18960. if (vertexIndex < minVertexIndex)
  18961. minVertexIndex = vertexIndex;
  18962. if (vertexIndex > maxVertexIndex)
  18963. maxVertexIndex = vertexIndex;
  18964. }
  18965. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  18966. };
  18967. return SubMesh;
  18968. }());
  18969. BABYLON.SubMesh = SubMesh;
  18970. })(BABYLON || (BABYLON = {}));
  18971. var BABYLON;
  18972. (function (BABYLON) {
  18973. var MeshBuilder = (function () {
  18974. function MeshBuilder() {
  18975. }
  18976. /**
  18977. * Creates a box mesh.
  18978. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  18979. * The parameter `size` sets the size (float) of each box side (default 1).
  18980. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  18981. * 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).
  18982. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  18983. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18984. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18986. */
  18987. MeshBuilder.CreateBox = function (name, options, scene) {
  18988. var box = new BABYLON.Mesh(name, scene);
  18989. var vertexData = BABYLON.VertexData.CreateBox(options);
  18990. vertexData.applyToMesh(box, options.updatable);
  18991. return box;
  18992. };
  18993. /**
  18994. * Creates a sphere mesh.
  18995. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  18996. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18997. * 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`).
  18998. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18999. * 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
  19000. * 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).
  19001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19002. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19004. */
  19005. MeshBuilder.CreateSphere = function (name, options, scene) {
  19006. var sphere = new BABYLON.Mesh(name, scene);
  19007. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19008. vertexData.applyToMesh(sphere, options.updatable);
  19009. return sphere;
  19010. };
  19011. /**
  19012. * Creates a plane polygonal mesh. By default, this is a disc.
  19013. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19014. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19015. * 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.
  19016. * 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
  19017. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19018. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19019. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19020. */
  19021. MeshBuilder.CreateDisc = function (name, options, scene) {
  19022. var disc = new BABYLON.Mesh(name, scene);
  19023. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19024. vertexData.applyToMesh(disc, options.updatable);
  19025. return disc;
  19026. };
  19027. /**
  19028. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19029. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19030. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19031. * 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`).
  19032. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19033. * 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.
  19034. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19035. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19037. */
  19038. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19039. var sphere = new BABYLON.Mesh(name, scene);
  19040. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19041. vertexData.applyToMesh(sphere, options.updatable);
  19042. return sphere;
  19043. };
  19044. ;
  19045. /**
  19046. * Creates a ribbon mesh.
  19047. * 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.
  19048. *
  19049. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19050. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19051. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19052. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19053. * 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.
  19054. * 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.
  19055. * 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
  19056. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19057. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19059. */
  19060. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19061. var pathArray = options.pathArray;
  19062. var closeArray = options.closeArray;
  19063. var closePath = options.closePath;
  19064. var offset = options.offset;
  19065. var sideOrientation = options.sideOrientation;
  19066. var instance = options.instance;
  19067. var updatable = options.updatable;
  19068. if (instance) {
  19069. // positionFunction : ribbon case
  19070. // only pathArray and sideOrientation parameters are taken into account for positions update
  19071. var positionFunction = function (positions) {
  19072. var minlg = pathArray[0].length;
  19073. var i = 0;
  19074. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19075. for (var si = 1; si <= ns; si++) {
  19076. for (var p = 0; p < pathArray.length; p++) {
  19077. var path = pathArray[p];
  19078. var l = path.length;
  19079. minlg = (minlg < l) ? minlg : l;
  19080. var j = 0;
  19081. while (j < minlg) {
  19082. positions[i] = path[j].x;
  19083. positions[i + 1] = path[j].y;
  19084. positions[i + 2] = path[j].z;
  19085. j++;
  19086. i += 3;
  19087. }
  19088. if (instance._closePath) {
  19089. positions[i] = path[0].x;
  19090. positions[i + 1] = path[0].y;
  19091. positions[i + 2] = path[0].z;
  19092. i += 3;
  19093. }
  19094. }
  19095. }
  19096. };
  19097. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19098. positionFunction(positions);
  19099. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19100. if (!(instance.areNormalsFrozen)) {
  19101. var indices = instance.getIndices();
  19102. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19103. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19104. if (instance._closePath) {
  19105. var indexFirst = 0;
  19106. var indexLast = 0;
  19107. for (var p = 0; p < pathArray.length; p++) {
  19108. indexFirst = instance._idx[p] * 3;
  19109. if (p + 1 < pathArray.length) {
  19110. indexLast = (instance._idx[p + 1] - 1) * 3;
  19111. }
  19112. else {
  19113. indexLast = normals.length - 3;
  19114. }
  19115. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19116. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19117. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19118. normals[indexLast] = normals[indexFirst];
  19119. normals[indexLast + 1] = normals[indexFirst + 1];
  19120. normals[indexLast + 2] = normals[indexFirst + 2];
  19121. }
  19122. }
  19123. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19124. }
  19125. return instance;
  19126. }
  19127. else {
  19128. var ribbon = new BABYLON.Mesh(name, scene);
  19129. ribbon.sideOrientation = sideOrientation;
  19130. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19131. if (closePath) {
  19132. ribbon._idx = vertexData._idx;
  19133. }
  19134. ribbon._closePath = closePath;
  19135. ribbon._closeArray = closeArray;
  19136. vertexData.applyToMesh(ribbon, updatable);
  19137. return ribbon;
  19138. }
  19139. };
  19140. /**
  19141. * Creates a cylinder or a cone mesh.
  19142. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19143. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19144. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19145. * 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.
  19146. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19147. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19148. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19149. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19150. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19151. * 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).
  19152. * 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
  19153. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19154. * 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
  19155. * 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.
  19156. * If `enclose` is false, a ring surface is one element.
  19157. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19158. * 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
  19159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19162. */
  19163. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19164. var cylinder = new BABYLON.Mesh(name, scene);
  19165. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19166. vertexData.applyToMesh(cylinder, options.updatable);
  19167. return cylinder;
  19168. };
  19169. /**
  19170. * Creates a torus mesh.
  19171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19172. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19173. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19174. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19176. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19178. */
  19179. MeshBuilder.CreateTorus = function (name, options, scene) {
  19180. var torus = new BABYLON.Mesh(name, scene);
  19181. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19182. vertexData.applyToMesh(torus, options.updatable);
  19183. return torus;
  19184. };
  19185. /**
  19186. * Creates a torus knot mesh.
  19187. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19188. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19189. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19190. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19191. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19192. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19193. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19194. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19195. */
  19196. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19197. var torusKnot = new BABYLON.Mesh(name, scene);
  19198. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19199. vertexData.applyToMesh(torusKnot, options.updatable);
  19200. return torusKnot;
  19201. };
  19202. /**
  19203. * Creates a line system mesh.
  19204. * A line system is a pool of many lines gathered in a single mesh.
  19205. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19206. * 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.
  19207. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19208. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19209. * 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
  19210. * 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
  19211. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19213. */
  19214. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19215. var instance = options.instance;
  19216. var lines = options.lines;
  19217. if (instance) {
  19218. var positionFunction = function (positions) {
  19219. var i = 0;
  19220. for (var l = 0; l < lines.length; l++) {
  19221. var points = lines[l];
  19222. for (var p = 0; p < points.length; p++) {
  19223. positions[i] = points[p].x;
  19224. positions[i + 1] = points[p].y;
  19225. positions[i + 2] = points[p].z;
  19226. i += 3;
  19227. }
  19228. }
  19229. };
  19230. instance.updateMeshPositions(positionFunction, false);
  19231. return instance;
  19232. }
  19233. // line system creation
  19234. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19235. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19236. vertexData.applyToMesh(lineSystem, options.updatable);
  19237. return lineSystem;
  19238. };
  19239. /**
  19240. * Creates a line mesh.
  19241. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19242. * 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.
  19243. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19244. * The parameter `points` is an array successive Vector3.
  19245. * 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
  19246. * When updating an instance, remember that only point positions can change, not the number of points.
  19247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19248. */
  19249. MeshBuilder.CreateLines = function (name, options, scene) {
  19250. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19251. return lines;
  19252. };
  19253. /**
  19254. * Creates a dashed line mesh.
  19255. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19256. * 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.
  19257. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19258. * The parameter `points` is an array successive Vector3.
  19259. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19260. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19261. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19262. * 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
  19263. * When updating an instance, remember that only point positions can change, not the number of points.
  19264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19265. */
  19266. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19267. var points = options.points;
  19268. var instance = options.instance;
  19269. var gapSize = options.gapSize;
  19270. var dashNb = options.dashNb;
  19271. var dashSize = options.dashSize;
  19272. if (instance) {
  19273. var positionFunction = function (positions) {
  19274. var curvect = BABYLON.Vector3.Zero();
  19275. var nbSeg = positions.length / 6;
  19276. var lg = 0;
  19277. var nb = 0;
  19278. var shft = 0;
  19279. var dashshft = 0;
  19280. var curshft = 0;
  19281. var p = 0;
  19282. var i = 0;
  19283. var j = 0;
  19284. for (i = 0; i < points.length - 1; i++) {
  19285. points[i + 1].subtractToRef(points[i], curvect);
  19286. lg += curvect.length();
  19287. }
  19288. shft = lg / nbSeg;
  19289. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19290. for (i = 0; i < points.length - 1; i++) {
  19291. points[i + 1].subtractToRef(points[i], curvect);
  19292. nb = Math.floor(curvect.length() / shft);
  19293. curvect.normalize();
  19294. j = 0;
  19295. while (j < nb && p < positions.length) {
  19296. curshft = shft * j;
  19297. positions[p] = points[i].x + curshft * curvect.x;
  19298. positions[p + 1] = points[i].y + curshft * curvect.y;
  19299. positions[p + 2] = points[i].z + curshft * curvect.z;
  19300. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19301. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19302. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19303. p += 6;
  19304. j++;
  19305. }
  19306. }
  19307. while (p < positions.length) {
  19308. positions[p] = points[i].x;
  19309. positions[p + 1] = points[i].y;
  19310. positions[p + 2] = points[i].z;
  19311. p += 3;
  19312. }
  19313. };
  19314. instance.updateMeshPositions(positionFunction, false);
  19315. return instance;
  19316. }
  19317. // dashed lines creation
  19318. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19319. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19320. vertexData.applyToMesh(dashedLines, options.updatable);
  19321. dashedLines.dashSize = dashSize;
  19322. dashedLines.gapSize = gapSize;
  19323. return dashedLines;
  19324. };
  19325. /**
  19326. * Creates an extruded shape mesh.
  19327. * 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.
  19328. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19329. *
  19330. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19331. * 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
  19332. * extruded along the Z axis.
  19333. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19334. * 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.
  19335. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19336. * 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
  19337. * 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
  19338. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19340. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19342. */
  19343. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19344. var path = options.path;
  19345. var shape = options.shape;
  19346. var scale = options.scale || 1;
  19347. var rotation = options.rotation || 0;
  19348. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19349. var updatable = options.updatable;
  19350. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19351. var instance = options.instance;
  19352. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19353. };
  19354. /**
  19355. * Creates an custom extruded shape mesh.
  19356. * 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.
  19357. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19358. *
  19359. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19360. * 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
  19361. * extruded along the Z axis.
  19362. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19363. * 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
  19364. * and the distance of this point from the begining of the path :
  19365. * ```rotationFunction = function(i, distance) {
  19366. * // do things
  19367. * return rotationValue; }```
  19368. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19369. * 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
  19370. * and the distance of this point from the begining of the path :
  19371. * ````scaleFunction = function(i, distance) {
  19372. * // do things
  19373. * return scaleValue;}```
  19374. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19375. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19376. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19377. * 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
  19378. * 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
  19379. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19380. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19381. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19382. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19383. */
  19384. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19385. var path = options.path;
  19386. var shape = options.shape;
  19387. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19388. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19389. var ribbonCloseArray = options.ribbonCloseArray || false;
  19390. var ribbonClosePath = options.ribbonClosePath || false;
  19391. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19392. var updatable = options.updatable;
  19393. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19394. var instance = options.instance;
  19395. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19396. };
  19397. /**
  19398. * Creates lathe mesh.
  19399. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19400. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19401. *
  19402. * 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
  19403. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19404. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19405. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19406. * 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.
  19407. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19408. * 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
  19409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19412. */
  19413. MeshBuilder.CreateLathe = function (name, options, scene) {
  19414. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19415. var closed = (options.closed === undefined) ? true : options.closed;
  19416. var shape = options.shape;
  19417. var radius = options.radius || 1;
  19418. var tessellation = options.tessellation || 64;
  19419. var updatable = options.updatable;
  19420. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19421. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19422. var pi2 = Math.PI * 2;
  19423. var paths = new Array();
  19424. var i = 0;
  19425. var p = 0;
  19426. var step = pi2 / tessellation * arc;
  19427. var rotated;
  19428. var path = new Array();
  19429. ;
  19430. for (i = 0; i <= tessellation; i++) {
  19431. var path = [];
  19432. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19433. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19434. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19435. }
  19436. for (p = 0; p < shape.length; p++) {
  19437. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19438. path.push(rotated);
  19439. }
  19440. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19441. 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));
  19442. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19443. }
  19444. paths.push(path);
  19445. }
  19446. // lathe ribbon
  19447. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19448. return lathe;
  19449. };
  19450. /**
  19451. * Creates a plane mesh.
  19452. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19453. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19454. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19455. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19456. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19457. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19459. */
  19460. MeshBuilder.CreatePlane = function (name, options, scene) {
  19461. var plane = new BABYLON.Mesh(name, scene);
  19462. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19463. vertexData.applyToMesh(plane, options.updatable);
  19464. if (options.sourcePlane) {
  19465. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19466. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19467. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19468. plane.rotate(vectorProduct, product);
  19469. }
  19470. return plane;
  19471. };
  19472. /**
  19473. * Creates a ground mesh.
  19474. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19475. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19476. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19478. */
  19479. MeshBuilder.CreateGround = function (name, options, scene) {
  19480. var ground = new BABYLON.GroundMesh(name, scene);
  19481. ground._setReady(false);
  19482. ground._subdivisions = options.subdivisions || 1;
  19483. ground._width = options.width || 1;
  19484. ground._height = options.height || 1;
  19485. ground._maxX = ground._width / 2;
  19486. ground._maxZ = ground._height / 2;
  19487. ground._minX = -ground._maxX;
  19488. ground._minZ = -ground._maxZ;
  19489. var vertexData = BABYLON.VertexData.CreateGround(options);
  19490. vertexData.applyToMesh(ground, options.updatable);
  19491. ground._setReady(true);
  19492. return ground;
  19493. };
  19494. /**
  19495. * Creates a tiled ground mesh.
  19496. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19497. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19498. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19499. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19500. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19501. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19502. * numbers of subdivisions on the ground width and height of each tile.
  19503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19504. */
  19505. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19506. var tiledGround = new BABYLON.Mesh(name, scene);
  19507. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19508. vertexData.applyToMesh(tiledGround, options.updatable);
  19509. return tiledGround;
  19510. };
  19511. /**
  19512. * Creates a ground mesh from a height map.
  19513. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19514. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19515. * The parameter `url` sets the URL of the height map image resource.
  19516. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19517. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19518. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19519. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19520. * 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).
  19521. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19522. * return; }```
  19523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19524. */
  19525. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19526. var width = options.width || 10;
  19527. var height = options.height || 10;
  19528. var subdivisions = options.subdivisions || 1;
  19529. var minHeight = options.minHeight;
  19530. var maxHeight = options.maxHeight || 10;
  19531. var updatable = options.updatable;
  19532. var onReady = options.onReady;
  19533. var ground = new BABYLON.GroundMesh(name, scene);
  19534. ground._subdivisions = subdivisions;
  19535. ground._width = width;
  19536. ground._height = height;
  19537. ground._maxX = ground._width / 2;
  19538. ground._maxZ = ground._height / 2;
  19539. ground._minX = -ground._maxX;
  19540. ground._minZ = -ground._maxZ;
  19541. ground._setReady(false);
  19542. var onload = function (img) {
  19543. // Getting height map data
  19544. var canvas = document.createElement("canvas");
  19545. var context = canvas.getContext("2d");
  19546. var bufferWidth = img.width;
  19547. var bufferHeight = img.height;
  19548. canvas.width = bufferWidth;
  19549. canvas.height = bufferHeight;
  19550. context.drawImage(img, 0, 0);
  19551. // Create VertexData from map data
  19552. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19553. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19554. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19555. width: width, height: height,
  19556. subdivisions: subdivisions,
  19557. minHeight: minHeight, maxHeight: maxHeight,
  19558. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19559. });
  19560. vertexData.applyToMesh(ground, updatable);
  19561. ground._setReady(true);
  19562. //execute ready callback, if set
  19563. if (onReady) {
  19564. onReady(ground);
  19565. }
  19566. };
  19567. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19568. return ground;
  19569. };
  19570. /**
  19571. * Creates a tube mesh.
  19572. * 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.
  19573. *
  19574. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19575. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19576. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19577. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19578. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19579. * 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.
  19580. * It must return a radius value (positive float) :
  19581. * ```var radiusFunction = function(i, distance) {
  19582. * // do things
  19583. * return radius; }```
  19584. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19585. * 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
  19586. * 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
  19587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19590. */
  19591. MeshBuilder.CreateTube = function (name, options, scene) {
  19592. var path = options.path;
  19593. var radius = options.radius || 1;
  19594. var tessellation = options.tessellation || 64;
  19595. var radiusFunction = options.radiusFunction;
  19596. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19597. var updatable = options.updatable;
  19598. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19599. var instance = options.instance;
  19600. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19601. // tube geometry
  19602. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19603. var tangents = path3D.getTangents();
  19604. var normals = path3D.getNormals();
  19605. var distances = path3D.getDistances();
  19606. var pi2 = Math.PI * 2;
  19607. var step = pi2 / tessellation * arc;
  19608. var returnRadius = function () { return radius; };
  19609. var radiusFunctionFinal = radiusFunction || returnRadius;
  19610. var circlePath;
  19611. var rad;
  19612. var normal;
  19613. var rotated;
  19614. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19615. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19616. for (var i = 0; i < path.length; i++) {
  19617. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19618. circlePath = Array(); // current circle array
  19619. normal = normals[i]; // current normal
  19620. for (var t = 0; t < tessellation; t++) {
  19621. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19622. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19623. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19624. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19625. circlePath[t] = rotated;
  19626. }
  19627. circlePaths[index] = circlePath;
  19628. index++;
  19629. }
  19630. // cap
  19631. var capPath = function (nbPoints, pathIndex) {
  19632. var pointCap = Array();
  19633. for (var i = 0; i < nbPoints; i++) {
  19634. pointCap.push(path[pathIndex]);
  19635. }
  19636. return pointCap;
  19637. };
  19638. switch (cap) {
  19639. case BABYLON.Mesh.NO_CAP:
  19640. break;
  19641. case BABYLON.Mesh.CAP_START:
  19642. circlePaths[0] = capPath(tessellation, 0);
  19643. circlePaths[1] = circlePaths[2].slice(0);
  19644. break;
  19645. case BABYLON.Mesh.CAP_END:
  19646. circlePaths[index] = circlePaths[index - 1].slice(0);
  19647. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19648. break;
  19649. case BABYLON.Mesh.CAP_ALL:
  19650. circlePaths[0] = capPath(tessellation, 0);
  19651. circlePaths[1] = circlePaths[2].slice(0);
  19652. circlePaths[index] = circlePaths[index - 1].slice(0);
  19653. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19654. break;
  19655. default:
  19656. break;
  19657. }
  19658. return circlePaths;
  19659. };
  19660. var path3D;
  19661. var pathArray;
  19662. if (instance) {
  19663. var arc = options.arc || instance.arc;
  19664. path3D = (instance.path3D).update(path);
  19665. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19666. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19667. instance.path3D = path3D;
  19668. instance.pathArray = pathArray;
  19669. instance.arc = arc;
  19670. return instance;
  19671. }
  19672. // tube creation
  19673. path3D = new BABYLON.Path3D(path);
  19674. var newPathArray = new Array();
  19675. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19676. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19677. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19678. tube.pathArray = pathArray;
  19679. tube.path3D = path3D;
  19680. tube.tessellation = tessellation;
  19681. tube.cap = cap;
  19682. tube.arc = options.arc;
  19683. return tube;
  19684. };
  19685. /**
  19686. * Creates a polyhedron mesh.
  19687. *
  19688. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  19689. * 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
  19690. * to choose the wanted type.
  19691. * The parameter `size` (positive float, default 1) sets the polygon size.
  19692. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19693. * 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`.
  19694. * 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
  19695. * 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)`).
  19696. * 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
  19697. * 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.
  19698. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19699. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19701. */
  19702. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  19703. var polyhedron = new BABYLON.Mesh(name, scene);
  19704. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  19705. vertexData.applyToMesh(polyhedron, options.updatable);
  19706. return polyhedron;
  19707. };
  19708. /**
  19709. * Creates a decal mesh.
  19710. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  19711. * 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.
  19712. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19713. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19714. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19715. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19716. */
  19717. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  19718. var indices = sourceMesh.getIndices();
  19719. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19720. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19721. var position = options.position || BABYLON.Vector3.Zero();
  19722. var normal = options.normal || BABYLON.Vector3.Up();
  19723. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  19724. var angle = options.angle || 0;
  19725. // Getting correct rotation
  19726. if (!normal) {
  19727. var target = new BABYLON.Vector3(0, 0, 1);
  19728. var camera = sourceMesh.getScene().activeCamera;
  19729. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  19730. normal = camera.globalPosition.subtract(cameraWorldTarget);
  19731. }
  19732. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  19733. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  19734. var pitch = Math.atan2(normal.y, len);
  19735. // Matrix
  19736. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  19737. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  19738. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  19739. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  19740. var vertexData = new BABYLON.VertexData();
  19741. vertexData.indices = [];
  19742. vertexData.positions = [];
  19743. vertexData.normals = [];
  19744. vertexData.uvs = [];
  19745. var currentVertexDataIndex = 0;
  19746. var extractDecalVector3 = function (indexId) {
  19747. var vertexId = indices[indexId];
  19748. var result = new BABYLON.PositionNormalVertex();
  19749. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  19750. // Send vector to decal local world
  19751. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  19752. // Get normal
  19753. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  19754. return result;
  19755. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  19756. var clip = function (vertices, axis) {
  19757. if (vertices.length === 0) {
  19758. return vertices;
  19759. }
  19760. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  19761. var clipVertices = function (v0, v1) {
  19762. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  19763. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  19764. };
  19765. var result = new Array();
  19766. for (var index = 0; index < vertices.length; index += 3) {
  19767. var v1Out;
  19768. var v2Out;
  19769. var v3Out;
  19770. var total = 0;
  19771. var nV1, nV2, nV3, nV4;
  19772. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  19773. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  19774. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  19775. v1Out = d1 > 0;
  19776. v2Out = d2 > 0;
  19777. v3Out = d3 > 0;
  19778. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  19779. switch (total) {
  19780. case 0:
  19781. result.push(vertices[index]);
  19782. result.push(vertices[index + 1]);
  19783. result.push(vertices[index + 2]);
  19784. break;
  19785. case 1:
  19786. if (v1Out) {
  19787. nV1 = vertices[index + 1];
  19788. nV2 = vertices[index + 2];
  19789. nV3 = clipVertices(vertices[index], nV1);
  19790. nV4 = clipVertices(vertices[index], nV2);
  19791. }
  19792. if (v2Out) {
  19793. nV1 = vertices[index];
  19794. nV2 = vertices[index + 2];
  19795. nV3 = clipVertices(vertices[index + 1], nV1);
  19796. nV4 = clipVertices(vertices[index + 1], nV2);
  19797. result.push(nV3);
  19798. result.push(nV2.clone());
  19799. result.push(nV1.clone());
  19800. result.push(nV2.clone());
  19801. result.push(nV3.clone());
  19802. result.push(nV4);
  19803. break;
  19804. }
  19805. if (v3Out) {
  19806. nV1 = vertices[index];
  19807. nV2 = vertices[index + 1];
  19808. nV3 = clipVertices(vertices[index + 2], nV1);
  19809. nV4 = clipVertices(vertices[index + 2], nV2);
  19810. }
  19811. result.push(nV1.clone());
  19812. result.push(nV2.clone());
  19813. result.push(nV3);
  19814. result.push(nV4);
  19815. result.push(nV3.clone());
  19816. result.push(nV2.clone());
  19817. break;
  19818. case 2:
  19819. if (!v1Out) {
  19820. nV1 = vertices[index].clone();
  19821. nV2 = clipVertices(nV1, vertices[index + 1]);
  19822. nV3 = clipVertices(nV1, vertices[index + 2]);
  19823. result.push(nV1);
  19824. result.push(nV2);
  19825. result.push(nV3);
  19826. }
  19827. if (!v2Out) {
  19828. nV1 = vertices[index + 1].clone();
  19829. nV2 = clipVertices(nV1, vertices[index + 2]);
  19830. nV3 = clipVertices(nV1, vertices[index]);
  19831. result.push(nV1);
  19832. result.push(nV2);
  19833. result.push(nV3);
  19834. }
  19835. if (!v3Out) {
  19836. nV1 = vertices[index + 2].clone();
  19837. nV2 = clipVertices(nV1, vertices[index]);
  19838. nV3 = clipVertices(nV1, vertices[index + 1]);
  19839. result.push(nV1);
  19840. result.push(nV2);
  19841. result.push(nV3);
  19842. }
  19843. break;
  19844. case 3:
  19845. break;
  19846. }
  19847. }
  19848. return result;
  19849. };
  19850. for (var index = 0; index < indices.length; index += 3) {
  19851. var faceVertices = new Array();
  19852. faceVertices.push(extractDecalVector3(index));
  19853. faceVertices.push(extractDecalVector3(index + 1));
  19854. faceVertices.push(extractDecalVector3(index + 2));
  19855. // Clip
  19856. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  19857. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  19858. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  19859. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  19860. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  19861. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  19862. if (faceVertices.length === 0) {
  19863. continue;
  19864. }
  19865. // Add UVs and get back to world
  19866. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  19867. var vertex = faceVertices[vIndex];
  19868. //TODO check for Int32Array
  19869. vertexData.indices.push(currentVertexDataIndex);
  19870. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  19871. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  19872. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  19873. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  19874. currentVertexDataIndex++;
  19875. }
  19876. }
  19877. // Return mesh
  19878. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  19879. vertexData.applyToMesh(decal);
  19880. decal.position = position.clone();
  19881. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  19882. return decal;
  19883. };
  19884. // Privates
  19885. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  19886. // extrusion geometry
  19887. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  19888. var tangents = path3D.getTangents();
  19889. var normals = path3D.getNormals();
  19890. var binormals = path3D.getBinormals();
  19891. var distances = path3D.getDistances();
  19892. var angle = 0;
  19893. var returnScale = function () { return scale; };
  19894. var returnRotation = function () { return rotation; };
  19895. var rotate = custom ? rotateFunction : returnRotation;
  19896. var scl = custom ? scaleFunction : returnScale;
  19897. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19898. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19899. for (var i = 0; i < curve.length; i++) {
  19900. var shapePath = new Array();
  19901. var angleStep = rotate(i, distances[i]);
  19902. var scaleRatio = scl(i, distances[i]);
  19903. for (var p = 0; p < shape.length; p++) {
  19904. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  19905. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  19906. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  19907. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  19908. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  19909. shapePath[p] = rotated;
  19910. }
  19911. shapePaths[index] = shapePath;
  19912. angle += angleStep;
  19913. index++;
  19914. }
  19915. // cap
  19916. var capPath = function (shapePath) {
  19917. var pointCap = Array();
  19918. var barycenter = BABYLON.Vector3.Zero();
  19919. var i;
  19920. for (i = 0; i < shapePath.length; i++) {
  19921. barycenter.addInPlace(shapePath[i]);
  19922. }
  19923. barycenter.scaleInPlace(1 / shapePath.length);
  19924. for (i = 0; i < shapePath.length; i++) {
  19925. pointCap.push(barycenter);
  19926. }
  19927. return pointCap;
  19928. };
  19929. switch (cap) {
  19930. case BABYLON.Mesh.NO_CAP:
  19931. break;
  19932. case BABYLON.Mesh.CAP_START:
  19933. shapePaths[0] = capPath(shapePaths[2]);
  19934. shapePaths[1] = shapePaths[2].slice(0);
  19935. break;
  19936. case BABYLON.Mesh.CAP_END:
  19937. shapePaths[index] = shapePaths[index - 1];
  19938. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  19939. break;
  19940. case BABYLON.Mesh.CAP_ALL:
  19941. shapePaths[0] = capPath(shapePaths[2]);
  19942. shapePaths[1] = shapePaths[2].slice(0);
  19943. shapePaths[index] = shapePaths[index - 1];
  19944. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  19945. break;
  19946. default:
  19947. break;
  19948. }
  19949. return shapePaths;
  19950. };
  19951. var path3D;
  19952. var pathArray;
  19953. if (instance) {
  19954. path3D = (instance.path3D).update(curve);
  19955. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  19956. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  19957. return instance;
  19958. }
  19959. // extruded shape creation
  19960. path3D = new BABYLON.Path3D(curve);
  19961. var newShapePaths = new Array();
  19962. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19963. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  19964. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  19965. extrudedGeneric.pathArray = pathArray;
  19966. extrudedGeneric.path3D = path3D;
  19967. extrudedGeneric.cap = cap;
  19968. return extrudedGeneric;
  19969. };
  19970. return MeshBuilder;
  19971. }());
  19972. BABYLON.MeshBuilder = MeshBuilder;
  19973. })(BABYLON || (BABYLON = {}));
  19974. var BABYLON;
  19975. (function (BABYLON) {
  19976. var BaseTexture = (function () {
  19977. function BaseTexture(scene) {
  19978. this.hasAlpha = false;
  19979. this.getAlphaFromRGB = false;
  19980. this.level = 1;
  19981. this.coordinatesIndex = 0;
  19982. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  19983. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19984. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19985. this.anisotropicFilteringLevel = 4;
  19986. this.isCube = false;
  19987. this.isRenderTarget = false;
  19988. this.animations = new Array();
  19989. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19990. this._scene = scene;
  19991. this._scene.textures.push(this);
  19992. }
  19993. BaseTexture.prototype.getScene = function () {
  19994. return this._scene;
  19995. };
  19996. BaseTexture.prototype.getTextureMatrix = function () {
  19997. return null;
  19998. };
  19999. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20000. return null;
  20001. };
  20002. BaseTexture.prototype.getInternalTexture = function () {
  20003. return this._texture;
  20004. };
  20005. BaseTexture.prototype.isReady = function () {
  20006. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20007. return true;
  20008. }
  20009. if (this._texture) {
  20010. return this._texture.isReady;
  20011. }
  20012. return false;
  20013. };
  20014. BaseTexture.prototype.getSize = function () {
  20015. if (this._texture._width) {
  20016. return { width: this._texture._width, height: this._texture._height };
  20017. }
  20018. if (this._texture._size) {
  20019. return { width: this._texture._size, height: this._texture._size };
  20020. }
  20021. return { width: 0, height: 0 };
  20022. };
  20023. BaseTexture.prototype.getBaseSize = function () {
  20024. if (!this.isReady())
  20025. return { width: 0, height: 0 };
  20026. if (this._texture._size) {
  20027. return { width: this._texture._size, height: this._texture._size };
  20028. }
  20029. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20030. };
  20031. BaseTexture.prototype.scale = function (ratio) {
  20032. };
  20033. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20034. get: function () {
  20035. return false;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20041. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20042. for (var index = 0; index < texturesCache.length; index++) {
  20043. var texturesCacheEntry = texturesCache[index];
  20044. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20045. texturesCache.splice(index, 1);
  20046. return;
  20047. }
  20048. }
  20049. };
  20050. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20051. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20052. for (var index = 0; index < texturesCache.length; index++) {
  20053. var texturesCacheEntry = texturesCache[index];
  20054. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20055. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20056. texturesCacheEntry.references++;
  20057. return texturesCacheEntry;
  20058. }
  20059. }
  20060. }
  20061. return null;
  20062. };
  20063. BaseTexture.prototype.delayLoad = function () {
  20064. };
  20065. BaseTexture.prototype.clone = function () {
  20066. return null;
  20067. };
  20068. BaseTexture.prototype.releaseInternalTexture = function () {
  20069. if (this._texture) {
  20070. this._scene.getEngine().releaseInternalTexture(this._texture);
  20071. delete this._texture;
  20072. }
  20073. };
  20074. BaseTexture.prototype.dispose = function () {
  20075. // Animations
  20076. this.getScene().stopAnimation(this);
  20077. // Remove from scene
  20078. var index = this._scene.textures.indexOf(this);
  20079. if (index >= 0) {
  20080. this._scene.textures.splice(index, 1);
  20081. }
  20082. if (this._texture === undefined) {
  20083. return;
  20084. }
  20085. // Release
  20086. this.releaseInternalTexture();
  20087. // Callback
  20088. if (this.onDispose) {
  20089. this.onDispose();
  20090. }
  20091. };
  20092. BaseTexture.prototype.serialize = function () {
  20093. if (!this.name) {
  20094. return null;
  20095. }
  20096. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20097. // Animations
  20098. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20099. return serializationObject;
  20100. };
  20101. __decorate([
  20102. BABYLON.serialize()
  20103. ], BaseTexture.prototype, "name", void 0);
  20104. __decorate([
  20105. BABYLON.serialize()
  20106. ], BaseTexture.prototype, "hasAlpha", void 0);
  20107. __decorate([
  20108. BABYLON.serialize()
  20109. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20110. __decorate([
  20111. BABYLON.serialize()
  20112. ], BaseTexture.prototype, "level", void 0);
  20113. __decorate([
  20114. BABYLON.serialize()
  20115. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20116. __decorate([
  20117. BABYLON.serialize()
  20118. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20119. __decorate([
  20120. BABYLON.serialize()
  20121. ], BaseTexture.prototype, "wrapU", void 0);
  20122. __decorate([
  20123. BABYLON.serialize()
  20124. ], BaseTexture.prototype, "wrapV", void 0);
  20125. __decorate([
  20126. BABYLON.serialize()
  20127. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20128. __decorate([
  20129. BABYLON.serialize()
  20130. ], BaseTexture.prototype, "isCube", void 0);
  20131. __decorate([
  20132. BABYLON.serialize()
  20133. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20134. return BaseTexture;
  20135. }());
  20136. BABYLON.BaseTexture = BaseTexture;
  20137. })(BABYLON || (BABYLON = {}));
  20138. var BABYLON;
  20139. (function (BABYLON) {
  20140. var Texture = (function (_super) {
  20141. __extends(Texture, _super);
  20142. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20143. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20144. if (onLoad === void 0) { onLoad = null; }
  20145. if (onError === void 0) { onError = null; }
  20146. if (buffer === void 0) { buffer = null; }
  20147. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20148. _super.call(this, scene);
  20149. this.uOffset = 0;
  20150. this.vOffset = 0;
  20151. this.uScale = 1.0;
  20152. this.vScale = 1.0;
  20153. this.uAng = 0;
  20154. this.vAng = 0;
  20155. this.wAng = 0;
  20156. this.name = url;
  20157. this.url = url;
  20158. this._noMipmap = noMipmap;
  20159. this._invertY = invertY;
  20160. this._samplingMode = samplingMode;
  20161. this._buffer = buffer;
  20162. this._deleteBuffer = deleteBuffer;
  20163. if (!url) {
  20164. return;
  20165. }
  20166. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20167. if (!this._texture) {
  20168. if (!scene.useDelayedTextureLoading) {
  20169. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20170. if (deleteBuffer) {
  20171. delete this._buffer;
  20172. }
  20173. }
  20174. else {
  20175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20176. this._delayedOnLoad = onLoad;
  20177. this._delayedOnError = onError;
  20178. }
  20179. }
  20180. else {
  20181. BABYLON.Tools.SetImmediate(function () {
  20182. if (onLoad) {
  20183. onLoad();
  20184. }
  20185. });
  20186. }
  20187. }
  20188. Texture.prototype.delayLoad = function () {
  20189. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20190. return;
  20191. }
  20192. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20193. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20194. if (!this._texture) {
  20195. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20196. if (this._deleteBuffer) {
  20197. delete this._buffer;
  20198. }
  20199. }
  20200. };
  20201. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20202. if (!this._texture) {
  20203. return;
  20204. }
  20205. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20206. };
  20207. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20208. x *= this.uScale;
  20209. y *= this.vScale;
  20210. x -= 0.5 * this.uScale;
  20211. y -= 0.5 * this.vScale;
  20212. z -= 0.5;
  20213. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20214. t.x += 0.5 * this.uScale + this.uOffset;
  20215. t.y += 0.5 * this.vScale + this.vOffset;
  20216. t.z += 0.5;
  20217. };
  20218. Texture.prototype.getTextureMatrix = function () {
  20219. if (this.uOffset === this._cachedUOffset &&
  20220. this.vOffset === this._cachedVOffset &&
  20221. this.uScale === this._cachedUScale &&
  20222. this.vScale === this._cachedVScale &&
  20223. this.uAng === this._cachedUAng &&
  20224. this.vAng === this._cachedVAng &&
  20225. this.wAng === this._cachedWAng) {
  20226. return this._cachedTextureMatrix;
  20227. }
  20228. this._cachedUOffset = this.uOffset;
  20229. this._cachedVOffset = this.vOffset;
  20230. this._cachedUScale = this.uScale;
  20231. this._cachedVScale = this.vScale;
  20232. this._cachedUAng = this.uAng;
  20233. this._cachedVAng = this.vAng;
  20234. this._cachedWAng = this.wAng;
  20235. if (!this._cachedTextureMatrix) {
  20236. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20237. this._rowGenerationMatrix = new BABYLON.Matrix();
  20238. this._t0 = BABYLON.Vector3.Zero();
  20239. this._t1 = BABYLON.Vector3.Zero();
  20240. this._t2 = BABYLON.Vector3.Zero();
  20241. }
  20242. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20243. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20244. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20245. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20246. this._t1.subtractInPlace(this._t0);
  20247. this._t2.subtractInPlace(this._t0);
  20248. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20249. this._cachedTextureMatrix.m[0] = this._t1.x;
  20250. this._cachedTextureMatrix.m[1] = this._t1.y;
  20251. this._cachedTextureMatrix.m[2] = this._t1.z;
  20252. this._cachedTextureMatrix.m[4] = this._t2.x;
  20253. this._cachedTextureMatrix.m[5] = this._t2.y;
  20254. this._cachedTextureMatrix.m[6] = this._t2.z;
  20255. this._cachedTextureMatrix.m[8] = this._t0.x;
  20256. this._cachedTextureMatrix.m[9] = this._t0.y;
  20257. this._cachedTextureMatrix.m[10] = this._t0.z;
  20258. return this._cachedTextureMatrix;
  20259. };
  20260. Texture.prototype.getReflectionTextureMatrix = function () {
  20261. if (this.uOffset === this._cachedUOffset &&
  20262. this.vOffset === this._cachedVOffset &&
  20263. this.uScale === this._cachedUScale &&
  20264. this.vScale === this._cachedVScale &&
  20265. this.coordinatesMode === this._cachedCoordinatesMode) {
  20266. return this._cachedTextureMatrix;
  20267. }
  20268. if (!this._cachedTextureMatrix) {
  20269. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20270. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20271. }
  20272. this._cachedCoordinatesMode = this.coordinatesMode;
  20273. switch (this.coordinatesMode) {
  20274. case Texture.PLANAR_MODE:
  20275. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20276. this._cachedTextureMatrix[0] = this.uScale;
  20277. this._cachedTextureMatrix[5] = this.vScale;
  20278. this._cachedTextureMatrix[12] = this.uOffset;
  20279. this._cachedTextureMatrix[13] = this.vOffset;
  20280. break;
  20281. case Texture.PROJECTION_MODE:
  20282. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20283. this._projectionModeMatrix.m[0] = 0.5;
  20284. this._projectionModeMatrix.m[5] = -0.5;
  20285. this._projectionModeMatrix.m[10] = 0.0;
  20286. this._projectionModeMatrix.m[12] = 0.5;
  20287. this._projectionModeMatrix.m[13] = 0.5;
  20288. this._projectionModeMatrix.m[14] = 1.0;
  20289. this._projectionModeMatrix.m[15] = 1.0;
  20290. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20291. break;
  20292. default:
  20293. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20294. break;
  20295. }
  20296. return this._cachedTextureMatrix;
  20297. };
  20298. Texture.prototype.clone = function () {
  20299. var _this = this;
  20300. return BABYLON.SerializationHelper.Clone(function () {
  20301. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20302. }, this);
  20303. };
  20304. // Statics
  20305. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20306. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20307. if (onLoad === void 0) { onLoad = null; }
  20308. if (onError === void 0) { onError = null; }
  20309. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20310. };
  20311. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20312. if (parsedTexture.isCube) {
  20313. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20314. }
  20315. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20316. return null;
  20317. }
  20318. var texture = BABYLON.SerializationHelper.Parse(function () {
  20319. if (parsedTexture.mirrorPlane) {
  20320. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20321. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20322. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20323. return mirrorTexture;
  20324. }
  20325. else if (parsedTexture.isRenderTarget) {
  20326. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20327. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20328. return renderTargetTexture;
  20329. }
  20330. else {
  20331. var texture;
  20332. if (parsedTexture.base64String) {
  20333. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20334. }
  20335. else {
  20336. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20337. }
  20338. return texture;
  20339. }
  20340. }, parsedTexture, scene);
  20341. // Animations
  20342. if (parsedTexture.animations) {
  20343. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20344. var parsedAnimation = parsedTexture.animations[animationIndex];
  20345. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20346. }
  20347. }
  20348. return texture;
  20349. };
  20350. // Constants
  20351. Texture.NEAREST_SAMPLINGMODE = 1;
  20352. Texture.BILINEAR_SAMPLINGMODE = 2;
  20353. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20354. Texture.EXPLICIT_MODE = 0;
  20355. Texture.SPHERICAL_MODE = 1;
  20356. Texture.PLANAR_MODE = 2;
  20357. Texture.CUBIC_MODE = 3;
  20358. Texture.PROJECTION_MODE = 4;
  20359. Texture.SKYBOX_MODE = 5;
  20360. Texture.INVCUBIC_MODE = 6;
  20361. Texture.EQUIRECTANGULAR_MODE = 7;
  20362. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20363. Texture.CLAMP_ADDRESSMODE = 0;
  20364. Texture.WRAP_ADDRESSMODE = 1;
  20365. Texture.MIRROR_ADDRESSMODE = 2;
  20366. __decorate([
  20367. BABYLON.serialize()
  20368. ], Texture.prototype, "url", void 0);
  20369. __decorate([
  20370. BABYLON.serialize()
  20371. ], Texture.prototype, "uOffset", void 0);
  20372. __decorate([
  20373. BABYLON.serialize()
  20374. ], Texture.prototype, "vOffset", void 0);
  20375. __decorate([
  20376. BABYLON.serialize()
  20377. ], Texture.prototype, "uScale", void 0);
  20378. __decorate([
  20379. BABYLON.serialize()
  20380. ], Texture.prototype, "vScale", void 0);
  20381. __decorate([
  20382. BABYLON.serialize()
  20383. ], Texture.prototype, "uAng", void 0);
  20384. __decorate([
  20385. BABYLON.serialize()
  20386. ], Texture.prototype, "vAng", void 0);
  20387. __decorate([
  20388. BABYLON.serialize()
  20389. ], Texture.prototype, "wAng", void 0);
  20390. return Texture;
  20391. }(BABYLON.BaseTexture));
  20392. BABYLON.Texture = Texture;
  20393. })(BABYLON || (BABYLON = {}));
  20394. var BABYLON;
  20395. (function (BABYLON) {
  20396. var CubeTexture = (function (_super) {
  20397. __extends(CubeTexture, _super);
  20398. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20399. _super.call(this, scene);
  20400. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20401. this.name = rootUrl;
  20402. this.url = rootUrl;
  20403. this._noMipmap = noMipmap;
  20404. this.hasAlpha = false;
  20405. if (!rootUrl && !files) {
  20406. return;
  20407. }
  20408. this._texture = this._getFromCache(rootUrl, noMipmap);
  20409. if (!files) {
  20410. if (!extensions) {
  20411. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20412. }
  20413. files = [];
  20414. for (var index = 0; index < extensions.length; index++) {
  20415. files.push(rootUrl + extensions[index]);
  20416. }
  20417. this._extensions = extensions;
  20418. }
  20419. this._files = files;
  20420. if (!this._texture) {
  20421. if (!scene.useDelayedTextureLoading) {
  20422. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20423. }
  20424. else {
  20425. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20426. }
  20427. }
  20428. this.isCube = true;
  20429. this._textureMatrix = BABYLON.Matrix.Identity();
  20430. }
  20431. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20432. return new CubeTexture("", scene, null, noMipmap, files);
  20433. };
  20434. // Methods
  20435. CubeTexture.prototype.delayLoad = function () {
  20436. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20437. return;
  20438. }
  20439. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20440. this._texture = this._getFromCache(this.url, this._noMipmap);
  20441. if (!this._texture) {
  20442. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20443. }
  20444. };
  20445. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20446. return this._textureMatrix;
  20447. };
  20448. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20449. var texture = BABYLON.SerializationHelper.Parse(function () {
  20450. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20451. }, parsedTexture, scene);
  20452. // Animations
  20453. if (parsedTexture.animations) {
  20454. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20455. var parsedAnimation = parsedTexture.animations[animationIndex];
  20456. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20457. }
  20458. }
  20459. return texture;
  20460. };
  20461. CubeTexture.prototype.clone = function () {
  20462. var _this = this;
  20463. return BABYLON.SerializationHelper.Clone(function () {
  20464. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20465. }, this);
  20466. };
  20467. return CubeTexture;
  20468. }(BABYLON.BaseTexture));
  20469. BABYLON.CubeTexture = CubeTexture;
  20470. })(BABYLON || (BABYLON = {}));
  20471. var BABYLON;
  20472. (function (BABYLON) {
  20473. var RenderTargetTexture = (function (_super) {
  20474. __extends(RenderTargetTexture, _super);
  20475. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20476. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20477. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20478. if (isCube === void 0) { isCube = false; }
  20479. _super.call(this, null, scene, !generateMipMaps);
  20480. this.isCube = isCube;
  20481. this.renderList = new Array();
  20482. this.renderParticles = true;
  20483. this.renderSprites = false;
  20484. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20485. this._currentRefreshId = -1;
  20486. this._refreshRate = 1;
  20487. this.name = name;
  20488. this.isRenderTarget = true;
  20489. this._size = size;
  20490. this._generateMipMaps = generateMipMaps;
  20491. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20492. if (isCube) {
  20493. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20494. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20495. this._textureMatrix = BABYLON.Matrix.Identity();
  20496. }
  20497. else {
  20498. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20499. }
  20500. // Rendering groups
  20501. this._renderingManager = new BABYLON.RenderingManager(scene);
  20502. }
  20503. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20504. get: function () {
  20505. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20506. },
  20507. enumerable: true,
  20508. configurable: true
  20509. });
  20510. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20511. get: function () {
  20512. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20513. },
  20514. enumerable: true,
  20515. configurable: true
  20516. });
  20517. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20518. get: function () {
  20519. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20520. },
  20521. enumerable: true,
  20522. configurable: true
  20523. });
  20524. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20525. this._currentRefreshId = -1;
  20526. };
  20527. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20528. get: function () {
  20529. return this._refreshRate;
  20530. },
  20531. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20532. set: function (value) {
  20533. this._refreshRate = value;
  20534. this.resetRefreshCounter();
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. RenderTargetTexture.prototype._shouldRender = function () {
  20540. if (this._currentRefreshId === -1) {
  20541. this._currentRefreshId = 1;
  20542. return true;
  20543. }
  20544. if (this.refreshRate === this._currentRefreshId) {
  20545. this._currentRefreshId = 1;
  20546. return true;
  20547. }
  20548. this._currentRefreshId++;
  20549. return false;
  20550. };
  20551. RenderTargetTexture.prototype.isReady = function () {
  20552. if (!this.getScene().renderTargetsEnabled) {
  20553. return false;
  20554. }
  20555. return _super.prototype.isReady.call(this);
  20556. };
  20557. RenderTargetTexture.prototype.getRenderSize = function () {
  20558. return this._size;
  20559. };
  20560. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20561. get: function () {
  20562. return true;
  20563. },
  20564. enumerable: true,
  20565. configurable: true
  20566. });
  20567. RenderTargetTexture.prototype.scale = function (ratio) {
  20568. var newSize = this._size * ratio;
  20569. this.resize(newSize, this._generateMipMaps);
  20570. };
  20571. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20572. if (this.isCube) {
  20573. return this._textureMatrix;
  20574. }
  20575. return _super.prototype.getReflectionTextureMatrix.call(this);
  20576. };
  20577. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20578. this.releaseInternalTexture();
  20579. if (this.isCube) {
  20580. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20581. }
  20582. else {
  20583. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20584. }
  20585. };
  20586. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20587. var scene = this.getScene();
  20588. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20589. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20590. }
  20591. if (this._waitingRenderList) {
  20592. this.renderList = [];
  20593. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20594. var id = this._waitingRenderList[index];
  20595. this.renderList.push(scene.getMeshByID(id));
  20596. }
  20597. delete this._waitingRenderList;
  20598. }
  20599. if (this.renderList && this.renderList.length === 0) {
  20600. return;
  20601. }
  20602. // Prepare renderingManager
  20603. this._renderingManager.reset();
  20604. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20605. var sceneRenderId = scene.getRenderId();
  20606. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20607. var mesh = currentRenderList[meshIndex];
  20608. if (mesh) {
  20609. if (!mesh.isReady()) {
  20610. // Reset _currentRefreshId
  20611. this.resetRefreshCounter();
  20612. continue;
  20613. }
  20614. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20615. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20616. mesh._activate(sceneRenderId);
  20617. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20618. var subMesh = mesh.subMeshes[subIndex];
  20619. scene._activeIndices += subMesh.indexCount;
  20620. this._renderingManager.dispatch(subMesh);
  20621. }
  20622. }
  20623. }
  20624. }
  20625. if (this.isCube) {
  20626. for (var face = 0; face < 6; face++) {
  20627. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20628. scene.incrementRenderId();
  20629. scene.resetCachedMaterial();
  20630. }
  20631. }
  20632. else {
  20633. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20634. }
  20635. if (this.onAfterUnbind) {
  20636. this.onAfterUnbind();
  20637. }
  20638. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20639. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20640. }
  20641. scene.resetCachedMaterial();
  20642. };
  20643. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20644. var scene = this.getScene();
  20645. var engine = scene.getEngine();
  20646. // Bind
  20647. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20648. if (this.isCube) {
  20649. engine.bindFramebuffer(this._texture, faceIndex);
  20650. }
  20651. else {
  20652. engine.bindFramebuffer(this._texture);
  20653. }
  20654. }
  20655. if (this.onBeforeRender) {
  20656. this.onBeforeRender(faceIndex);
  20657. }
  20658. // Clear
  20659. if (this.onClear) {
  20660. this.onClear(engine);
  20661. }
  20662. else {
  20663. engine.clear(scene.clearColor, true, true);
  20664. }
  20665. if (!this._doNotChangeAspectRatio) {
  20666. scene.updateTransformMatrix(true);
  20667. }
  20668. // Render
  20669. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20670. if (useCameraPostProcess) {
  20671. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20672. }
  20673. if (!this._doNotChangeAspectRatio) {
  20674. scene.updateTransformMatrix(true);
  20675. }
  20676. if (this.onAfterRender) {
  20677. this.onAfterRender(faceIndex);
  20678. }
  20679. // Dump ?
  20680. if (dumpForDebug) {
  20681. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20682. }
  20683. // Unbind
  20684. if (!this.isCube || faceIndex === 5) {
  20685. if (this.isCube) {
  20686. if (faceIndex === 5) {
  20687. engine.generateMipMapsForCubemap(this._texture);
  20688. }
  20689. }
  20690. engine.unBindFramebuffer(this._texture, this.isCube);
  20691. }
  20692. };
  20693. RenderTargetTexture.prototype.clone = function () {
  20694. var textureSize = this.getSize();
  20695. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20696. // Base texture
  20697. newTexture.hasAlpha = this.hasAlpha;
  20698. newTexture.level = this.level;
  20699. // RenderTarget Texture
  20700. newTexture.coordinatesMode = this.coordinatesMode;
  20701. newTexture.renderList = this.renderList.slice(0);
  20702. return newTexture;
  20703. };
  20704. RenderTargetTexture.prototype.serialize = function () {
  20705. if (!this.name) {
  20706. return null;
  20707. }
  20708. var serializationObject = _super.prototype.serialize.call(this);
  20709. serializationObject.renderTargetSize = this.getRenderSize();
  20710. serializationObject.renderList = [];
  20711. for (var index = 0; index < this.renderList.length; index++) {
  20712. serializationObject.renderList.push(this.renderList[index].id);
  20713. }
  20714. return serializationObject;
  20715. };
  20716. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  20717. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  20718. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  20719. return RenderTargetTexture;
  20720. }(BABYLON.Texture));
  20721. BABYLON.RenderTargetTexture = RenderTargetTexture;
  20722. })(BABYLON || (BABYLON = {}));
  20723. var BABYLON;
  20724. (function (BABYLON) {
  20725. var ProceduralTexture = (function (_super) {
  20726. __extends(ProceduralTexture, _super);
  20727. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  20728. if (generateMipMaps === void 0) { generateMipMaps = true; }
  20729. if (isCube === void 0) { isCube = false; }
  20730. _super.call(this, null, scene, !generateMipMaps);
  20731. this.isCube = isCube;
  20732. this.isEnabled = true;
  20733. this._currentRefreshId = -1;
  20734. this._refreshRate = 1;
  20735. this._vertexDeclaration = [2];
  20736. this._vertexStrideSize = 2 * 4;
  20737. this._uniforms = new Array();
  20738. this._samplers = new Array();
  20739. this._textures = new Array();
  20740. this._floats = new Array();
  20741. this._floatsArrays = {};
  20742. this._colors3 = new Array();
  20743. this._colors4 = new Array();
  20744. this._vectors2 = new Array();
  20745. this._vectors3 = new Array();
  20746. this._matrices = new Array();
  20747. this._fallbackTextureUsed = false;
  20748. scene._proceduralTextures.push(this);
  20749. this.name = name;
  20750. this.isRenderTarget = true;
  20751. this._size = size;
  20752. this._generateMipMaps = generateMipMaps;
  20753. this.setFragment(fragment);
  20754. this._fallbackTexture = fallbackTexture;
  20755. if (isCube) {
  20756. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20757. this.setFloat("face", 0);
  20758. }
  20759. else {
  20760. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  20761. }
  20762. // VBO
  20763. var vertices = [];
  20764. vertices.push(1, 1);
  20765. vertices.push(-1, 1);
  20766. vertices.push(-1, -1);
  20767. vertices.push(1, -1);
  20768. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20769. // Indices
  20770. var indices = [];
  20771. indices.push(0);
  20772. indices.push(1);
  20773. indices.push(2);
  20774. indices.push(0);
  20775. indices.push(2);
  20776. indices.push(3);
  20777. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20778. }
  20779. ProceduralTexture.prototype.reset = function () {
  20780. if (this._effect === undefined) {
  20781. return;
  20782. }
  20783. var engine = this.getScene().getEngine();
  20784. engine._releaseEffect(this._effect);
  20785. };
  20786. ProceduralTexture.prototype.isReady = function () {
  20787. var _this = this;
  20788. var engine = this.getScene().getEngine();
  20789. var shaders;
  20790. if (!this._fragment) {
  20791. return false;
  20792. }
  20793. if (this._fallbackTextureUsed) {
  20794. return true;
  20795. }
  20796. if (this._fragment.fragmentElement !== undefined) {
  20797. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  20798. }
  20799. else {
  20800. shaders = { vertex: "procedural", fragment: this._fragment };
  20801. }
  20802. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  20803. _this.releaseInternalTexture();
  20804. if (_this._fallbackTexture) {
  20805. _this._texture = _this._fallbackTexture._texture;
  20806. _this._texture.references++;
  20807. }
  20808. _this._fallbackTextureUsed = true;
  20809. });
  20810. return this._effect.isReady();
  20811. };
  20812. ProceduralTexture.prototype.resetRefreshCounter = function () {
  20813. this._currentRefreshId = -1;
  20814. };
  20815. ProceduralTexture.prototype.setFragment = function (fragment) {
  20816. this._fragment = fragment;
  20817. };
  20818. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  20819. get: function () {
  20820. return this._refreshRate;
  20821. },
  20822. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20823. set: function (value) {
  20824. this._refreshRate = value;
  20825. this.resetRefreshCounter();
  20826. },
  20827. enumerable: true,
  20828. configurable: true
  20829. });
  20830. ProceduralTexture.prototype._shouldRender = function () {
  20831. if (!this.isEnabled || !this.isReady() || !this._texture) {
  20832. return false;
  20833. }
  20834. if (this._fallbackTextureUsed) {
  20835. return false;
  20836. }
  20837. if (this._currentRefreshId === -1) {
  20838. this._currentRefreshId = 1;
  20839. return true;
  20840. }
  20841. if (this.refreshRate === this._currentRefreshId) {
  20842. this._currentRefreshId = 1;
  20843. return true;
  20844. }
  20845. this._currentRefreshId++;
  20846. return false;
  20847. };
  20848. ProceduralTexture.prototype.getRenderSize = function () {
  20849. return this._size;
  20850. };
  20851. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  20852. if (this._fallbackTextureUsed) {
  20853. return;
  20854. }
  20855. this.releaseInternalTexture();
  20856. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20857. };
  20858. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  20859. if (this._uniforms.indexOf(uniformName) === -1) {
  20860. this._uniforms.push(uniformName);
  20861. }
  20862. };
  20863. ProceduralTexture.prototype.setTexture = function (name, texture) {
  20864. if (this._samplers.indexOf(name) === -1) {
  20865. this._samplers.push(name);
  20866. }
  20867. this._textures[name] = texture;
  20868. return this;
  20869. };
  20870. ProceduralTexture.prototype.setFloat = function (name, value) {
  20871. this._checkUniform(name);
  20872. this._floats[name] = value;
  20873. return this;
  20874. };
  20875. ProceduralTexture.prototype.setFloats = function (name, value) {
  20876. this._checkUniform(name);
  20877. this._floatsArrays[name] = value;
  20878. return this;
  20879. };
  20880. ProceduralTexture.prototype.setColor3 = function (name, value) {
  20881. this._checkUniform(name);
  20882. this._colors3[name] = value;
  20883. return this;
  20884. };
  20885. ProceduralTexture.prototype.setColor4 = function (name, value) {
  20886. this._checkUniform(name);
  20887. this._colors4[name] = value;
  20888. return this;
  20889. };
  20890. ProceduralTexture.prototype.setVector2 = function (name, value) {
  20891. this._checkUniform(name);
  20892. this._vectors2[name] = value;
  20893. return this;
  20894. };
  20895. ProceduralTexture.prototype.setVector3 = function (name, value) {
  20896. this._checkUniform(name);
  20897. this._vectors3[name] = value;
  20898. return this;
  20899. };
  20900. ProceduralTexture.prototype.setMatrix = function (name, value) {
  20901. this._checkUniform(name);
  20902. this._matrices[name] = value;
  20903. return this;
  20904. };
  20905. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  20906. var scene = this.getScene();
  20907. var engine = scene.getEngine();
  20908. // Render
  20909. engine.enableEffect(this._effect);
  20910. engine.setState(false);
  20911. // Texture
  20912. for (var name in this._textures) {
  20913. this._effect.setTexture(name, this._textures[name]);
  20914. }
  20915. // Float
  20916. for (name in this._floats) {
  20917. this._effect.setFloat(name, this._floats[name]);
  20918. }
  20919. // Floats
  20920. for (name in this._floatsArrays) {
  20921. this._effect.setArray(name, this._floatsArrays[name]);
  20922. }
  20923. // Color3
  20924. for (name in this._colors3) {
  20925. this._effect.setColor3(name, this._colors3[name]);
  20926. }
  20927. // Color4
  20928. for (name in this._colors4) {
  20929. var color = this._colors4[name];
  20930. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20931. }
  20932. // Vector2
  20933. for (name in this._vectors2) {
  20934. this._effect.setVector2(name, this._vectors2[name]);
  20935. }
  20936. // Vector3
  20937. for (name in this._vectors3) {
  20938. this._effect.setVector3(name, this._vectors3[name]);
  20939. }
  20940. // Matrix
  20941. for (name in this._matrices) {
  20942. this._effect.setMatrix(name, this._matrices[name]);
  20943. }
  20944. // VBOs
  20945. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20946. if (this.isCube) {
  20947. for (var face = 0; face < 6; face++) {
  20948. engine.bindFramebuffer(this._texture, face);
  20949. this._effect.setFloat("face", face);
  20950. // Clear
  20951. engine.clear(scene.clearColor, true, true);
  20952. // Draw order
  20953. engine.draw(true, 0, 6);
  20954. // Mipmaps
  20955. if (face === 5) {
  20956. engine.generateMipMapsForCubemap(this._texture);
  20957. }
  20958. }
  20959. }
  20960. else {
  20961. engine.bindFramebuffer(this._texture);
  20962. // Clear
  20963. engine.clear(scene.clearColor, true, true);
  20964. // Draw order
  20965. engine.draw(true, 0, 6);
  20966. }
  20967. // Unbind
  20968. engine.unBindFramebuffer(this._texture, this.isCube);
  20969. if (this.onGenerated) {
  20970. this.onGenerated();
  20971. }
  20972. };
  20973. ProceduralTexture.prototype.clone = function () {
  20974. var textureSize = this.getSize();
  20975. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  20976. // Base texture
  20977. newTexture.hasAlpha = this.hasAlpha;
  20978. newTexture.level = this.level;
  20979. // RenderTarget Texture
  20980. newTexture.coordinatesMode = this.coordinatesMode;
  20981. return newTexture;
  20982. };
  20983. ProceduralTexture.prototype.dispose = function () {
  20984. var index = this.getScene()._proceduralTextures.indexOf(this);
  20985. if (index >= 0) {
  20986. this.getScene()._proceduralTextures.splice(index, 1);
  20987. }
  20988. _super.prototype.dispose.call(this);
  20989. };
  20990. return ProceduralTexture;
  20991. }(BABYLON.Texture));
  20992. BABYLON.ProceduralTexture = ProceduralTexture;
  20993. })(BABYLON || (BABYLON = {}));
  20994. var BABYLON;
  20995. (function (BABYLON) {
  20996. var MirrorTexture = (function (_super) {
  20997. __extends(MirrorTexture, _super);
  20998. function MirrorTexture(name, size, scene, generateMipMaps) {
  20999. var _this = this;
  21000. _super.call(this, name, size, scene, generateMipMaps, true);
  21001. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21002. this._transformMatrix = BABYLON.Matrix.Zero();
  21003. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21004. this.onBeforeRender = function () {
  21005. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21006. _this._savedViewMatrix = scene.getViewMatrix();
  21007. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21008. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21009. scene.clipPlane = _this.mirrorPlane;
  21010. scene.getEngine().cullBackFaces = false;
  21011. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21012. };
  21013. this.onAfterRender = function () {
  21014. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21015. scene.getEngine().cullBackFaces = true;
  21016. scene._mirroredCameraPosition = null;
  21017. delete scene.clipPlane;
  21018. };
  21019. }
  21020. MirrorTexture.prototype.clone = function () {
  21021. var textureSize = this.getSize();
  21022. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21023. // Base texture
  21024. newTexture.hasAlpha = this.hasAlpha;
  21025. newTexture.level = this.level;
  21026. // Mirror Texture
  21027. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21028. newTexture.renderList = this.renderList.slice(0);
  21029. return newTexture;
  21030. };
  21031. MirrorTexture.prototype.serialize = function () {
  21032. if (!this.name) {
  21033. return null;
  21034. }
  21035. var serializationObject = _super.prototype.serialize.call(this);
  21036. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21037. return serializationObject;
  21038. };
  21039. return MirrorTexture;
  21040. }(BABYLON.RenderTargetTexture));
  21041. BABYLON.MirrorTexture = MirrorTexture;
  21042. })(BABYLON || (BABYLON = {}));
  21043. var BABYLON;
  21044. (function (BABYLON) {
  21045. /**
  21046. * Creates a refraction texture used by refraction channel of the standard material.
  21047. * @param name the texture name
  21048. * @param size size of the underlying texture
  21049. * @param scene root scene
  21050. */
  21051. var RefractionTexture = (function (_super) {
  21052. __extends(RefractionTexture, _super);
  21053. function RefractionTexture(name, size, scene, generateMipMaps) {
  21054. var _this = this;
  21055. _super.call(this, name, size, scene, generateMipMaps, true);
  21056. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21057. this.depth = 2.0;
  21058. this.onBeforeRender = function () {
  21059. scene.clipPlane = _this.refractionPlane;
  21060. };
  21061. this.onAfterRender = function () {
  21062. delete scene.clipPlane;
  21063. };
  21064. }
  21065. RefractionTexture.prototype.clone = function () {
  21066. var textureSize = this.getSize();
  21067. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21068. // Base texture
  21069. newTexture.hasAlpha = this.hasAlpha;
  21070. newTexture.level = this.level;
  21071. // Refraction Texture
  21072. newTexture.refractionPlane = this.refractionPlane.clone();
  21073. newTexture.renderList = this.renderList.slice(0);
  21074. newTexture.depth = this.depth;
  21075. return newTexture;
  21076. };
  21077. RefractionTexture.prototype.serialize = function () {
  21078. if (!this.name) {
  21079. return null;
  21080. }
  21081. var serializationObject = _super.prototype.serialize.call(this);
  21082. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21083. serializationObject.depth = this.depth;
  21084. return serializationObject;
  21085. };
  21086. return RefractionTexture;
  21087. }(BABYLON.RenderTargetTexture));
  21088. BABYLON.RefractionTexture = RefractionTexture;
  21089. })(BABYLON || (BABYLON = {}));
  21090. var BABYLON;
  21091. (function (BABYLON) {
  21092. var DynamicTexture = (function (_super) {
  21093. __extends(DynamicTexture, _super);
  21094. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21096. _super.call(this, null, scene, !generateMipMaps);
  21097. this.name = name;
  21098. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21099. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21100. this._generateMipMaps = generateMipMaps;
  21101. if (options.getContext) {
  21102. this._canvas = options;
  21103. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21104. }
  21105. else {
  21106. this._canvas = document.createElement("canvas");
  21107. if (options.width) {
  21108. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21109. }
  21110. else {
  21111. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21112. }
  21113. }
  21114. var textureSize = this.getSize();
  21115. this._canvas.width = textureSize.width;
  21116. this._canvas.height = textureSize.height;
  21117. this._context = this._canvas.getContext("2d");
  21118. }
  21119. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21120. get: function () {
  21121. return true;
  21122. },
  21123. enumerable: true,
  21124. configurable: true
  21125. });
  21126. DynamicTexture.prototype.scale = function (ratio) {
  21127. var textureSize = this.getSize();
  21128. textureSize.width *= ratio;
  21129. textureSize.height *= ratio;
  21130. this._canvas.width = textureSize.width;
  21131. this._canvas.height = textureSize.height;
  21132. this.releaseInternalTexture();
  21133. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21134. };
  21135. DynamicTexture.prototype.getContext = function () {
  21136. return this._context;
  21137. };
  21138. DynamicTexture.prototype.clear = function () {
  21139. var size = this.getSize();
  21140. this._context.fillRect(0, 0, size.width, size.height);
  21141. };
  21142. DynamicTexture.prototype.update = function (invertY) {
  21143. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21144. };
  21145. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21146. if (update === void 0) { update = true; }
  21147. var size = this.getSize();
  21148. if (clearColor) {
  21149. this._context.fillStyle = clearColor;
  21150. this._context.fillRect(0, 0, size.width, size.height);
  21151. }
  21152. this._context.font = font;
  21153. if (x === null) {
  21154. var textSize = this._context.measureText(text);
  21155. x = (size.width - textSize.width) / 2;
  21156. }
  21157. this._context.fillStyle = color;
  21158. this._context.fillText(text, x, y);
  21159. if (update) {
  21160. this.update(invertY);
  21161. }
  21162. };
  21163. DynamicTexture.prototype.clone = function () {
  21164. var textureSize = this.getSize();
  21165. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21166. // Base texture
  21167. newTexture.hasAlpha = this.hasAlpha;
  21168. newTexture.level = this.level;
  21169. // Dynamic Texture
  21170. newTexture.wrapU = this.wrapU;
  21171. newTexture.wrapV = this.wrapV;
  21172. return newTexture;
  21173. };
  21174. return DynamicTexture;
  21175. }(BABYLON.Texture));
  21176. BABYLON.DynamicTexture = DynamicTexture;
  21177. })(BABYLON || (BABYLON = {}));
  21178. var BABYLON;
  21179. (function (BABYLON) {
  21180. var VideoTexture = (function (_super) {
  21181. __extends(VideoTexture, _super);
  21182. /**
  21183. * Creates a video texture.
  21184. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21185. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21186. * @param {BABYLON.Scene} scene is obviously the current scene.
  21187. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21188. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21189. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21190. */
  21191. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21192. var _this = this;
  21193. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21194. if (invertY === void 0) { invertY = false; }
  21195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21196. _super.call(this, null, scene, !generateMipMaps, invertY);
  21197. this._autoLaunch = true;
  21198. var urls;
  21199. this.name = name;
  21200. if (urlsOrVideo instanceof HTMLVideoElement) {
  21201. this.video = urlsOrVideo;
  21202. }
  21203. else {
  21204. urls = urlsOrVideo;
  21205. this.video = document.createElement("video");
  21206. this.video.autoplay = false;
  21207. this.video.loop = true;
  21208. }
  21209. this._generateMipMaps = generateMipMaps;
  21210. this._samplingMode = samplingMode;
  21211. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21212. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21213. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21214. }
  21215. else {
  21216. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21217. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21218. this._generateMipMaps = false;
  21219. }
  21220. if (urls) {
  21221. this.video.addEventListener("canplaythrough", function () {
  21222. _this._createTexture();
  21223. });
  21224. urls.forEach(function (url) {
  21225. var source = document.createElement("source");
  21226. source.src = url;
  21227. _this.video.appendChild(source);
  21228. });
  21229. }
  21230. else {
  21231. this._createTexture();
  21232. }
  21233. this._lastUpdate = BABYLON.Tools.Now;
  21234. }
  21235. VideoTexture.prototype._createTexture = function () {
  21236. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21237. this._texture.isReady = true;
  21238. };
  21239. VideoTexture.prototype.update = function () {
  21240. if (this._autoLaunch) {
  21241. this._autoLaunch = false;
  21242. this.video.play();
  21243. }
  21244. var now = BABYLON.Tools.Now;
  21245. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21246. return false;
  21247. }
  21248. this._lastUpdate = now;
  21249. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21250. return true;
  21251. };
  21252. return VideoTexture;
  21253. }(BABYLON.Texture));
  21254. BABYLON.VideoTexture = VideoTexture;
  21255. })(BABYLON || (BABYLON = {}));
  21256. var BABYLON;
  21257. (function (BABYLON) {
  21258. var CustomProceduralTexture = (function (_super) {
  21259. __extends(CustomProceduralTexture, _super);
  21260. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21261. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21262. this._animate = true;
  21263. this._time = 0;
  21264. this._texturePath = texturePath;
  21265. //Try to load json
  21266. this.loadJson(texturePath);
  21267. this.refreshRate = 1;
  21268. }
  21269. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21270. var _this = this;
  21271. var that = this;
  21272. function noConfigFile() {
  21273. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21274. try {
  21275. that.setFragment(that._texturePath);
  21276. }
  21277. catch (ex) {
  21278. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21279. }
  21280. }
  21281. var configFileUrl = jsonUrl + "/config.json";
  21282. var xhr = new XMLHttpRequest();
  21283. xhr.open("GET", configFileUrl, true);
  21284. xhr.addEventListener("load", function () {
  21285. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21286. try {
  21287. _this._config = JSON.parse(xhr.response);
  21288. _this.updateShaderUniforms();
  21289. _this.updateTextures();
  21290. _this.setFragment(_this._texturePath + "/custom");
  21291. _this._animate = _this._config.animate;
  21292. _this.refreshRate = _this._config.refreshrate;
  21293. }
  21294. catch (ex) {
  21295. noConfigFile();
  21296. }
  21297. }
  21298. else {
  21299. noConfigFile();
  21300. }
  21301. }, false);
  21302. xhr.addEventListener("error", function () {
  21303. noConfigFile();
  21304. }, false);
  21305. try {
  21306. xhr.send();
  21307. }
  21308. catch (ex) {
  21309. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21310. }
  21311. };
  21312. CustomProceduralTexture.prototype.isReady = function () {
  21313. if (!_super.prototype.isReady.call(this)) {
  21314. return false;
  21315. }
  21316. for (var name in this._textures) {
  21317. var texture = this._textures[name];
  21318. if (!texture.isReady()) {
  21319. return false;
  21320. }
  21321. }
  21322. return true;
  21323. };
  21324. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21325. if (this._animate) {
  21326. this._time += this.getScene().getAnimationRatio() * 0.03;
  21327. this.updateShaderUniforms();
  21328. }
  21329. _super.prototype.render.call(this, useCameraPostProcess);
  21330. };
  21331. CustomProceduralTexture.prototype.updateTextures = function () {
  21332. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21333. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21334. }
  21335. };
  21336. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21337. if (this._config) {
  21338. for (var j = 0; j < this._config.uniforms.length; j++) {
  21339. var uniform = this._config.uniforms[j];
  21340. switch (uniform.type) {
  21341. case "float":
  21342. this.setFloat(uniform.name, uniform.value);
  21343. break;
  21344. case "color3":
  21345. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21346. break;
  21347. case "color4":
  21348. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21349. break;
  21350. case "vector2":
  21351. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21352. break;
  21353. case "vector3":
  21354. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21355. break;
  21356. }
  21357. }
  21358. }
  21359. this.setFloat("time", this._time);
  21360. };
  21361. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21362. get: function () {
  21363. return this._animate;
  21364. },
  21365. set: function (value) {
  21366. this._animate = value;
  21367. },
  21368. enumerable: true,
  21369. configurable: true
  21370. });
  21371. return CustomProceduralTexture;
  21372. }(BABYLON.ProceduralTexture));
  21373. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21374. })(BABYLON || (BABYLON = {}));
  21375. var BABYLON;
  21376. (function (BABYLON) {
  21377. var EffectFallbacks = (function () {
  21378. function EffectFallbacks() {
  21379. this._defines = {};
  21380. this._currentRank = 32;
  21381. this._maxRank = -1;
  21382. }
  21383. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21384. if (!this._defines[rank]) {
  21385. if (rank < this._currentRank) {
  21386. this._currentRank = rank;
  21387. }
  21388. if (rank > this._maxRank) {
  21389. this._maxRank = rank;
  21390. }
  21391. this._defines[rank] = new Array();
  21392. }
  21393. this._defines[rank].push(define);
  21394. };
  21395. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21396. this._meshRank = rank;
  21397. this._mesh = mesh;
  21398. if (rank > this._maxRank) {
  21399. this._maxRank = rank;
  21400. }
  21401. };
  21402. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21403. get: function () {
  21404. return this._currentRank <= this._maxRank;
  21405. },
  21406. enumerable: true,
  21407. configurable: true
  21408. });
  21409. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21410. var currentFallbacks = this._defines[this._currentRank];
  21411. for (var index = 0; index < currentFallbacks.length; index++) {
  21412. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21413. }
  21414. if (this._mesh && this._currentRank === this._meshRank) {
  21415. this._mesh.computeBonesUsingShaders = false;
  21416. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21417. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21418. }
  21419. this._currentRank++;
  21420. return currentDefines;
  21421. };
  21422. return EffectFallbacks;
  21423. }());
  21424. BABYLON.EffectFallbacks = EffectFallbacks;
  21425. var Effect = (function () {
  21426. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  21427. var _this = this;
  21428. this._isReady = false;
  21429. this._compilationError = "";
  21430. this._valueCache = [];
  21431. this._engine = engine;
  21432. this.name = baseName;
  21433. this.defines = defines;
  21434. this._uniformsNames = uniformsNames.concat(samplers);
  21435. this._samplers = samplers;
  21436. this._attributesNames = attributesNames;
  21437. this.onError = onError;
  21438. this.onCompiled = onCompiled;
  21439. var vertexSource;
  21440. var fragmentSource;
  21441. if (baseName.vertexElement) {
  21442. vertexSource = document.getElementById(baseName.vertexElement);
  21443. if (!vertexSource) {
  21444. vertexSource = baseName.vertexElement;
  21445. }
  21446. }
  21447. else {
  21448. vertexSource = baseName.vertex || baseName;
  21449. }
  21450. if (baseName.fragmentElement) {
  21451. fragmentSource = document.getElementById(baseName.fragmentElement);
  21452. if (!fragmentSource) {
  21453. fragmentSource = baseName.fragmentElement;
  21454. }
  21455. }
  21456. else {
  21457. fragmentSource = baseName.fragment || baseName;
  21458. }
  21459. this._loadVertexShader(vertexSource, function (vertexCode) {
  21460. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21461. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21462. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21463. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21464. });
  21465. });
  21466. });
  21467. });
  21468. }
  21469. // Properties
  21470. Effect.prototype.isReady = function () {
  21471. return this._isReady;
  21472. };
  21473. Effect.prototype.getProgram = function () {
  21474. return this._program;
  21475. };
  21476. Effect.prototype.getAttributesNames = function () {
  21477. return this._attributesNames;
  21478. };
  21479. Effect.prototype.getAttributeLocation = function (index) {
  21480. return this._attributes[index];
  21481. };
  21482. Effect.prototype.getAttributeLocationByName = function (name) {
  21483. var index = this._attributesNames.indexOf(name);
  21484. return this._attributes[index];
  21485. };
  21486. Effect.prototype.getAttributesCount = function () {
  21487. return this._attributes.length;
  21488. };
  21489. Effect.prototype.getUniformIndex = function (uniformName) {
  21490. return this._uniformsNames.indexOf(uniformName);
  21491. };
  21492. Effect.prototype.getUniform = function (uniformName) {
  21493. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21494. };
  21495. Effect.prototype.getSamplers = function () {
  21496. return this._samplers;
  21497. };
  21498. Effect.prototype.getCompilationError = function () {
  21499. return this._compilationError;
  21500. };
  21501. // Methods
  21502. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21503. // DOM element ?
  21504. if (vertex instanceof HTMLElement) {
  21505. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21506. callback(vertexCode);
  21507. return;
  21508. }
  21509. // Is in local store ?
  21510. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21511. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21512. return;
  21513. }
  21514. var vertexShaderUrl;
  21515. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21516. vertexShaderUrl = vertex;
  21517. }
  21518. else {
  21519. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21520. }
  21521. // Vertex shader
  21522. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21523. };
  21524. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21525. // DOM element ?
  21526. if (fragment instanceof HTMLElement) {
  21527. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21528. callback(fragmentCode);
  21529. return;
  21530. }
  21531. // Is in local store ?
  21532. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21533. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21534. return;
  21535. }
  21536. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21537. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21538. return;
  21539. }
  21540. var fragmentShaderUrl;
  21541. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21542. fragmentShaderUrl = fragment;
  21543. }
  21544. else {
  21545. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21546. }
  21547. // Fragment shader
  21548. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21549. };
  21550. Effect.prototype._dumpShadersName = function () {
  21551. if (this.name.vertexElement) {
  21552. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21553. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21554. }
  21555. else if (this.name.vertex) {
  21556. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21557. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21558. }
  21559. else {
  21560. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21561. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21562. }
  21563. };
  21564. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21565. var _this = this;
  21566. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21567. var match = regex.exec(sourceCode);
  21568. var returnValue = new String(sourceCode);
  21569. while (match != null) {
  21570. var includeFile = match[1];
  21571. if (Effect.IncludesShadersStore[includeFile]) {
  21572. // Substitution
  21573. var includeContent = Effect.IncludesShadersStore[includeFile];
  21574. if (match[2]) {
  21575. var splits = match[3].split(",");
  21576. for (var index = 0; index < splits.length; index += 2) {
  21577. var source = new RegExp(splits[index], "g");
  21578. var dest = splits[index + 1];
  21579. includeContent = includeContent.replace(source, dest);
  21580. }
  21581. }
  21582. if (match[4]) {
  21583. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  21584. }
  21585. // Replace
  21586. returnValue = returnValue.replace(match[0], includeContent);
  21587. }
  21588. else {
  21589. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21590. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21591. Effect.IncludesShadersStore[includeFile] = fileContent;
  21592. _this._processIncludes(returnValue, callback);
  21593. });
  21594. return;
  21595. }
  21596. match = regex.exec(sourceCode);
  21597. }
  21598. callback(returnValue);
  21599. };
  21600. Effect.prototype._processPrecision = function (source) {
  21601. if (source.indexOf("precision highp float") === -1) {
  21602. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21603. source = "precision mediump float;\n" + source;
  21604. }
  21605. else {
  21606. source = "precision highp float;\n" + source;
  21607. }
  21608. }
  21609. else {
  21610. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21611. source = source.replace("precision highp float", "precision mediump float");
  21612. }
  21613. }
  21614. return source;
  21615. };
  21616. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21617. try {
  21618. var engine = this._engine;
  21619. // Precision
  21620. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21621. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21622. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21624. this._attributes = engine.getAttributes(this._program, attributesNames);
  21625. for (var index = 0; index < this._samplers.length; index++) {
  21626. var sampler = this.getUniform(this._samplers[index]);
  21627. if (sampler == null) {
  21628. this._samplers.splice(index, 1);
  21629. index--;
  21630. }
  21631. }
  21632. engine.bindSamplers(this);
  21633. this._isReady = true;
  21634. if (this.onCompiled) {
  21635. this.onCompiled(this);
  21636. }
  21637. }
  21638. catch (e) {
  21639. // Is it a problem with precision?
  21640. if (e.message.indexOf("highp") !== -1) {
  21641. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21642. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21643. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21644. return;
  21645. }
  21646. // Let's go through fallbacks then
  21647. if (fallbacks && fallbacks.isMoreFallbacks) {
  21648. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21649. this._dumpShadersName();
  21650. defines = fallbacks.reduce(defines);
  21651. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21652. }
  21653. else {
  21654. BABYLON.Tools.Error("Unable to compile effect: ");
  21655. this._dumpShadersName();
  21656. BABYLON.Tools.Error("Defines: " + defines);
  21657. BABYLON.Tools.Error("Error: " + e.message);
  21658. this._compilationError = e.message;
  21659. if (this.onError) {
  21660. this.onError(this, this._compilationError);
  21661. }
  21662. }
  21663. }
  21664. };
  21665. Object.defineProperty(Effect.prototype, "isSupported", {
  21666. get: function () {
  21667. return this._compilationError === "";
  21668. },
  21669. enumerable: true,
  21670. configurable: true
  21671. });
  21672. Effect.prototype._bindTexture = function (channel, texture) {
  21673. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21674. };
  21675. Effect.prototype.setTexture = function (channel, texture) {
  21676. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  21677. };
  21678. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21679. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21680. };
  21681. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21682. if (!this._valueCache[uniformName]) {
  21683. this._valueCache[uniformName] = new BABYLON.Matrix();
  21684. }
  21685. for (var index = 0; index < 16; index++) {
  21686. this._valueCache[uniformName].m[index] = matrix.m[index];
  21687. }
  21688. };
  21689. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21690. if (!this._valueCache[uniformName]) {
  21691. this._valueCache[uniformName] = [x, y];
  21692. return;
  21693. }
  21694. this._valueCache[uniformName][0] = x;
  21695. this._valueCache[uniformName][1] = y;
  21696. };
  21697. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21698. if (!this._valueCache[uniformName]) {
  21699. this._valueCache[uniformName] = [x, y, z];
  21700. return;
  21701. }
  21702. this._valueCache[uniformName][0] = x;
  21703. this._valueCache[uniformName][1] = y;
  21704. this._valueCache[uniformName][2] = z;
  21705. };
  21706. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21707. if (!this._valueCache[uniformName]) {
  21708. this._valueCache[uniformName] = [x, y, z, w];
  21709. return;
  21710. }
  21711. this._valueCache[uniformName][0] = x;
  21712. this._valueCache[uniformName][1] = y;
  21713. this._valueCache[uniformName][2] = z;
  21714. this._valueCache[uniformName][3] = w;
  21715. };
  21716. Effect.prototype.setArray = function (uniformName, array) {
  21717. this._engine.setArray(this.getUniform(uniformName), array);
  21718. return this;
  21719. };
  21720. Effect.prototype.setArray2 = function (uniformName, array) {
  21721. this._engine.setArray2(this.getUniform(uniformName), array);
  21722. return this;
  21723. };
  21724. Effect.prototype.setArray3 = function (uniformName, array) {
  21725. this._engine.setArray3(this.getUniform(uniformName), array);
  21726. return this;
  21727. };
  21728. Effect.prototype.setArray4 = function (uniformName, array) {
  21729. this._engine.setArray4(this.getUniform(uniformName), array);
  21730. return this;
  21731. };
  21732. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21733. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21734. return this;
  21735. };
  21736. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21737. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  21738. // return this;
  21739. // this._cacheMatrix(uniformName, matrix);
  21740. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21741. return this;
  21742. };
  21743. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21744. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21745. return this;
  21746. };
  21747. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  21748. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  21749. return this;
  21750. };
  21751. Effect.prototype.setFloat = function (uniformName, value) {
  21752. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  21753. return this;
  21754. this._valueCache[uniformName] = value;
  21755. this._engine.setFloat(this.getUniform(uniformName), value);
  21756. return this;
  21757. };
  21758. Effect.prototype.setBool = function (uniformName, bool) {
  21759. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  21760. return this;
  21761. this._valueCache[uniformName] = bool;
  21762. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21763. return this;
  21764. };
  21765. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21766. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  21767. return this;
  21768. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  21769. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21770. return this;
  21771. };
  21772. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21773. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  21774. return this;
  21775. this._cacheFloat2(uniformName, x, y);
  21776. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21777. return this;
  21778. };
  21779. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21780. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  21781. return this;
  21782. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  21783. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21784. return this;
  21785. };
  21786. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21787. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  21788. return this;
  21789. this._cacheFloat3(uniformName, x, y, z);
  21790. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21791. return this;
  21792. };
  21793. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21794. 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)
  21795. return this;
  21796. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  21797. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21798. return this;
  21799. };
  21800. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21801. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  21802. return this;
  21803. this._cacheFloat4(uniformName, x, y, z, w);
  21804. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21805. return this;
  21806. };
  21807. Effect.prototype.setColor3 = function (uniformName, color3) {
  21808. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  21809. return this;
  21810. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  21811. this._engine.setColor3(this.getUniform(uniformName), color3);
  21812. return this;
  21813. };
  21814. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21815. 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)
  21816. return this;
  21817. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  21818. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21819. return this;
  21820. };
  21821. // Statics
  21822. Effect.ShadersStore = {};
  21823. Effect.IncludesShadersStore = {};
  21824. return Effect;
  21825. }());
  21826. BABYLON.Effect = Effect;
  21827. })(BABYLON || (BABYLON = {}));
  21828. var BABYLON;
  21829. (function (BABYLON) {
  21830. var maxSimultaneousLights = 4;
  21831. var MaterialHelper = (function () {
  21832. function MaterialHelper() {
  21833. }
  21834. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  21835. var lightIndex = 0;
  21836. var needNormals = false;
  21837. for (var index = 0; index < scene.lights.length; index++) {
  21838. var light = scene.lights[index];
  21839. if (!light.isEnabled()) {
  21840. continue;
  21841. }
  21842. // Excluded check
  21843. if (light._excludedMeshesIds.length > 0) {
  21844. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  21845. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  21846. if (excludedMesh) {
  21847. light.excludedMeshes.push(excludedMesh);
  21848. }
  21849. }
  21850. light._excludedMeshesIds = [];
  21851. }
  21852. // Included check
  21853. if (light._includedOnlyMeshesIds.length > 0) {
  21854. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  21855. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  21856. if (includedOnlyMesh) {
  21857. light.includedOnlyMeshes.push(includedOnlyMesh);
  21858. }
  21859. }
  21860. light._includedOnlyMeshesIds = [];
  21861. }
  21862. if (!light.canAffectMesh(mesh)) {
  21863. continue;
  21864. }
  21865. needNormals = true;
  21866. defines["LIGHT" + lightIndex] = true;
  21867. var type;
  21868. if (light instanceof BABYLON.SpotLight) {
  21869. type = "SPOTLIGHT" + lightIndex;
  21870. }
  21871. else if (light instanceof BABYLON.HemisphericLight) {
  21872. type = "HEMILIGHT" + lightIndex;
  21873. }
  21874. else if (light instanceof BABYLON.PointLight) {
  21875. type = "POINTLIGHT" + lightIndex;
  21876. }
  21877. else {
  21878. type = "DIRLIGHT" + lightIndex;
  21879. }
  21880. defines[type] = true;
  21881. // Specular
  21882. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  21883. defines["SPECULARTERM"] = true;
  21884. }
  21885. // Shadows
  21886. if (scene.shadowsEnabled) {
  21887. var shadowGenerator = light.getShadowGenerator();
  21888. if (mesh && mesh.receiveShadows && shadowGenerator) {
  21889. defines["SHADOW" + lightIndex] = true;
  21890. defines["SHADOWS"] = true;
  21891. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  21892. defines["SHADOWVSM" + lightIndex] = true;
  21893. }
  21894. if (shadowGenerator.usePoissonSampling) {
  21895. defines["SHADOWPCF" + lightIndex] = true;
  21896. }
  21897. }
  21898. }
  21899. lightIndex++;
  21900. if (lightIndex === maxSimultaneousLights)
  21901. break;
  21902. }
  21903. return needNormals;
  21904. };
  21905. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  21906. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  21907. if (!defines["LIGHT" + lightIndex]) {
  21908. continue;
  21909. }
  21910. if (lightIndex > 0) {
  21911. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  21912. }
  21913. if (defines["SHADOW" + lightIndex]) {
  21914. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  21915. }
  21916. if (defines["SHADOWPCF" + lightIndex]) {
  21917. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  21918. }
  21919. if (defines["SHADOWVSM" + lightIndex]) {
  21920. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  21921. }
  21922. }
  21923. };
  21924. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  21925. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  21926. fallbacks.addCPUSkinningFallback(0, mesh);
  21927. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21928. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21929. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  21930. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  21931. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  21932. }
  21933. }
  21934. };
  21935. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  21936. if (defines["INSTANCES"]) {
  21937. attribs.push("world0");
  21938. attribs.push("world1");
  21939. attribs.push("world2");
  21940. attribs.push("world3");
  21941. }
  21942. };
  21943. // Bindings
  21944. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  21945. var shadowGenerator = light.getShadowGenerator();
  21946. if (mesh.receiveShadows && shadowGenerator) {
  21947. if (!light.needCube()) {
  21948. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  21949. }
  21950. else {
  21951. if (!depthValuesAlreadySet) {
  21952. depthValuesAlreadySet = true;
  21953. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  21954. }
  21955. }
  21956. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  21957. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  21958. }
  21959. return depthValuesAlreadySet;
  21960. };
  21961. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  21962. if (light instanceof BABYLON.PointLight) {
  21963. // Point Light
  21964. light.transferToEffect(effect, "vLightData" + lightIndex);
  21965. }
  21966. else if (light instanceof BABYLON.DirectionalLight) {
  21967. // Directional Light
  21968. light.transferToEffect(effect, "vLightData" + lightIndex);
  21969. }
  21970. else if (light instanceof BABYLON.SpotLight) {
  21971. // Spot Light
  21972. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  21973. }
  21974. else if (light instanceof BABYLON.HemisphericLight) {
  21975. // Hemispheric Light
  21976. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  21977. }
  21978. };
  21979. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  21980. var lightIndex = 0;
  21981. var depthValuesAlreadySet = false;
  21982. for (var index = 0; index < scene.lights.length; index++) {
  21983. var light = scene.lights[index];
  21984. if (!light.isEnabled()) {
  21985. continue;
  21986. }
  21987. if (!light.canAffectMesh(mesh)) {
  21988. continue;
  21989. }
  21990. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  21991. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  21992. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  21993. if (defines["SPECULARTERM"]) {
  21994. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  21995. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  21996. }
  21997. // Shadows
  21998. if (scene.shadowsEnabled) {
  21999. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22000. }
  22001. lightIndex++;
  22002. if (lightIndex === maxSimultaneousLights)
  22003. break;
  22004. }
  22005. };
  22006. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22007. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22008. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22009. effect.setColor3("vFogColor", scene.fogColor);
  22010. }
  22011. };
  22012. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22013. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22014. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22015. }
  22016. };
  22017. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22018. if (defines["LOGARITHMICDEPTH"]) {
  22019. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22020. }
  22021. };
  22022. MaterialHelper.BindClipPlane = function (effect, scene) {
  22023. if (scene.clipPlane) {
  22024. var clipPlane = scene.clipPlane;
  22025. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22026. }
  22027. };
  22028. return MaterialHelper;
  22029. }());
  22030. BABYLON.MaterialHelper = MaterialHelper;
  22031. })(BABYLON || (BABYLON = {}));
  22032. var BABYLON;
  22033. (function (BABYLON) {
  22034. var FresnelParameters = (function () {
  22035. function FresnelParameters() {
  22036. this.isEnabled = true;
  22037. this.leftColor = BABYLON.Color3.White();
  22038. this.rightColor = BABYLON.Color3.Black();
  22039. this.bias = 0;
  22040. this.power = 1;
  22041. }
  22042. FresnelParameters.prototype.clone = function () {
  22043. var newFresnelParameters = new FresnelParameters();
  22044. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22045. return new FresnelParameters;
  22046. };
  22047. FresnelParameters.prototype.serialize = function () {
  22048. var serializationObject = {};
  22049. serializationObject.isEnabled = this.isEnabled;
  22050. serializationObject.leftColor = this.leftColor;
  22051. serializationObject.rightColor = this.rightColor;
  22052. serializationObject.bias = this.bias;
  22053. serializationObject.power = this.power;
  22054. return serializationObject;
  22055. };
  22056. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22057. var fresnelParameters = new FresnelParameters();
  22058. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22059. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22060. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22061. fresnelParameters.bias = parsedFresnelParameters.bias;
  22062. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22063. return fresnelParameters;
  22064. };
  22065. return FresnelParameters;
  22066. }());
  22067. BABYLON.FresnelParameters = FresnelParameters;
  22068. })(BABYLON || (BABYLON = {}));
  22069. var BABYLON;
  22070. (function (BABYLON) {
  22071. var MaterialDefines = (function () {
  22072. function MaterialDefines() {
  22073. }
  22074. MaterialDefines.prototype.isEqual = function (other) {
  22075. for (var index = 0; index < this._keys.length; index++) {
  22076. var prop = this._keys[index];
  22077. if (this[prop] !== other[prop]) {
  22078. return false;
  22079. }
  22080. }
  22081. return true;
  22082. };
  22083. MaterialDefines.prototype.cloneTo = function (other) {
  22084. for (var index = 0; index < this._keys.length; index++) {
  22085. var prop = this._keys[index];
  22086. other[prop] = this[prop];
  22087. }
  22088. };
  22089. MaterialDefines.prototype.reset = function () {
  22090. for (var index = 0; index < this._keys.length; index++) {
  22091. var prop = this._keys[index];
  22092. if (typeof (this[prop]) === "number") {
  22093. this[prop] = 0;
  22094. }
  22095. else {
  22096. this[prop] = false;
  22097. }
  22098. }
  22099. };
  22100. MaterialDefines.prototype.toString = function () {
  22101. var result = "";
  22102. for (var index = 0; index < this._keys.length; index++) {
  22103. var prop = this._keys[index];
  22104. if (typeof (this[prop]) === "number") {
  22105. result += "#define " + prop + " " + this[prop] + "\n";
  22106. }
  22107. else if (this[prop]) {
  22108. result += "#define " + prop + "\n";
  22109. }
  22110. }
  22111. return result;
  22112. };
  22113. return MaterialDefines;
  22114. }());
  22115. BABYLON.MaterialDefines = MaterialDefines;
  22116. var Material = (function () {
  22117. function Material(name, scene, doNotAdd) {
  22118. this.name = name;
  22119. this.checkReadyOnEveryCall = false;
  22120. this.checkReadyOnlyOnce = false;
  22121. this.state = "";
  22122. this.alpha = 1.0;
  22123. this.backFaceCulling = true;
  22124. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22125. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22126. this.disableDepthWrite = false;
  22127. this.fogEnabled = true;
  22128. this.pointSize = 1.0;
  22129. this.zOffset = 0;
  22130. this._wasPreviouslyReady = false;
  22131. this._fillMode = Material.TriangleFillMode;
  22132. this.id = name;
  22133. this._scene = scene;
  22134. if (!doNotAdd) {
  22135. scene.materials.push(this);
  22136. }
  22137. }
  22138. Object.defineProperty(Material, "TriangleFillMode", {
  22139. get: function () {
  22140. return Material._TriangleFillMode;
  22141. },
  22142. enumerable: true,
  22143. configurable: true
  22144. });
  22145. Object.defineProperty(Material, "WireFrameFillMode", {
  22146. get: function () {
  22147. return Material._WireFrameFillMode;
  22148. },
  22149. enumerable: true,
  22150. configurable: true
  22151. });
  22152. Object.defineProperty(Material, "PointFillMode", {
  22153. get: function () {
  22154. return Material._PointFillMode;
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22160. get: function () {
  22161. return Material._ClockWiseSideOrientation;
  22162. },
  22163. enumerable: true,
  22164. configurable: true
  22165. });
  22166. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22167. get: function () {
  22168. return Material._CounterClockWiseSideOrientation;
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Object.defineProperty(Material.prototype, "wireframe", {
  22174. get: function () {
  22175. return this._fillMode === Material.WireFrameFillMode;
  22176. },
  22177. set: function (value) {
  22178. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22179. },
  22180. enumerable: true,
  22181. configurable: true
  22182. });
  22183. Object.defineProperty(Material.prototype, "pointsCloud", {
  22184. get: function () {
  22185. return this._fillMode === Material.PointFillMode;
  22186. },
  22187. set: function (value) {
  22188. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22189. },
  22190. enumerable: true,
  22191. configurable: true
  22192. });
  22193. Object.defineProperty(Material.prototype, "fillMode", {
  22194. get: function () {
  22195. return this._fillMode;
  22196. },
  22197. set: function (value) {
  22198. this._fillMode = value;
  22199. },
  22200. enumerable: true,
  22201. configurable: true
  22202. });
  22203. /**
  22204. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22205. * subclasses should override adding information pertainent to themselves
  22206. */
  22207. Material.prototype.toString = function (fullDetails) {
  22208. var ret = "Name: " + this.name;
  22209. if (fullDetails) {
  22210. }
  22211. return ret;
  22212. };
  22213. Object.defineProperty(Material.prototype, "isFrozen", {
  22214. get: function () {
  22215. return this.checkReadyOnlyOnce;
  22216. },
  22217. enumerable: true,
  22218. configurable: true
  22219. });
  22220. Material.prototype.freeze = function () {
  22221. this.checkReadyOnlyOnce = true;
  22222. };
  22223. Material.prototype.unfreeze = function () {
  22224. this.checkReadyOnlyOnce = false;
  22225. };
  22226. Material.prototype.isReady = function (mesh, useInstances) {
  22227. return true;
  22228. };
  22229. Material.prototype.getEffect = function () {
  22230. return this._effect;
  22231. };
  22232. Material.prototype.getScene = function () {
  22233. return this._scene;
  22234. };
  22235. Material.prototype.needAlphaBlending = function () {
  22236. return (this.alpha < 1.0);
  22237. };
  22238. Material.prototype.needAlphaTesting = function () {
  22239. return false;
  22240. };
  22241. Material.prototype.getAlphaTestTexture = function () {
  22242. return null;
  22243. };
  22244. Material.prototype.trackCreation = function (onCompiled, onError) {
  22245. };
  22246. Material.prototype.markDirty = function () {
  22247. this._wasPreviouslyReady = false;
  22248. };
  22249. Material.prototype._preBind = function () {
  22250. var engine = this._scene.getEngine();
  22251. engine.enableEffect(this._effect);
  22252. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22253. };
  22254. Material.prototype.bind = function (world, mesh) {
  22255. this._scene._cachedMaterial = this;
  22256. if (this.onBind) {
  22257. this.onBind(this, mesh);
  22258. }
  22259. if (this.disableDepthWrite) {
  22260. var engine = this._scene.getEngine();
  22261. this._cachedDepthWriteState = engine.getDepthWrite();
  22262. engine.setDepthWrite(false);
  22263. }
  22264. };
  22265. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22266. };
  22267. Material.prototype.unbind = function () {
  22268. if (this.disableDepthWrite) {
  22269. var engine = this._scene.getEngine();
  22270. engine.setDepthWrite(this._cachedDepthWriteState);
  22271. }
  22272. };
  22273. Material.prototype.clone = function (name) {
  22274. return null;
  22275. };
  22276. Material.prototype.getBindedMeshes = function () {
  22277. var result = new Array();
  22278. for (var index = 0; index < this._scene.meshes.length; index++) {
  22279. var mesh = this._scene.meshes[index];
  22280. if (mesh.material === this) {
  22281. result.push(mesh);
  22282. }
  22283. }
  22284. return result;
  22285. };
  22286. Material.prototype.dispose = function (forceDisposeEffect) {
  22287. // Animations
  22288. this.getScene().stopAnimation(this);
  22289. // Remove from scene
  22290. var index = this._scene.materials.indexOf(this);
  22291. if (index >= 0) {
  22292. this._scene.materials.splice(index, 1);
  22293. }
  22294. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22295. if (forceDisposeEffect && this._effect) {
  22296. this._scene.getEngine()._releaseEffect(this._effect);
  22297. this._effect = null;
  22298. }
  22299. // Remove from meshes
  22300. for (index = 0; index < this._scene.meshes.length; index++) {
  22301. var mesh = this._scene.meshes[index];
  22302. if (mesh.material === this) {
  22303. mesh.material = null;
  22304. }
  22305. }
  22306. // Callback
  22307. if (this.onDispose) {
  22308. this.onDispose();
  22309. }
  22310. };
  22311. Material.prototype.serialize = function () {
  22312. return BABYLON.SerializationHelper.Serialize(this);
  22313. };
  22314. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22315. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22316. multiMaterial.id = parsedMultiMaterial.id;
  22317. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22318. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22319. var subMatId = parsedMultiMaterial.materials[matIndex];
  22320. if (subMatId) {
  22321. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22322. }
  22323. else {
  22324. multiMaterial.subMaterials.push(null);
  22325. }
  22326. }
  22327. return multiMaterial;
  22328. };
  22329. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22330. if (!parsedMaterial.customType) {
  22331. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22332. }
  22333. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22334. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22335. ;
  22336. };
  22337. Material._TriangleFillMode = 0;
  22338. Material._WireFrameFillMode = 1;
  22339. Material._PointFillMode = 2;
  22340. Material._ClockWiseSideOrientation = 0;
  22341. Material._CounterClockWiseSideOrientation = 1;
  22342. __decorate([
  22343. BABYLON.serialize()
  22344. ], Material.prototype, "id", void 0);
  22345. __decorate([
  22346. BABYLON.serialize()
  22347. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22348. __decorate([
  22349. BABYLON.serialize()
  22350. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22351. __decorate([
  22352. BABYLON.serialize()
  22353. ], Material.prototype, "state", void 0);
  22354. __decorate([
  22355. BABYLON.serialize()
  22356. ], Material.prototype, "alpha", void 0);
  22357. __decorate([
  22358. BABYLON.serialize()
  22359. ], Material.prototype, "backFaceCulling", void 0);
  22360. __decorate([
  22361. BABYLON.serialize()
  22362. ], Material.prototype, "sideOrientation", void 0);
  22363. __decorate([
  22364. BABYLON.serialize()
  22365. ], Material.prototype, "alphaMode", void 0);
  22366. __decorate([
  22367. BABYLON.serialize()
  22368. ], Material.prototype, "disableDepthWrite", void 0);
  22369. __decorate([
  22370. BABYLON.serialize()
  22371. ], Material.prototype, "fogEnabled", void 0);
  22372. __decorate([
  22373. BABYLON.serialize()
  22374. ], Material.prototype, "pointSize", void 0);
  22375. __decorate([
  22376. BABYLON.serialize()
  22377. ], Material.prototype, "zOffset", void 0);
  22378. __decorate([
  22379. BABYLON.serialize()
  22380. ], Material.prototype, "wireframe", null);
  22381. __decorate([
  22382. BABYLON.serialize()
  22383. ], Material.prototype, "pointsCloud", null);
  22384. __decorate([
  22385. BABYLON.serialize()
  22386. ], Material.prototype, "fillMode", null);
  22387. return Material;
  22388. }());
  22389. BABYLON.Material = Material;
  22390. })(BABYLON || (BABYLON = {}));
  22391. var BABYLON;
  22392. (function (BABYLON) {
  22393. var StandardMaterialDefines = (function (_super) {
  22394. __extends(StandardMaterialDefines, _super);
  22395. function StandardMaterialDefines() {
  22396. _super.call(this);
  22397. this.DIFFUSE = false;
  22398. this.AMBIENT = false;
  22399. this.OPACITY = false;
  22400. this.OPACITYRGB = false;
  22401. this.REFLECTION = false;
  22402. this.EMISSIVE = false;
  22403. this.SPECULAR = false;
  22404. this.BUMP = false;
  22405. this.PARALLAX = false;
  22406. this.PARALLAXOCCLUSION = false;
  22407. this.SPECULAROVERALPHA = false;
  22408. this.CLIPPLANE = false;
  22409. this.ALPHATEST = false;
  22410. this.ALPHAFROMDIFFUSE = false;
  22411. this.POINTSIZE = false;
  22412. this.FOG = false;
  22413. this.LIGHT0 = false;
  22414. this.LIGHT1 = false;
  22415. this.LIGHT2 = false;
  22416. this.LIGHT3 = false;
  22417. this.SPOTLIGHT0 = false;
  22418. this.SPOTLIGHT1 = false;
  22419. this.SPOTLIGHT2 = false;
  22420. this.SPOTLIGHT3 = false;
  22421. this.HEMILIGHT0 = false;
  22422. this.HEMILIGHT1 = false;
  22423. this.HEMILIGHT2 = false;
  22424. this.HEMILIGHT3 = false;
  22425. this.POINTLIGHT0 = false;
  22426. this.POINTLIGHT1 = false;
  22427. this.POINTLIGHT2 = false;
  22428. this.POINTLIGHT3 = false;
  22429. this.DIRLIGHT0 = false;
  22430. this.DIRLIGHT1 = false;
  22431. this.DIRLIGHT2 = false;
  22432. this.DIRLIGHT3 = false;
  22433. this.SPECULARTERM = false;
  22434. this.SHADOW0 = false;
  22435. this.SHADOW1 = false;
  22436. this.SHADOW2 = false;
  22437. this.SHADOW3 = false;
  22438. this.SHADOWS = false;
  22439. this.SHADOWVSM0 = false;
  22440. this.SHADOWVSM1 = false;
  22441. this.SHADOWVSM2 = false;
  22442. this.SHADOWVSM3 = false;
  22443. this.SHADOWPCF0 = false;
  22444. this.SHADOWPCF1 = false;
  22445. this.SHADOWPCF2 = false;
  22446. this.SHADOWPCF3 = false;
  22447. this.DIFFUSEFRESNEL = false;
  22448. this.OPACITYFRESNEL = false;
  22449. this.REFLECTIONFRESNEL = false;
  22450. this.REFRACTIONFRESNEL = false;
  22451. this.EMISSIVEFRESNEL = false;
  22452. this.FRESNEL = false;
  22453. this.NORMAL = false;
  22454. this.UV1 = false;
  22455. this.UV2 = false;
  22456. this.VERTEXCOLOR = false;
  22457. this.VERTEXALPHA = false;
  22458. this.NUM_BONE_INFLUENCERS = 0;
  22459. this.BonesPerMesh = 0;
  22460. this.INSTANCES = false;
  22461. this.GLOSSINESS = false;
  22462. this.ROUGHNESS = false;
  22463. this.EMISSIVEASILLUMINATION = false;
  22464. this.LINKEMISSIVEWITHDIFFUSE = false;
  22465. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22466. this.LIGHTMAP = false;
  22467. this.USELIGHTMAPASSHADOWMAP = false;
  22468. this.REFLECTIONMAP_3D = false;
  22469. this.REFLECTIONMAP_SPHERICAL = false;
  22470. this.REFLECTIONMAP_PLANAR = false;
  22471. this.REFLECTIONMAP_CUBIC = false;
  22472. this.REFLECTIONMAP_PROJECTION = false;
  22473. this.REFLECTIONMAP_SKYBOX = false;
  22474. this.REFLECTIONMAP_EXPLICIT = false;
  22475. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22476. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22477. this.INVERTCUBICMAP = false;
  22478. this.LOGARITHMICDEPTH = false;
  22479. this.REFRACTION = false;
  22480. this.REFRACTIONMAP_3D = false;
  22481. this.REFLECTIONOVERALPHA = false;
  22482. this._keys = Object.keys(this);
  22483. }
  22484. return StandardMaterialDefines;
  22485. }(BABYLON.MaterialDefines));
  22486. var StandardMaterial = (function (_super) {
  22487. __extends(StandardMaterial, _super);
  22488. function StandardMaterial(name, scene) {
  22489. var _this = this;
  22490. _super.call(this, name, scene);
  22491. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22492. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22493. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22494. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22495. this.specularPower = 64;
  22496. this.useAlphaFromDiffuseTexture = false;
  22497. this.useEmissiveAsIllumination = false;
  22498. this.linkEmissiveWithDiffuse = false;
  22499. this.useReflectionFresnelFromSpecular = false;
  22500. this.useSpecularOverAlpha = false;
  22501. this.useReflectionOverAlpha = false;
  22502. this.disableLighting = false;
  22503. this.useParallax = false;
  22504. this.useParallaxOcclusion = false;
  22505. this.parallaxScaleBias = 0.05;
  22506. this.roughness = 0;
  22507. this.indexOfRefraction = 0.98;
  22508. this.invertRefractionY = true;
  22509. this.useLightmapAsShadowmap = false;
  22510. this.useGlossinessFromSpecularMapAlpha = false;
  22511. this._renderTargets = new BABYLON.SmartArray(16);
  22512. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22513. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22514. this._defines = new StandardMaterialDefines();
  22515. this._cachedDefines = new StandardMaterialDefines();
  22516. this._cachedDefines.BonesPerMesh = -1;
  22517. this.getRenderTargetTextures = function () {
  22518. _this._renderTargets.reset();
  22519. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22520. _this._renderTargets.push(_this.reflectionTexture);
  22521. }
  22522. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22523. _this._renderTargets.push(_this.refractionTexture);
  22524. }
  22525. return _this._renderTargets;
  22526. };
  22527. }
  22528. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22529. get: function () {
  22530. return this._useLogarithmicDepth;
  22531. },
  22532. set: function (value) {
  22533. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22534. },
  22535. enumerable: true,
  22536. configurable: true
  22537. });
  22538. StandardMaterial.prototype.needAlphaBlending = function () {
  22539. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22540. };
  22541. StandardMaterial.prototype.needAlphaTesting = function () {
  22542. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22543. };
  22544. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22545. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22546. };
  22547. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22548. return this.diffuseTexture;
  22549. };
  22550. // Methods
  22551. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22552. if (!mesh) {
  22553. return true;
  22554. }
  22555. if (this._defines.INSTANCES !== useInstances) {
  22556. return false;
  22557. }
  22558. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22559. return true;
  22560. }
  22561. return false;
  22562. };
  22563. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22564. if (this.isFrozen) {
  22565. if (this._wasPreviouslyReady) {
  22566. return true;
  22567. }
  22568. }
  22569. var scene = this.getScene();
  22570. if (!this.checkReadyOnEveryCall) {
  22571. if (this._renderId === scene.getRenderId()) {
  22572. if (this._checkCache(scene, mesh, useInstances)) {
  22573. return true;
  22574. }
  22575. }
  22576. }
  22577. var engine = scene.getEngine();
  22578. var needNormals = false;
  22579. var needUVs = false;
  22580. this._defines.reset();
  22581. // Textures
  22582. if (scene.texturesEnabled) {
  22583. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22584. if (!this.diffuseTexture.isReady()) {
  22585. return false;
  22586. }
  22587. else {
  22588. needUVs = true;
  22589. this._defines.DIFFUSE = true;
  22590. }
  22591. }
  22592. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22593. if (!this.ambientTexture.isReady()) {
  22594. return false;
  22595. }
  22596. else {
  22597. needUVs = true;
  22598. this._defines.AMBIENT = true;
  22599. }
  22600. }
  22601. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22602. if (!this.opacityTexture.isReady()) {
  22603. return false;
  22604. }
  22605. else {
  22606. needUVs = true;
  22607. this._defines.OPACITY = true;
  22608. if (this.opacityTexture.getAlphaFromRGB) {
  22609. this._defines.OPACITYRGB = true;
  22610. }
  22611. }
  22612. }
  22613. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22614. if (!this.reflectionTexture.isReady()) {
  22615. return false;
  22616. }
  22617. else {
  22618. needNormals = true;
  22619. this._defines.REFLECTION = true;
  22620. if (this.roughness > 0) {
  22621. this._defines.ROUGHNESS = true;
  22622. }
  22623. if (this.useReflectionOverAlpha) {
  22624. this._defines.REFLECTIONOVERALPHA = true;
  22625. }
  22626. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22627. this._defines.INVERTCUBICMAP = true;
  22628. }
  22629. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22630. switch (this.reflectionTexture.coordinatesMode) {
  22631. case BABYLON.Texture.CUBIC_MODE:
  22632. case BABYLON.Texture.INVCUBIC_MODE:
  22633. this._defines.REFLECTIONMAP_CUBIC = true;
  22634. break;
  22635. case BABYLON.Texture.EXPLICIT_MODE:
  22636. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22637. break;
  22638. case BABYLON.Texture.PLANAR_MODE:
  22639. this._defines.REFLECTIONMAP_PLANAR = true;
  22640. break;
  22641. case BABYLON.Texture.PROJECTION_MODE:
  22642. this._defines.REFLECTIONMAP_PROJECTION = true;
  22643. break;
  22644. case BABYLON.Texture.SKYBOX_MODE:
  22645. this._defines.REFLECTIONMAP_SKYBOX = true;
  22646. break;
  22647. case BABYLON.Texture.SPHERICAL_MODE:
  22648. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22649. break;
  22650. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22651. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22652. break;
  22653. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22654. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22655. break;
  22656. }
  22657. }
  22658. }
  22659. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22660. if (!this.emissiveTexture.isReady()) {
  22661. return false;
  22662. }
  22663. else {
  22664. needUVs = true;
  22665. this._defines.EMISSIVE = true;
  22666. }
  22667. }
  22668. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22669. if (!this.lightmapTexture.isReady()) {
  22670. return false;
  22671. }
  22672. else {
  22673. needUVs = true;
  22674. this._defines.LIGHTMAP = true;
  22675. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  22676. }
  22677. }
  22678. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22679. if (!this.specularTexture.isReady()) {
  22680. return false;
  22681. }
  22682. else {
  22683. needUVs = true;
  22684. this._defines.SPECULAR = true;
  22685. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  22686. }
  22687. }
  22688. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  22689. if (!this.bumpTexture.isReady()) {
  22690. return false;
  22691. }
  22692. else {
  22693. needUVs = true;
  22694. this._defines.BUMP = true;
  22695. if (this.useParallax) {
  22696. this._defines.PARALLAX = true;
  22697. if (this.useParallaxOcclusion) {
  22698. this._defines.PARALLAXOCCLUSION = true;
  22699. }
  22700. }
  22701. }
  22702. }
  22703. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22704. if (!this.refractionTexture.isReady()) {
  22705. return false;
  22706. }
  22707. else {
  22708. needUVs = true;
  22709. this._defines.REFRACTION = true;
  22710. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  22711. }
  22712. }
  22713. }
  22714. // Effect
  22715. if (scene.clipPlane) {
  22716. this._defines.CLIPPLANE = true;
  22717. }
  22718. if (engine.getAlphaTesting()) {
  22719. this._defines.ALPHATEST = true;
  22720. }
  22721. if (this._shouldUseAlphaFromDiffuseTexture()) {
  22722. this._defines.ALPHAFROMDIFFUSE = true;
  22723. }
  22724. if (this.useEmissiveAsIllumination) {
  22725. this._defines.EMISSIVEASILLUMINATION = true;
  22726. }
  22727. if (this.linkEmissiveWithDiffuse) {
  22728. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  22729. }
  22730. if (this.useLogarithmicDepth) {
  22731. this._defines.LOGARITHMICDEPTH = true;
  22732. }
  22733. // Point size
  22734. if (this.pointsCloud || scene.forcePointsCloud) {
  22735. this._defines.POINTSIZE = true;
  22736. }
  22737. // Fog
  22738. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22739. this._defines.FOG = true;
  22740. }
  22741. if (scene.lightsEnabled && !this.disableLighting) {
  22742. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  22743. }
  22744. if (StandardMaterial.FresnelEnabled) {
  22745. // Fresnel
  22746. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  22747. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  22748. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  22749. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  22750. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22751. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22752. this._defines.DIFFUSEFRESNEL = true;
  22753. }
  22754. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22755. this._defines.OPACITYFRESNEL = true;
  22756. }
  22757. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22758. this._defines.REFLECTIONFRESNEL = true;
  22759. if (this.useReflectionFresnelFromSpecular) {
  22760. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  22761. }
  22762. }
  22763. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22764. this._defines.REFRACTIONFRESNEL = true;
  22765. }
  22766. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22767. this._defines.EMISSIVEFRESNEL = true;
  22768. }
  22769. needNormals = true;
  22770. this._defines.FRESNEL = true;
  22771. }
  22772. }
  22773. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  22774. this._defines.SPECULAROVERALPHA = true;
  22775. }
  22776. // Attribs
  22777. if (mesh) {
  22778. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22779. this._defines.NORMAL = true;
  22780. }
  22781. if (needUVs) {
  22782. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22783. this._defines.UV1 = true;
  22784. }
  22785. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22786. this._defines.UV2 = true;
  22787. }
  22788. }
  22789. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22790. this._defines.VERTEXCOLOR = true;
  22791. if (mesh.hasVertexAlpha) {
  22792. this._defines.VERTEXALPHA = true;
  22793. }
  22794. }
  22795. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22796. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  22797. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  22798. }
  22799. // Instances
  22800. if (useInstances) {
  22801. this._defines.INSTANCES = true;
  22802. }
  22803. }
  22804. // Get correct effect
  22805. if (!this._defines.isEqual(this._cachedDefines)) {
  22806. this._defines.cloneTo(this._cachedDefines);
  22807. scene.resetCachedMaterial();
  22808. // Fallbacks
  22809. var fallbacks = new BABYLON.EffectFallbacks();
  22810. if (this._defines.REFLECTION) {
  22811. fallbacks.addFallback(0, "REFLECTION");
  22812. }
  22813. if (this._defines.SPECULAR) {
  22814. fallbacks.addFallback(0, "SPECULAR");
  22815. }
  22816. if (this._defines.BUMP) {
  22817. fallbacks.addFallback(0, "BUMP");
  22818. }
  22819. if (this._defines.PARALLAX) {
  22820. fallbacks.addFallback(1, "PARALLAX");
  22821. }
  22822. if (this._defines.PARALLAXOCCLUSION) {
  22823. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  22824. }
  22825. if (this._defines.SPECULAROVERALPHA) {
  22826. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  22827. }
  22828. if (this._defines.FOG) {
  22829. fallbacks.addFallback(1, "FOG");
  22830. }
  22831. if (this._defines.POINTSIZE) {
  22832. fallbacks.addFallback(0, "POINTSIZE");
  22833. }
  22834. if (this._defines.LOGARITHMICDEPTH) {
  22835. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  22836. }
  22837. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  22838. if (this._defines.SPECULARTERM) {
  22839. fallbacks.addFallback(0, "SPECULARTERM");
  22840. }
  22841. if (this._defines.DIFFUSEFRESNEL) {
  22842. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  22843. }
  22844. if (this._defines.OPACITYFRESNEL) {
  22845. fallbacks.addFallback(2, "OPACITYFRESNEL");
  22846. }
  22847. if (this._defines.REFLECTIONFRESNEL) {
  22848. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  22849. }
  22850. if (this._defines.EMISSIVEFRESNEL) {
  22851. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  22852. }
  22853. if (this._defines.FRESNEL) {
  22854. fallbacks.addFallback(4, "FRESNEL");
  22855. }
  22856. //Attributes
  22857. var attribs = [BABYLON.VertexBuffer.PositionKind];
  22858. if (this._defines.NORMAL) {
  22859. attribs.push(BABYLON.VertexBuffer.NormalKind);
  22860. }
  22861. if (this._defines.UV1) {
  22862. attribs.push(BABYLON.VertexBuffer.UVKind);
  22863. }
  22864. if (this._defines.UV2) {
  22865. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  22866. }
  22867. if (this._defines.VERTEXCOLOR) {
  22868. attribs.push(BABYLON.VertexBuffer.ColorKind);
  22869. }
  22870. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  22871. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  22872. // Legacy browser patch
  22873. var shaderName = "default";
  22874. if (!scene.getEngine().getCaps().standardDerivatives) {
  22875. shaderName = "legacydefault";
  22876. }
  22877. var join = this._defines.toString();
  22878. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  22879. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  22880. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  22881. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  22882. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  22883. "vFogInfos", "vFogColor", "pointSize",
  22884. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  22885. "mBones",
  22886. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  22887. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  22888. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  22889. "logarithmicDepthConstant"
  22890. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  22891. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  22892. ], join, fallbacks, this.onCompiled, this.onError);
  22893. }
  22894. if (!this._effect.isReady()) {
  22895. return false;
  22896. }
  22897. this._renderId = scene.getRenderId();
  22898. this._wasPreviouslyReady = true;
  22899. if (mesh) {
  22900. if (!mesh._materialDefines) {
  22901. mesh._materialDefines = new StandardMaterialDefines();
  22902. }
  22903. this._defines.cloneTo(mesh._materialDefines);
  22904. }
  22905. return true;
  22906. };
  22907. StandardMaterial.prototype.unbind = function () {
  22908. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  22909. this._effect.setTexture("reflection2DSampler", null);
  22910. }
  22911. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  22912. this._effect.setTexture("refraction2DSampler", null);
  22913. }
  22914. _super.prototype.unbind.call(this);
  22915. };
  22916. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22917. this._effect.setMatrix("world", world);
  22918. };
  22919. StandardMaterial.prototype.bind = function (world, mesh) {
  22920. var scene = this.getScene();
  22921. // Matrices
  22922. this.bindOnlyWorldMatrix(world);
  22923. // Bones
  22924. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  22925. if (scene.getCachedMaterial() !== this) {
  22926. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  22927. if (StandardMaterial.FresnelEnabled) {
  22928. // Fresnel
  22929. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22930. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  22931. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  22932. }
  22933. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22934. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  22935. }
  22936. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22937. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  22938. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  22939. }
  22940. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22941. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  22942. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  22943. }
  22944. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22945. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  22946. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  22947. }
  22948. }
  22949. // Textures
  22950. if (scene.texturesEnabled) {
  22951. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22952. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  22953. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  22954. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  22955. }
  22956. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22957. this._effect.setTexture("ambientSampler", this.ambientTexture);
  22958. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  22959. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  22960. }
  22961. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22962. this._effect.setTexture("opacitySampler", this.opacityTexture);
  22963. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  22964. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  22965. }
  22966. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22967. if (this.reflectionTexture.isCube) {
  22968. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  22969. }
  22970. else {
  22971. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  22972. }
  22973. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  22974. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  22975. }
  22976. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22977. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  22978. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  22979. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  22980. }
  22981. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22982. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  22983. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  22984. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  22985. }
  22986. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22987. this._effect.setTexture("specularSampler", this.specularTexture);
  22988. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  22989. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  22990. }
  22991. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  22992. this._effect.setTexture("bumpSampler", this.bumpTexture);
  22993. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  22994. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  22995. }
  22996. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22997. var depth = 1.0;
  22998. if (this.refractionTexture.isCube) {
  22999. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23000. }
  23001. else {
  23002. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23003. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23004. if (this.refractionTexture.depth) {
  23005. depth = this.refractionTexture.depth;
  23006. }
  23007. }
  23008. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23009. }
  23010. }
  23011. // Clip plane
  23012. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23013. // Point size
  23014. if (this.pointsCloud) {
  23015. this._effect.setFloat("pointSize", this.pointSize);
  23016. }
  23017. // Colors
  23018. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23019. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23020. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23021. if (this._defines.SPECULARTERM) {
  23022. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23023. }
  23024. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23025. }
  23026. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23027. // Diffuse
  23028. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23029. // Lights
  23030. if (scene.lightsEnabled && !this.disableLighting) {
  23031. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  23032. }
  23033. // View
  23034. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23035. this._effect.setMatrix("view", scene.getViewMatrix());
  23036. }
  23037. // Fog
  23038. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23039. // Log. depth
  23040. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23041. }
  23042. _super.prototype.bind.call(this, world, mesh);
  23043. };
  23044. StandardMaterial.prototype.getAnimatables = function () {
  23045. var results = [];
  23046. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23047. results.push(this.diffuseTexture);
  23048. }
  23049. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23050. results.push(this.ambientTexture);
  23051. }
  23052. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23053. results.push(this.opacityTexture);
  23054. }
  23055. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23056. results.push(this.reflectionTexture);
  23057. }
  23058. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23059. results.push(this.emissiveTexture);
  23060. }
  23061. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23062. results.push(this.specularTexture);
  23063. }
  23064. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23065. results.push(this.bumpTexture);
  23066. }
  23067. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23068. results.push(this.lightmapTexture);
  23069. }
  23070. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23071. results.push(this.refractionTexture);
  23072. }
  23073. return results;
  23074. };
  23075. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  23076. if (this.diffuseTexture) {
  23077. this.diffuseTexture.dispose();
  23078. }
  23079. if (this.ambientTexture) {
  23080. this.ambientTexture.dispose();
  23081. }
  23082. if (this.opacityTexture) {
  23083. this.opacityTexture.dispose();
  23084. }
  23085. if (this.reflectionTexture) {
  23086. this.reflectionTexture.dispose();
  23087. }
  23088. if (this.emissiveTexture) {
  23089. this.emissiveTexture.dispose();
  23090. }
  23091. if (this.specularTexture) {
  23092. this.specularTexture.dispose();
  23093. }
  23094. if (this.bumpTexture) {
  23095. this.bumpTexture.dispose();
  23096. }
  23097. if (this.lightmapTexture) {
  23098. this.lightmapTexture.dispose();
  23099. }
  23100. if (this.refractionTexture) {
  23101. this.refractionTexture.dispose();
  23102. }
  23103. _super.prototype.dispose.call(this, forceDisposeEffect);
  23104. };
  23105. StandardMaterial.prototype.clone = function (name) {
  23106. var _this = this;
  23107. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23108. };
  23109. StandardMaterial.prototype.serialize = function () {
  23110. return BABYLON.SerializationHelper.Serialize(this);
  23111. };
  23112. // Statics
  23113. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23114. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23115. };
  23116. // Flags used to enable or disable a type of texture for all Standard Materials
  23117. StandardMaterial.DiffuseTextureEnabled = true;
  23118. StandardMaterial.AmbientTextureEnabled = true;
  23119. StandardMaterial.OpacityTextureEnabled = true;
  23120. StandardMaterial.ReflectionTextureEnabled = true;
  23121. StandardMaterial.EmissiveTextureEnabled = true;
  23122. StandardMaterial.SpecularTextureEnabled = true;
  23123. StandardMaterial.BumpTextureEnabled = true;
  23124. StandardMaterial.FresnelEnabled = true;
  23125. StandardMaterial.LightmapTextureEnabled = true;
  23126. StandardMaterial.RefractionTextureEnabled = true;
  23127. __decorate([
  23128. BABYLON.serializeAsTexture()
  23129. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23130. __decorate([
  23131. BABYLON.serializeAsTexture()
  23132. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23133. __decorate([
  23134. BABYLON.serializeAsTexture()
  23135. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23136. __decorate([
  23137. BABYLON.serializeAsTexture()
  23138. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23139. __decorate([
  23140. BABYLON.serializeAsTexture()
  23141. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23142. __decorate([
  23143. BABYLON.serializeAsTexture()
  23144. ], StandardMaterial.prototype, "specularTexture", void 0);
  23145. __decorate([
  23146. BABYLON.serializeAsTexture()
  23147. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23148. __decorate([
  23149. BABYLON.serializeAsTexture()
  23150. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23151. __decorate([
  23152. BABYLON.serializeAsTexture()
  23153. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23154. __decorate([
  23155. BABYLON.serializeAsColor3("ambient")
  23156. ], StandardMaterial.prototype, "ambientColor", void 0);
  23157. __decorate([
  23158. BABYLON.serializeAsColor3("diffuse")
  23159. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23160. __decorate([
  23161. BABYLON.serializeAsColor3("specular")
  23162. ], StandardMaterial.prototype, "specularColor", void 0);
  23163. __decorate([
  23164. BABYLON.serializeAsColor3("emissive")
  23165. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23166. __decorate([
  23167. BABYLON.serialize()
  23168. ], StandardMaterial.prototype, "specularPower", void 0);
  23169. __decorate([
  23170. BABYLON.serialize()
  23171. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23172. __decorate([
  23173. BABYLON.serialize()
  23174. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23175. __decorate([
  23176. BABYLON.serialize()
  23177. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23178. __decorate([
  23179. BABYLON.serialize()
  23180. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23181. __decorate([
  23182. BABYLON.serialize()
  23183. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23184. __decorate([
  23185. BABYLON.serialize()
  23186. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23187. __decorate([
  23188. BABYLON.serialize()
  23189. ], StandardMaterial.prototype, "disableLighting", void 0);
  23190. __decorate([
  23191. BABYLON.serialize()
  23192. ], StandardMaterial.prototype, "useParallax", void 0);
  23193. __decorate([
  23194. BABYLON.serialize()
  23195. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23196. __decorate([
  23197. BABYLON.serialize()
  23198. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23199. __decorate([
  23200. BABYLON.serialize()
  23201. ], StandardMaterial.prototype, "roughness", void 0);
  23202. __decorate([
  23203. BABYLON.serialize()
  23204. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23205. __decorate([
  23206. BABYLON.serialize()
  23207. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23208. __decorate([
  23209. BABYLON.serialize()
  23210. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23211. __decorate([
  23212. BABYLON.serializeAsFresnelParameters()
  23213. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23214. __decorate([
  23215. BABYLON.serializeAsFresnelParameters()
  23216. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23217. __decorate([
  23218. BABYLON.serializeAsFresnelParameters()
  23219. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23220. __decorate([
  23221. BABYLON.serializeAsFresnelParameters()
  23222. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23223. __decorate([
  23224. BABYLON.serializeAsFresnelParameters()
  23225. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23226. __decorate([
  23227. BABYLON.serialize()
  23228. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23229. __decorate([
  23230. BABYLON.serialize()
  23231. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23232. return StandardMaterial;
  23233. }(BABYLON.Material));
  23234. BABYLON.StandardMaterial = StandardMaterial;
  23235. })(BABYLON || (BABYLON = {}));
  23236. var BABYLON;
  23237. (function (BABYLON) {
  23238. var MultiMaterial = (function (_super) {
  23239. __extends(MultiMaterial, _super);
  23240. function MultiMaterial(name, scene) {
  23241. _super.call(this, name, scene, true);
  23242. this.subMaterials = new Array();
  23243. scene.multiMaterials.push(this);
  23244. }
  23245. // Properties
  23246. MultiMaterial.prototype.getSubMaterial = function (index) {
  23247. if (index < 0 || index >= this.subMaterials.length) {
  23248. return this.getScene().defaultMaterial;
  23249. }
  23250. return this.subMaterials[index];
  23251. };
  23252. // Methods
  23253. MultiMaterial.prototype.isReady = function (mesh) {
  23254. for (var index = 0; index < this.subMaterials.length; index++) {
  23255. var subMaterial = this.subMaterials[index];
  23256. if (subMaterial) {
  23257. if (!this.subMaterials[index].isReady(mesh)) {
  23258. return false;
  23259. }
  23260. }
  23261. }
  23262. return true;
  23263. };
  23264. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23265. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23266. for (var index = 0; index < this.subMaterials.length; index++) {
  23267. var subMaterial = null;
  23268. if (cloneChildren) {
  23269. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23270. }
  23271. else {
  23272. subMaterial = this.subMaterials[index];
  23273. }
  23274. newMultiMaterial.subMaterials.push(subMaterial);
  23275. }
  23276. return newMultiMaterial;
  23277. };
  23278. MultiMaterial.prototype.serialize = function () {
  23279. var serializationObject = {};
  23280. serializationObject.name = this.name;
  23281. serializationObject.id = this.id;
  23282. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23283. serializationObject.materials = [];
  23284. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23285. var subMat = this.subMaterials[matIndex];
  23286. if (subMat) {
  23287. serializationObject.materials.push(subMat.id);
  23288. }
  23289. else {
  23290. serializationObject.materials.push(null);
  23291. }
  23292. }
  23293. return serializationObject;
  23294. };
  23295. return MultiMaterial;
  23296. }(BABYLON.Material));
  23297. BABYLON.MultiMaterial = MultiMaterial;
  23298. })(BABYLON || (BABYLON = {}));
  23299. var BABYLON;
  23300. (function (BABYLON) {
  23301. var SceneLoader = (function () {
  23302. function SceneLoader() {
  23303. }
  23304. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23305. get: function () {
  23306. return 0;
  23307. },
  23308. enumerable: true,
  23309. configurable: true
  23310. });
  23311. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23312. get: function () {
  23313. return 1;
  23314. },
  23315. enumerable: true,
  23316. configurable: true
  23317. });
  23318. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23319. get: function () {
  23320. return 2;
  23321. },
  23322. enumerable: true,
  23323. configurable: true
  23324. });
  23325. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23326. get: function () {
  23327. return 3;
  23328. },
  23329. enumerable: true,
  23330. configurable: true
  23331. });
  23332. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23333. get: function () {
  23334. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23335. },
  23336. set: function (value) {
  23337. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23338. },
  23339. enumerable: true,
  23340. configurable: true
  23341. });
  23342. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23343. get: function () {
  23344. return SceneLoader._ShowLoadingScreen;
  23345. },
  23346. set: function (value) {
  23347. SceneLoader._ShowLoadingScreen = value;
  23348. },
  23349. enumerable: true,
  23350. configurable: true
  23351. });
  23352. Object.defineProperty(SceneLoader, "loggingLevel", {
  23353. get: function () {
  23354. return SceneLoader._loggingLevel;
  23355. },
  23356. set: function (value) {
  23357. SceneLoader._loggingLevel = value;
  23358. },
  23359. enumerable: true,
  23360. configurable: true
  23361. });
  23362. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23363. var dotPosition = sceneFilename.lastIndexOf(".");
  23364. var queryStringPosition = sceneFilename.indexOf("?");
  23365. if (queryStringPosition === -1) {
  23366. queryStringPosition = sceneFilename.length;
  23367. }
  23368. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23369. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23370. var plugin = this._registeredPlugins[index];
  23371. if (plugin.extensions.indexOf(extension) !== -1) {
  23372. return plugin;
  23373. }
  23374. }
  23375. return this._registeredPlugins[this._registeredPlugins.length - 1];
  23376. };
  23377. // Public functions
  23378. SceneLoader.GetPluginForExtension = function (extension) {
  23379. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23380. var plugin = this._registeredPlugins[index];
  23381. if (plugin.extensions.indexOf(extension) !== -1) {
  23382. return plugin;
  23383. }
  23384. }
  23385. return null;
  23386. };
  23387. SceneLoader.RegisterPlugin = function (plugin) {
  23388. plugin.extensions = plugin.extensions.toLowerCase();
  23389. SceneLoader._registeredPlugins.push(plugin);
  23390. };
  23391. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23392. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23393. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23394. return;
  23395. }
  23396. var loadingToken = {};
  23397. scene._addPendingData(loadingToken);
  23398. var manifestChecked = function (success) {
  23399. scene.database = database;
  23400. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23401. var importMeshFromData = function (data) {
  23402. var meshes = [];
  23403. var particleSystems = [];
  23404. var skeletons = [];
  23405. try {
  23406. if (plugin.importMesh) {
  23407. var syncedPlugin = plugin;
  23408. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23409. if (onerror) {
  23410. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23411. }
  23412. scene._removePendingData(loadingToken);
  23413. return;
  23414. }
  23415. if (onsuccess) {
  23416. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23417. onsuccess(meshes, particleSystems, skeletons);
  23418. scene._removePendingData(loadingToken);
  23419. }
  23420. }
  23421. else {
  23422. var asyncedPlugin = plugin;
  23423. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23424. if (onsuccess) {
  23425. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23426. onsuccess(meshes, particleSystems, skeletons);
  23427. scene._removePendingData(loadingToken);
  23428. }
  23429. }, function () {
  23430. if (onerror) {
  23431. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23432. }
  23433. scene._removePendingData(loadingToken);
  23434. });
  23435. }
  23436. }
  23437. catch (e) {
  23438. if (onerror) {
  23439. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  23440. }
  23441. scene._removePendingData(loadingToken);
  23442. }
  23443. };
  23444. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23445. // Direct load
  23446. importMeshFromData(sceneFilename.substr(5));
  23447. return;
  23448. }
  23449. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23450. importMeshFromData(data);
  23451. }, progressCallBack, database);
  23452. };
  23453. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23454. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23455. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23456. }
  23457. else {
  23458. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23459. manifestChecked(true);
  23460. }
  23461. };
  23462. /**
  23463. * Load a scene
  23464. * @param rootUrl a string that defines the root url for scene and resources
  23465. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23466. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23467. */
  23468. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23469. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23470. };
  23471. /**
  23472. * Append a scene
  23473. * @param rootUrl a string that defines the root url for scene and resources
  23474. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23475. * @param scene is the instance of BABYLON.Scene to append to
  23476. */
  23477. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23478. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23479. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23480. return;
  23481. }
  23482. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23483. var database;
  23484. var loadingToken = {};
  23485. scene._addPendingData(loadingToken);
  23486. if (SceneLoader.ShowLoadingScreen) {
  23487. scene.getEngine().displayLoadingUI();
  23488. }
  23489. var loadSceneFromData = function (data) {
  23490. scene.database = database;
  23491. if (plugin.load) {
  23492. var syncedPlugin = plugin;
  23493. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23494. if (onerror) {
  23495. onerror(scene);
  23496. }
  23497. scene._removePendingData(loadingToken);
  23498. scene.getEngine().hideLoadingUI();
  23499. return;
  23500. }
  23501. if (onsuccess) {
  23502. onsuccess(scene);
  23503. }
  23504. scene._removePendingData(loadingToken);
  23505. }
  23506. else {
  23507. var asyncedPlugin = plugin;
  23508. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23509. if (onsuccess) {
  23510. onsuccess(scene);
  23511. }
  23512. }, function () {
  23513. if (onerror) {
  23514. onerror(scene);
  23515. }
  23516. scene._removePendingData(loadingToken);
  23517. scene.getEngine().hideLoadingUI();
  23518. });
  23519. }
  23520. if (SceneLoader.ShowLoadingScreen) {
  23521. scene.executeWhenReady(function () {
  23522. scene.getEngine().hideLoadingUI();
  23523. });
  23524. }
  23525. };
  23526. var manifestChecked = function (success) {
  23527. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23528. };
  23529. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23530. // Direct load
  23531. loadSceneFromData(sceneFilename.substr(5));
  23532. return;
  23533. }
  23534. if (rootUrl.indexOf("file:") === -1) {
  23535. if (scene.getEngine().enableOfflineSupport) {
  23536. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23537. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23538. }
  23539. else {
  23540. manifestChecked(true);
  23541. }
  23542. }
  23543. else {
  23544. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23545. }
  23546. };
  23547. // Flags
  23548. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23549. SceneLoader._ShowLoadingScreen = true;
  23550. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23551. // Members
  23552. SceneLoader._registeredPlugins = new Array();
  23553. return SceneLoader;
  23554. }());
  23555. BABYLON.SceneLoader = SceneLoader;
  23556. ;
  23557. })(BABYLON || (BABYLON = {}));
  23558. var BABYLON;
  23559. (function (BABYLON) {
  23560. var Internals;
  23561. (function (Internals) {
  23562. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23563. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23564. var parsedMaterial = parsedData.materials[index];
  23565. if (parsedMaterial.id === id) {
  23566. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23567. }
  23568. }
  23569. return null;
  23570. };
  23571. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23572. names = (names instanceof Array) ? names : [names];
  23573. for (var i in names) {
  23574. if (mesh.name === names[i]) {
  23575. hierarchyIds.push(mesh.id);
  23576. return true;
  23577. }
  23578. }
  23579. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23580. hierarchyIds.push(mesh.id);
  23581. return true;
  23582. }
  23583. return false;
  23584. };
  23585. var logOperation = function (operation, producer) {
  23586. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23587. };
  23588. BABYLON.SceneLoader.RegisterPlugin({
  23589. extensions: ".babylon",
  23590. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23591. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23592. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23593. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23594. // and avoid problems with multiple concurrent .babylon loads.
  23595. var log = "importMesh has failed JSON parse";
  23596. try {
  23597. var parsedData = JSON.parse(data);
  23598. log = "";
  23599. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23600. var loadedSkeletonsIds = [];
  23601. var loadedMaterialsIds = [];
  23602. var hierarchyIds = [];
  23603. var index;
  23604. var cache;
  23605. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23606. var parsedMesh = parsedData.meshes[index];
  23607. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23608. if (meshesNames instanceof Array) {
  23609. // Remove found mesh name from list.
  23610. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23611. }
  23612. //Geometry?
  23613. if (parsedMesh.geometryId) {
  23614. //does the file contain geometries?
  23615. if (parsedData.geometries) {
  23616. //find the correct geometry and add it to the scene
  23617. var found = false;
  23618. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23619. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23620. return;
  23621. }
  23622. else {
  23623. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23624. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23625. switch (geometryType) {
  23626. case "boxes":
  23627. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23628. break;
  23629. case "spheres":
  23630. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23631. break;
  23632. case "cylinders":
  23633. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23634. break;
  23635. case "toruses":
  23636. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23637. break;
  23638. case "grounds":
  23639. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23640. break;
  23641. case "planes":
  23642. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23643. break;
  23644. case "torusKnots":
  23645. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23646. break;
  23647. case "vertexData":
  23648. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23649. break;
  23650. }
  23651. found = true;
  23652. }
  23653. });
  23654. }
  23655. });
  23656. if (!found) {
  23657. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  23658. }
  23659. }
  23660. }
  23661. // Material ?
  23662. if (parsedMesh.materialId) {
  23663. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  23664. if (!materialFound && parsedData.multiMaterials) {
  23665. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  23666. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  23667. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  23668. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  23669. var subMatId = parsedMultiMaterial.materials[matIndex];
  23670. loadedMaterialsIds.push(subMatId);
  23671. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  23672. log += "\n\tMaterial " + mat.toString(fullDetails);
  23673. }
  23674. loadedMaterialsIds.push(parsedMultiMaterial.id);
  23675. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23676. materialFound = true;
  23677. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  23678. break;
  23679. }
  23680. }
  23681. }
  23682. if (!materialFound) {
  23683. loadedMaterialsIds.push(parsedMesh.materialId);
  23684. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  23685. if (!mat) {
  23686. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  23687. }
  23688. else {
  23689. log += "\n\tMaterial " + mat.toString(fullDetails);
  23690. }
  23691. }
  23692. }
  23693. // Skeleton ?
  23694. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  23695. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  23696. if (!skeletonAlreadyLoaded) {
  23697. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  23698. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  23699. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  23700. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23701. skeletons.push(skeleton);
  23702. loadedSkeletonsIds.push(parsedSkeleton.id);
  23703. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  23704. }
  23705. }
  23706. }
  23707. }
  23708. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23709. meshes.push(mesh);
  23710. log += "\n\tMesh " + mesh.toString(fullDetails);
  23711. }
  23712. }
  23713. // Connecting parents
  23714. var currentMesh;
  23715. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23716. currentMesh = scene.meshes[index];
  23717. if (currentMesh._waitingParentId) {
  23718. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  23719. currentMesh._waitingParentId = undefined;
  23720. }
  23721. }
  23722. // freeze and compute world matrix application
  23723. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23724. currentMesh = scene.meshes[index];
  23725. if (currentMesh._waitingFreezeWorldMatrix) {
  23726. currentMesh.freezeWorldMatrix();
  23727. currentMesh._waitingFreezeWorldMatrix = undefined;
  23728. }
  23729. else {
  23730. currentMesh.computeWorldMatrix(true);
  23731. }
  23732. }
  23733. // Particles
  23734. if (parsedData.particleSystems) {
  23735. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  23736. var parsedParticleSystem = parsedData.particleSystems[index];
  23737. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  23738. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  23739. }
  23740. }
  23741. }
  23742. return true;
  23743. }
  23744. catch (err) {
  23745. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  23746. log = null;
  23747. throw err;
  23748. }
  23749. finally {
  23750. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  23751. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  23752. }
  23753. }
  23754. },
  23755. load: function (scene, data, rootUrl) {
  23756. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23757. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23758. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23759. // and avoid problems with multiple concurrent .babylon loads.
  23760. var log = "importScene has failed JSON parse";
  23761. try {
  23762. var parsedData = JSON.parse(data);
  23763. log = "";
  23764. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23765. // Scene
  23766. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  23767. scene.autoClear = parsedData.autoClear;
  23768. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  23769. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  23770. if (parsedData.gravity) {
  23771. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  23772. }
  23773. // Fog
  23774. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  23775. scene.fogMode = parsedData.fogMode;
  23776. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  23777. scene.fogStart = parsedData.fogStart;
  23778. scene.fogEnd = parsedData.fogEnd;
  23779. scene.fogDensity = parsedData.fogDensity;
  23780. log += "\tFog mode for scene: ";
  23781. switch (scene.fogMode) {
  23782. // getters not compiling, so using hardcoded
  23783. case 1:
  23784. log += "exp\n";
  23785. break;
  23786. case 2:
  23787. log += "exp2\n";
  23788. break;
  23789. case 3:
  23790. log += "linear\n";
  23791. break;
  23792. }
  23793. }
  23794. //Physics
  23795. if (parsedData.physicsEnabled) {
  23796. var physicsPlugin;
  23797. if (parsedData.physicsEngine === "cannon") {
  23798. physicsPlugin = new BABYLON.CannonJSPlugin();
  23799. }
  23800. else if (parsedData.physicsEngine === "oimo") {
  23801. physicsPlugin = new BABYLON.OimoJSPlugin();
  23802. }
  23803. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  23804. //else - default engine, which is currently oimo
  23805. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  23806. scene.enablePhysics(physicsGravity, physicsPlugin);
  23807. }
  23808. //collisions, if defined. otherwise, default is true
  23809. if (parsedData.collisionsEnabled != undefined) {
  23810. scene.collisionsEnabled = parsedData.collisionsEnabled;
  23811. }
  23812. scene.workerCollisions = !!parsedData.workerCollisions;
  23813. var index;
  23814. var cache;
  23815. // Lights
  23816. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  23817. var parsedLight = parsedData.lights[index];
  23818. var light = BABYLON.Light.Parse(parsedLight, scene);
  23819. log += (index === 0 ? "\n\tLights:" : "");
  23820. log += "\n\t\t" + light.toString(fullDetails);
  23821. }
  23822. // Animations
  23823. if (parsedData.animations) {
  23824. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  23825. var parsedAnimation = parsedData.animations[index];
  23826. var animation = BABYLON.Animation.Parse(parsedAnimation);
  23827. scene.animations.push(animation);
  23828. log += (index === 0 ? "\n\tAnimations:" : "");
  23829. log += "\n\t\t" + animation.toString(fullDetails);
  23830. }
  23831. }
  23832. // Materials
  23833. if (parsedData.materials) {
  23834. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23835. var parsedMaterial = parsedData.materials[index];
  23836. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23837. log += (index === 0 ? "\n\tMaterials:" : "");
  23838. log += "\n\t\t" + mat.toString(fullDetails);
  23839. }
  23840. }
  23841. if (parsedData.multiMaterials) {
  23842. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  23843. var parsedMultiMaterial = parsedData.multiMaterials[index];
  23844. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23845. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  23846. log += "\n\t\t" + mmat.toString(fullDetails);
  23847. }
  23848. }
  23849. // Skeletons
  23850. if (parsedData.skeletons) {
  23851. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  23852. var parsedSkeleton = parsedData.skeletons[index];
  23853. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23854. log += (index === 0 ? "\n\tSkeletons:" : "");
  23855. log += "\n\t\t" + skeleton.toString(fullDetails);
  23856. }
  23857. }
  23858. // Geometries
  23859. var geometries = parsedData.geometries;
  23860. if (geometries) {
  23861. // Boxes
  23862. var boxes = geometries.boxes;
  23863. if (boxes) {
  23864. for (index = 0, cache = boxes.length; index < cache; index++) {
  23865. var parsedBox = boxes[index];
  23866. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  23867. }
  23868. }
  23869. // Spheres
  23870. var spheres = geometries.spheres;
  23871. if (spheres) {
  23872. for (index = 0, cache = spheres.length; index < cache; index++) {
  23873. var parsedSphere = spheres[index];
  23874. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  23875. }
  23876. }
  23877. // Cylinders
  23878. var cylinders = geometries.cylinders;
  23879. if (cylinders) {
  23880. for (index = 0, cache = cylinders.length; index < cache; index++) {
  23881. var parsedCylinder = cylinders[index];
  23882. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  23883. }
  23884. }
  23885. // Toruses
  23886. var toruses = geometries.toruses;
  23887. if (toruses) {
  23888. for (index = 0, cache = toruses.length; index < cache; index++) {
  23889. var parsedTorus = toruses[index];
  23890. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  23891. }
  23892. }
  23893. // Grounds
  23894. var grounds = geometries.grounds;
  23895. if (grounds) {
  23896. for (index = 0, cache = grounds.length; index < cache; index++) {
  23897. var parsedGround = grounds[index];
  23898. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  23899. }
  23900. }
  23901. // Planes
  23902. var planes = geometries.planes;
  23903. if (planes) {
  23904. for (index = 0, cache = planes.length; index < cache; index++) {
  23905. var parsedPlane = planes[index];
  23906. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  23907. }
  23908. }
  23909. // TorusKnots
  23910. var torusKnots = geometries.torusKnots;
  23911. if (torusKnots) {
  23912. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  23913. var parsedTorusKnot = torusKnots[index];
  23914. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  23915. }
  23916. }
  23917. // VertexData
  23918. var vertexData = geometries.vertexData;
  23919. if (vertexData) {
  23920. for (index = 0, cache = vertexData.length; index < cache; index++) {
  23921. var parsedVertexData = vertexData[index];
  23922. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  23923. }
  23924. }
  23925. }
  23926. // Meshes
  23927. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23928. var parsedMesh = parsedData.meshes[index];
  23929. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23930. log += (index === 0 ? "\n\tMeshes:" : "");
  23931. log += "\n\t\t" + mesh.toString(fullDetails);
  23932. }
  23933. // Cameras
  23934. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  23935. var parsedCamera = parsedData.cameras[index];
  23936. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  23937. log += (index === 0 ? "\n\tCameras:" : "");
  23938. log += "\n\t\t" + camera.toString(fullDetails);
  23939. }
  23940. if (parsedData.activeCameraID) {
  23941. scene.setActiveCameraByID(parsedData.activeCameraID);
  23942. }
  23943. // Browsing all the graph to connect the dots
  23944. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  23945. var camera = scene.cameras[index];
  23946. if (camera._waitingParentId) {
  23947. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  23948. camera._waitingParentId = undefined;
  23949. }
  23950. }
  23951. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  23952. var light = scene.lights[index];
  23953. if (light._waitingParentId) {
  23954. light.parent = scene.getLastEntryByID(light._waitingParentId);
  23955. light._waitingParentId = undefined;
  23956. }
  23957. }
  23958. // Sounds
  23959. var loadedSounds = [];
  23960. var loadedSound;
  23961. if (BABYLON.AudioEngine && parsedData.sounds) {
  23962. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  23963. var parsedSound = parsedData.sounds[index];
  23964. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  23965. if (!parsedSound.url)
  23966. parsedSound.url = parsedSound.name;
  23967. if (!loadedSounds[parsedSound.url]) {
  23968. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  23969. loadedSounds[parsedSound.url] = loadedSound;
  23970. }
  23971. else {
  23972. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  23973. }
  23974. }
  23975. else {
  23976. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  23977. }
  23978. }
  23979. }
  23980. loadedSounds = [];
  23981. // Connect parents & children and parse actions
  23982. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23983. var mesh = scene.meshes[index];
  23984. if (mesh._waitingParentId) {
  23985. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  23986. mesh._waitingParentId = undefined;
  23987. }
  23988. if (mesh._waitingActions) {
  23989. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  23990. mesh._waitingActions = undefined;
  23991. }
  23992. }
  23993. // freeze world matrix application
  23994. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23995. var currentMesh = scene.meshes[index];
  23996. if (currentMesh._waitingFreezeWorldMatrix) {
  23997. currentMesh.freezeWorldMatrix();
  23998. currentMesh._waitingFreezeWorldMatrix = undefined;
  23999. }
  24000. else {
  24001. currentMesh.computeWorldMatrix(true);
  24002. }
  24003. }
  24004. // Particles Systems
  24005. if (parsedData.particleSystems) {
  24006. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24007. var parsedParticleSystem = parsedData.particleSystems[index];
  24008. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24009. }
  24010. }
  24011. // Lens flares
  24012. if (parsedData.lensFlareSystems) {
  24013. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24014. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24015. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24016. }
  24017. }
  24018. // Shadows
  24019. if (parsedData.shadowGenerators) {
  24020. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24021. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24022. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24023. }
  24024. }
  24025. // Actions (scene)
  24026. if (parsedData.actions) {
  24027. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24028. }
  24029. // Finish
  24030. return true;
  24031. }
  24032. catch (err) {
  24033. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24034. log = null;
  24035. throw err;
  24036. }
  24037. finally {
  24038. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24039. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24040. }
  24041. }
  24042. }
  24043. });
  24044. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24045. })(BABYLON || (BABYLON = {}));
  24046. var BABYLON;
  24047. (function (BABYLON) {
  24048. var SpriteManager = (function () {
  24049. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24051. this.name = name;
  24052. this.cellSize = cellSize;
  24053. this.sprites = new Array();
  24054. this.renderingGroupId = 0;
  24055. this.layerMask = 0x0FFFFFFF;
  24056. this.fogEnabled = true;
  24057. this.isPickable = false;
  24058. this._vertexDeclaration = [4, 4, 4, 4];
  24059. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24060. this._capacity = capacity;
  24061. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24062. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24063. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24064. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24065. this._scene = scene;
  24066. this._scene.spriteManagers.push(this);
  24067. // VBO
  24068. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24069. var indices = [];
  24070. var index = 0;
  24071. for (var count = 0; count < capacity; count++) {
  24072. indices.push(index);
  24073. indices.push(index + 1);
  24074. indices.push(index + 2);
  24075. indices.push(index);
  24076. indices.push(index + 2);
  24077. indices.push(index + 3);
  24078. index += 4;
  24079. }
  24080. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24081. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24082. // Effects
  24083. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24084. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24085. }
  24086. Object.defineProperty(SpriteManager.prototype, "texture", {
  24087. get: function () {
  24088. return this._spriteTexture;
  24089. },
  24090. set: function (value) {
  24091. this._spriteTexture = value;
  24092. },
  24093. enumerable: true,
  24094. configurable: true
  24095. });
  24096. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24097. var arrayOffset = index * 16;
  24098. if (offsetX === 0)
  24099. offsetX = this._epsilon;
  24100. else if (offsetX === 1)
  24101. offsetX = 1 - this._epsilon;
  24102. if (offsetY === 0)
  24103. offsetY = this._epsilon;
  24104. else if (offsetY === 1)
  24105. offsetY = 1 - this._epsilon;
  24106. this._vertices[arrayOffset] = sprite.position.x;
  24107. this._vertices[arrayOffset + 1] = sprite.position.y;
  24108. this._vertices[arrayOffset + 2] = sprite.position.z;
  24109. this._vertices[arrayOffset + 3] = sprite.angle;
  24110. this._vertices[arrayOffset + 4] = sprite.width;
  24111. this._vertices[arrayOffset + 5] = sprite.height;
  24112. this._vertices[arrayOffset + 6] = offsetX;
  24113. this._vertices[arrayOffset + 7] = offsetY;
  24114. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24115. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24116. var offset = (sprite.cellIndex / rowSize) >> 0;
  24117. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24118. this._vertices[arrayOffset + 11] = offset;
  24119. // Color
  24120. this._vertices[arrayOffset + 12] = sprite.color.r;
  24121. this._vertices[arrayOffset + 13] = sprite.color.g;
  24122. this._vertices[arrayOffset + 14] = sprite.color.b;
  24123. this._vertices[arrayOffset + 15] = sprite.color.a;
  24124. };
  24125. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24126. var count = Math.min(this._capacity, this.sprites.length);
  24127. var min = BABYLON.Vector3.Zero();
  24128. var max = BABYLON.Vector3.Zero();
  24129. var distance = Number.MAX_VALUE;
  24130. var currentSprite;
  24131. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24132. var cameraView = camera.getViewMatrix();
  24133. for (var index = 0; index < count; index++) {
  24134. var sprite = this.sprites[index];
  24135. if (!sprite) {
  24136. continue;
  24137. }
  24138. if (predicate) {
  24139. if (!predicate(sprite)) {
  24140. continue;
  24141. }
  24142. }
  24143. else if (!sprite.isPickable) {
  24144. continue;
  24145. }
  24146. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24147. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24148. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24149. if (ray.intersectsBoxMinMax(min, max)) {
  24150. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24151. if (distance > currentDistance) {
  24152. distance = currentDistance;
  24153. currentSprite = sprite;
  24154. if (fastCheck) {
  24155. break;
  24156. }
  24157. }
  24158. }
  24159. }
  24160. if (currentSprite) {
  24161. var result = new BABYLON.PickingInfo();
  24162. result.hit = true;
  24163. result.pickedSprite = currentSprite;
  24164. result.distance = distance;
  24165. return result;
  24166. }
  24167. return null;
  24168. };
  24169. SpriteManager.prototype.render = function () {
  24170. // Check
  24171. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24172. return;
  24173. var engine = this._scene.getEngine();
  24174. var baseSize = this._spriteTexture.getBaseSize();
  24175. // Sprites
  24176. var deltaTime = engine.getDeltaTime();
  24177. var max = Math.min(this._capacity, this.sprites.length);
  24178. var rowSize = baseSize.width / this.cellSize;
  24179. var offset = 0;
  24180. for (var index = 0; index < max; index++) {
  24181. var sprite = this.sprites[index];
  24182. if (!sprite) {
  24183. continue;
  24184. }
  24185. sprite._animate(deltaTime);
  24186. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24187. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24188. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24189. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24190. }
  24191. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24192. // Render
  24193. var effect = this._effectBase;
  24194. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24195. effect = this._effectFog;
  24196. }
  24197. engine.enableEffect(effect);
  24198. var viewMatrix = this._scene.getViewMatrix();
  24199. effect.setTexture("diffuseSampler", this._spriteTexture);
  24200. effect.setMatrix("view", viewMatrix);
  24201. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24202. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24203. // Fog
  24204. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24205. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24206. effect.setColor3("vFogColor", this._scene.fogColor);
  24207. }
  24208. // VBOs
  24209. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24210. // Draw order
  24211. engine.setDepthFunctionToLessOrEqual();
  24212. effect.setBool("alphaTest", true);
  24213. engine.setColorWrite(false);
  24214. engine.draw(true, 0, max * 6);
  24215. engine.setColorWrite(true);
  24216. effect.setBool("alphaTest", false);
  24217. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24218. engine.draw(true, 0, max * 6);
  24219. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24220. };
  24221. SpriteManager.prototype.dispose = function () {
  24222. if (this._vertexBuffer) {
  24223. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24224. this._vertexBuffer = null;
  24225. }
  24226. if (this._indexBuffer) {
  24227. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24228. this._indexBuffer = null;
  24229. }
  24230. if (this._spriteTexture) {
  24231. this._spriteTexture.dispose();
  24232. this._spriteTexture = null;
  24233. }
  24234. // Remove from scene
  24235. var index = this._scene.spriteManagers.indexOf(this);
  24236. this._scene.spriteManagers.splice(index, 1);
  24237. // Callback
  24238. if (this.onDispose) {
  24239. this.onDispose();
  24240. }
  24241. };
  24242. return SpriteManager;
  24243. }());
  24244. BABYLON.SpriteManager = SpriteManager;
  24245. })(BABYLON || (BABYLON = {}));
  24246. var BABYLON;
  24247. (function (BABYLON) {
  24248. var Sprite = (function () {
  24249. function Sprite(name, manager) {
  24250. this.name = name;
  24251. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24252. this.width = 1.0;
  24253. this.height = 1.0;
  24254. this.angle = 0;
  24255. this.cellIndex = 0;
  24256. this.invertU = 0;
  24257. this.invertV = 0;
  24258. this.animations = new Array();
  24259. this.isPickable = false;
  24260. this._animationStarted = false;
  24261. this._loopAnimation = false;
  24262. this._fromIndex = 0;
  24263. this._toIndex = 0;
  24264. this._delay = 0;
  24265. this._direction = 1;
  24266. this._frameCount = 0;
  24267. this._time = 0;
  24268. this._manager = manager;
  24269. this._manager.sprites.push(this);
  24270. this.position = BABYLON.Vector3.Zero();
  24271. }
  24272. Object.defineProperty(Sprite.prototype, "size", {
  24273. get: function () {
  24274. return this.width;
  24275. },
  24276. set: function (value) {
  24277. this.width = value;
  24278. this.height = value;
  24279. },
  24280. enumerable: true,
  24281. configurable: true
  24282. });
  24283. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24284. this._fromIndex = from;
  24285. this._toIndex = to;
  24286. this._loopAnimation = loop;
  24287. this._delay = delay;
  24288. this._animationStarted = true;
  24289. this._direction = from < to ? 1 : -1;
  24290. this.cellIndex = from;
  24291. this._time = 0;
  24292. };
  24293. Sprite.prototype.stopAnimation = function () {
  24294. this._animationStarted = false;
  24295. };
  24296. Sprite.prototype._animate = function (deltaTime) {
  24297. if (!this._animationStarted)
  24298. return;
  24299. this._time += deltaTime;
  24300. if (this._time > this._delay) {
  24301. this._time = this._time % this._delay;
  24302. this.cellIndex += this._direction;
  24303. if (this.cellIndex == this._toIndex) {
  24304. if (this._loopAnimation) {
  24305. this.cellIndex = this._fromIndex;
  24306. }
  24307. else {
  24308. this._animationStarted = false;
  24309. if (this.disposeWhenFinishedAnimating) {
  24310. this.dispose();
  24311. }
  24312. }
  24313. }
  24314. }
  24315. };
  24316. Sprite.prototype.dispose = function () {
  24317. for (var i = 0; i < this._manager.sprites.length; i++) {
  24318. if (this._manager.sprites[i] == this) {
  24319. this._manager.sprites.splice(i, 1);
  24320. }
  24321. }
  24322. };
  24323. return Sprite;
  24324. }());
  24325. BABYLON.Sprite = Sprite;
  24326. })(BABYLON || (BABYLON = {}));
  24327. var BABYLON;
  24328. (function (BABYLON) {
  24329. var Layer = (function () {
  24330. function Layer(name, imgUrl, scene, isBackground, color) {
  24331. this.name = name;
  24332. this.scale = new BABYLON.Vector2(1, 1);
  24333. this.offset = new BABYLON.Vector2(0, 0);
  24334. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24335. this._vertexDeclaration = [2];
  24336. this._vertexStrideSize = 2 * 4;
  24337. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24338. this.isBackground = isBackground === undefined ? true : isBackground;
  24339. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24340. this._scene = scene;
  24341. this._scene.layers.push(this);
  24342. // VBO
  24343. var vertices = [];
  24344. vertices.push(1, 1);
  24345. vertices.push(-1, 1);
  24346. vertices.push(-1, -1);
  24347. vertices.push(1, -1);
  24348. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24349. // Indices
  24350. var indices = [];
  24351. indices.push(0);
  24352. indices.push(1);
  24353. indices.push(2);
  24354. indices.push(0);
  24355. indices.push(2);
  24356. indices.push(3);
  24357. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24358. // Effects
  24359. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24360. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24361. }
  24362. Layer.prototype.render = function () {
  24363. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24364. // Check
  24365. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24366. return;
  24367. var engine = this._scene.getEngine();
  24368. if (this.onBeforeRender) {
  24369. this.onBeforeRender();
  24370. }
  24371. // Render
  24372. engine.enableEffect(currentEffect);
  24373. engine.setState(false);
  24374. // Texture
  24375. currentEffect.setTexture("textureSampler", this.texture);
  24376. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24377. // Color
  24378. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24379. // Scale / offset
  24380. currentEffect.setVector2("offset", this.offset);
  24381. currentEffect.setVector2("scale", this.scale);
  24382. // VBOs
  24383. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24384. // Draw order
  24385. if (!this._alphaTestEffect) {
  24386. engine.setAlphaMode(this.alphaBlendingMode);
  24387. engine.draw(true, 0, 6);
  24388. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24389. }
  24390. else {
  24391. engine.draw(true, 0, 6);
  24392. }
  24393. if (this.onAfterRender) {
  24394. this.onAfterRender();
  24395. }
  24396. };
  24397. Layer.prototype.dispose = function () {
  24398. if (this._vertexBuffer) {
  24399. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24400. this._vertexBuffer = null;
  24401. }
  24402. if (this._indexBuffer) {
  24403. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24404. this._indexBuffer = null;
  24405. }
  24406. if (this.texture) {
  24407. this.texture.dispose();
  24408. this.texture = null;
  24409. }
  24410. // Remove from scene
  24411. var index = this._scene.layers.indexOf(this);
  24412. this._scene.layers.splice(index, 1);
  24413. // Callback
  24414. if (this.onDispose) {
  24415. this.onDispose();
  24416. }
  24417. };
  24418. return Layer;
  24419. }());
  24420. BABYLON.Layer = Layer;
  24421. })(BABYLON || (BABYLON = {}));
  24422. var BABYLON;
  24423. (function (BABYLON) {
  24424. var Particle = (function () {
  24425. function Particle() {
  24426. this.position = BABYLON.Vector3.Zero();
  24427. this.direction = BABYLON.Vector3.Zero();
  24428. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24429. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24430. this.lifeTime = 1.0;
  24431. this.age = 0;
  24432. this.size = 0;
  24433. this.angle = 0;
  24434. this.angularSpeed = 0;
  24435. }
  24436. Particle.prototype.copyTo = function (other) {
  24437. other.position.copyFrom(this.position);
  24438. other.direction.copyFrom(this.direction);
  24439. other.color.copyFrom(this.color);
  24440. other.colorStep.copyFrom(this.colorStep);
  24441. other.lifeTime = this.lifeTime;
  24442. other.age = this.age;
  24443. other.size = this.size;
  24444. other.angle = this.angle;
  24445. other.angularSpeed = this.angularSpeed;
  24446. };
  24447. return Particle;
  24448. }());
  24449. BABYLON.Particle = Particle;
  24450. })(BABYLON || (BABYLON = {}));
  24451. var BABYLON;
  24452. (function (BABYLON) {
  24453. var randomNumber = function (min, max) {
  24454. if (min === max) {
  24455. return (min);
  24456. }
  24457. var random = Math.random();
  24458. return ((random * (max - min)) + min);
  24459. };
  24460. var ParticleSystem = (function () {
  24461. function ParticleSystem(name, capacity, scene, customEffect) {
  24462. var _this = this;
  24463. this.name = name;
  24464. // Members
  24465. this.animations = [];
  24466. this.renderingGroupId = 0;
  24467. this.emitter = null;
  24468. this.emitRate = 10;
  24469. this.manualEmitCount = -1;
  24470. this.updateSpeed = 0.01;
  24471. this.targetStopDuration = 0;
  24472. this.disposeOnStop = false;
  24473. this.minEmitPower = 1;
  24474. this.maxEmitPower = 1;
  24475. this.minLifeTime = 1;
  24476. this.maxLifeTime = 1;
  24477. this.minSize = 1;
  24478. this.maxSize = 1;
  24479. this.minAngularSpeed = 0;
  24480. this.maxAngularSpeed = 0;
  24481. this.layerMask = 0x0FFFFFFF;
  24482. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24483. this.forceDepthWrite = false;
  24484. this.gravity = BABYLON.Vector3.Zero();
  24485. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24486. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24487. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24488. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24489. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24490. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24491. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24492. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24493. this.particles = new Array();
  24494. this._vertexDeclaration = [3, 4, 4];
  24495. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24496. this._stockParticles = new Array();
  24497. this._newPartsExcess = 0;
  24498. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24499. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24500. this._scaledDirection = BABYLON.Vector3.Zero();
  24501. this._scaledGravity = BABYLON.Vector3.Zero();
  24502. this._currentRenderId = -1;
  24503. this._started = false;
  24504. this._stopped = false;
  24505. this._actualFrame = 0;
  24506. this.id = name;
  24507. this._capacity = capacity;
  24508. this._scene = scene;
  24509. this._customEffect = customEffect;
  24510. scene.particleSystems.push(this);
  24511. // VBO
  24512. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24513. var indices = [];
  24514. var index = 0;
  24515. for (var count = 0; count < capacity; count++) {
  24516. indices.push(index);
  24517. indices.push(index + 1);
  24518. indices.push(index + 2);
  24519. indices.push(index);
  24520. indices.push(index + 2);
  24521. indices.push(index + 3);
  24522. index += 4;
  24523. }
  24524. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24525. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24526. // Default behaviors
  24527. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24528. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24529. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24530. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24531. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24532. };
  24533. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24534. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24535. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24536. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24537. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24538. };
  24539. this.updateFunction = function (particles) {
  24540. for (var index = 0; index < particles.length; index++) {
  24541. var particle = particles[index];
  24542. particle.age += _this._scaledUpdateSpeed;
  24543. if (particle.age >= particle.lifeTime) {
  24544. _this.recycleParticle(particle);
  24545. index--;
  24546. continue;
  24547. }
  24548. else {
  24549. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24550. particle.color.addInPlace(_this._scaledColorStep);
  24551. if (particle.color.a < 0)
  24552. particle.color.a = 0;
  24553. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24554. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24555. particle.position.addInPlace(_this._scaledDirection);
  24556. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24557. particle.direction.addInPlace(_this._scaledGravity);
  24558. }
  24559. }
  24560. };
  24561. }
  24562. ParticleSystem.prototype.recycleParticle = function (particle) {
  24563. var lastParticle = this.particles.pop();
  24564. if (lastParticle !== particle) {
  24565. lastParticle.copyTo(particle);
  24566. this._stockParticles.push(lastParticle);
  24567. }
  24568. };
  24569. ParticleSystem.prototype.getCapacity = function () {
  24570. return this._capacity;
  24571. };
  24572. ParticleSystem.prototype.isAlive = function () {
  24573. return this._alive;
  24574. };
  24575. ParticleSystem.prototype.isStarted = function () {
  24576. return this._started;
  24577. };
  24578. ParticleSystem.prototype.start = function () {
  24579. this._started = true;
  24580. this._stopped = false;
  24581. this._actualFrame = 0;
  24582. };
  24583. ParticleSystem.prototype.stop = function () {
  24584. this._stopped = true;
  24585. };
  24586. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24587. var offset = index * 11;
  24588. this._vertices[offset] = particle.position.x;
  24589. this._vertices[offset + 1] = particle.position.y;
  24590. this._vertices[offset + 2] = particle.position.z;
  24591. this._vertices[offset + 3] = particle.color.r;
  24592. this._vertices[offset + 4] = particle.color.g;
  24593. this._vertices[offset + 5] = particle.color.b;
  24594. this._vertices[offset + 6] = particle.color.a;
  24595. this._vertices[offset + 7] = particle.angle;
  24596. this._vertices[offset + 8] = particle.size;
  24597. this._vertices[offset + 9] = offsetX;
  24598. this._vertices[offset + 10] = offsetY;
  24599. };
  24600. ParticleSystem.prototype._update = function (newParticles) {
  24601. // Update current
  24602. this._alive = this.particles.length > 0;
  24603. this.updateFunction(this.particles);
  24604. // Add new ones
  24605. var worldMatrix;
  24606. if (this.emitter.position) {
  24607. worldMatrix = this.emitter.getWorldMatrix();
  24608. }
  24609. else {
  24610. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24611. }
  24612. var particle;
  24613. for (var index = 0; index < newParticles; index++) {
  24614. if (this.particles.length === this._capacity) {
  24615. break;
  24616. }
  24617. if (this._stockParticles.length !== 0) {
  24618. particle = this._stockParticles.pop();
  24619. particle.age = 0;
  24620. }
  24621. else {
  24622. particle = new BABYLON.Particle();
  24623. }
  24624. this.particles.push(particle);
  24625. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24626. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24627. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24628. particle.size = randomNumber(this.minSize, this.maxSize);
  24629. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24630. this.startPositionFunction(worldMatrix, particle.position, particle);
  24631. var step = randomNumber(0, 1.0);
  24632. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24633. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24634. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24635. }
  24636. };
  24637. ParticleSystem.prototype._getEffect = function () {
  24638. if (this._customEffect) {
  24639. return this._customEffect;
  24640. }
  24641. ;
  24642. var defines = [];
  24643. if (this._scene.clipPlane) {
  24644. defines.push("#define CLIPPLANE");
  24645. }
  24646. // Effect
  24647. var join = defines.join("\n");
  24648. if (this._cachedDefines !== join) {
  24649. this._cachedDefines = join;
  24650. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  24651. }
  24652. return this._effect;
  24653. };
  24654. ParticleSystem.prototype.animate = function () {
  24655. if (!this._started)
  24656. return;
  24657. var effect = this._getEffect();
  24658. // Check
  24659. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  24660. return;
  24661. if (this._currentRenderId === this._scene.getRenderId()) {
  24662. return;
  24663. }
  24664. this._currentRenderId = this._scene.getRenderId();
  24665. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  24666. // determine the number of particles we need to create
  24667. var newParticles;
  24668. if (this.manualEmitCount > -1) {
  24669. newParticles = this.manualEmitCount;
  24670. this._newPartsExcess = 0;
  24671. this.manualEmitCount = 0;
  24672. }
  24673. else {
  24674. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  24675. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  24676. }
  24677. if (this._newPartsExcess > 1.0) {
  24678. newParticles += this._newPartsExcess >> 0;
  24679. this._newPartsExcess -= this._newPartsExcess >> 0;
  24680. }
  24681. this._alive = false;
  24682. if (!this._stopped) {
  24683. this._actualFrame += this._scaledUpdateSpeed;
  24684. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  24685. this.stop();
  24686. }
  24687. else {
  24688. newParticles = 0;
  24689. }
  24690. this._update(newParticles);
  24691. // Stopped?
  24692. if (this._stopped) {
  24693. if (!this._alive) {
  24694. this._started = false;
  24695. if (this.disposeOnStop) {
  24696. this._scene._toBeDisposed.push(this);
  24697. }
  24698. }
  24699. }
  24700. // Update VBO
  24701. var offset = 0;
  24702. for (var index = 0; index < this.particles.length; index++) {
  24703. var particle = this.particles[index];
  24704. this._appendParticleVertex(offset++, particle, 0, 0);
  24705. this._appendParticleVertex(offset++, particle, 1, 0);
  24706. this._appendParticleVertex(offset++, particle, 1, 1);
  24707. this._appendParticleVertex(offset++, particle, 0, 1);
  24708. }
  24709. var engine = this._scene.getEngine();
  24710. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24711. };
  24712. ParticleSystem.prototype.render = function () {
  24713. var effect = this._getEffect();
  24714. // Check
  24715. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  24716. return 0;
  24717. var engine = this._scene.getEngine();
  24718. // Render
  24719. engine.enableEffect(effect);
  24720. engine.setState(false);
  24721. var viewMatrix = this._scene.getViewMatrix();
  24722. effect.setTexture("diffuseSampler", this.particleTexture);
  24723. effect.setMatrix("view", viewMatrix);
  24724. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24725. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  24726. if (this._scene.clipPlane) {
  24727. var clipPlane = this._scene.clipPlane;
  24728. var invView = viewMatrix.clone();
  24729. invView.invert();
  24730. effect.setMatrix("invView", invView);
  24731. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24732. }
  24733. // VBOs
  24734. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24735. // Draw order
  24736. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  24737. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  24738. }
  24739. else {
  24740. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24741. }
  24742. if (this.forceDepthWrite) {
  24743. engine.setDepthWrite(true);
  24744. }
  24745. engine.draw(true, 0, this.particles.length * 6);
  24746. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24747. return this.particles.length;
  24748. };
  24749. ParticleSystem.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.particleTexture) {
  24759. this.particleTexture.dispose();
  24760. this.particleTexture = null;
  24761. }
  24762. // Remove from scene
  24763. var index = this._scene.particleSystems.indexOf(this);
  24764. this._scene.particleSystems.splice(index, 1);
  24765. // Callback
  24766. if (this.onDispose) {
  24767. this.onDispose();
  24768. }
  24769. };
  24770. // Clone
  24771. ParticleSystem.prototype.clone = function (name, newEmitter) {
  24772. var result = new ParticleSystem(name, this._capacity, this._scene);
  24773. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  24774. if (newEmitter === undefined) {
  24775. newEmitter = this.emitter;
  24776. }
  24777. result.emitter = newEmitter;
  24778. if (this.particleTexture) {
  24779. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  24780. }
  24781. result.start();
  24782. return result;
  24783. };
  24784. ParticleSystem.prototype.serialize = function () {
  24785. var serializationObject = {};
  24786. serializationObject.name = this.name;
  24787. serializationObject.id = this.id;
  24788. // Emitter
  24789. if (this.emitter.position) {
  24790. serializationObject.emitterId = this.emitter.id;
  24791. }
  24792. else {
  24793. serializationObject.emitter = this.emitter.asArray();
  24794. }
  24795. serializationObject.capacity = this.getCapacity();
  24796. if (this.particleTexture) {
  24797. serializationObject.textureName = this.particleTexture.name;
  24798. }
  24799. // Animations
  24800. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24801. // Particle system
  24802. serializationObject.minAngularSpeed = this.minAngularSpeed;
  24803. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  24804. serializationObject.minSize = this.minSize;
  24805. serializationObject.maxSize = this.maxSize;
  24806. serializationObject.minEmitPower = this.minEmitPower;
  24807. serializationObject.maxEmitPower = this.maxEmitPower;
  24808. serializationObject.minLifeTime = this.minLifeTime;
  24809. serializationObject.maxLifeTime = this.maxLifeTime;
  24810. serializationObject.emitRate = this.emitRate;
  24811. serializationObject.minEmitBox = this.minEmitBox.asArray();
  24812. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  24813. serializationObject.gravity = this.gravity.asArray();
  24814. serializationObject.direction1 = this.direction1.asArray();
  24815. serializationObject.direction2 = this.direction2.asArray();
  24816. serializationObject.color1 = this.color1.asArray();
  24817. serializationObject.color2 = this.color2.asArray();
  24818. serializationObject.colorDead = this.colorDead.asArray();
  24819. serializationObject.updateSpeed = this.updateSpeed;
  24820. serializationObject.targetStopDuration = this.targetStopDuration;
  24821. serializationObject.textureMask = this.textureMask.asArray();
  24822. serializationObject.blendMode = this.blendMode;
  24823. return serializationObject;
  24824. };
  24825. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  24826. var name = parsedParticleSystem.name;
  24827. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  24828. if (parsedParticleSystem.id) {
  24829. particleSystem.id = parsedParticleSystem.id;
  24830. }
  24831. // Texture
  24832. if (parsedParticleSystem.textureName) {
  24833. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  24834. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  24835. }
  24836. // Emitter
  24837. if (parsedParticleSystem.emitterId) {
  24838. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  24839. }
  24840. else {
  24841. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  24842. }
  24843. // Animations
  24844. if (parsedParticleSystem.animations) {
  24845. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  24846. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  24847. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24848. }
  24849. }
  24850. if (parsedParticleSystem.autoAnimate) {
  24851. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  24852. }
  24853. // Particle system
  24854. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  24855. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  24856. particleSystem.minSize = parsedParticleSystem.minSize;
  24857. particleSystem.maxSize = parsedParticleSystem.maxSize;
  24858. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  24859. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  24860. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  24861. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  24862. particleSystem.emitRate = parsedParticleSystem.emitRate;
  24863. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  24864. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  24865. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  24866. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  24867. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  24868. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  24869. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  24870. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  24871. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  24872. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  24873. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  24874. particleSystem.blendMode = parsedParticleSystem.blendMode;
  24875. particleSystem.start();
  24876. return particleSystem;
  24877. };
  24878. // Statics
  24879. ParticleSystem.BLENDMODE_ONEONE = 0;
  24880. ParticleSystem.BLENDMODE_STANDARD = 1;
  24881. return ParticleSystem;
  24882. }());
  24883. BABYLON.ParticleSystem = ParticleSystem;
  24884. })(BABYLON || (BABYLON = {}));
  24885. var BABYLON;
  24886. (function (BABYLON) {
  24887. var AnimationRange = (function () {
  24888. function AnimationRange(name, from, to) {
  24889. this.name = name;
  24890. this.from = from;
  24891. this.to = to;
  24892. }
  24893. AnimationRange.prototype.clone = function () {
  24894. return new AnimationRange(this.name, this.from, this.to);
  24895. };
  24896. return AnimationRange;
  24897. }());
  24898. BABYLON.AnimationRange = AnimationRange;
  24899. /**
  24900. * Composed of a frame, and an action function
  24901. */
  24902. var AnimationEvent = (function () {
  24903. function AnimationEvent(frame, action, onlyOnce) {
  24904. this.frame = frame;
  24905. this.action = action;
  24906. this.onlyOnce = onlyOnce;
  24907. this.isDone = false;
  24908. }
  24909. return AnimationEvent;
  24910. }());
  24911. BABYLON.AnimationEvent = AnimationEvent;
  24912. var PathCursor = (function () {
  24913. function PathCursor(path) {
  24914. this.path = path;
  24915. this._onchange = new Array();
  24916. this.value = 0;
  24917. this.animations = new Array();
  24918. }
  24919. PathCursor.prototype.getPoint = function () {
  24920. var point = this.path.getPointAtLengthPosition(this.value);
  24921. return new BABYLON.Vector3(point.x, 0, point.y);
  24922. };
  24923. PathCursor.prototype.moveAhead = function (step) {
  24924. if (step === void 0) { step = 0.002; }
  24925. this.move(step);
  24926. return this;
  24927. };
  24928. PathCursor.prototype.moveBack = function (step) {
  24929. if (step === void 0) { step = 0.002; }
  24930. this.move(-step);
  24931. return this;
  24932. };
  24933. PathCursor.prototype.move = function (step) {
  24934. if (Math.abs(step) > 1) {
  24935. throw "step size should be less than 1.";
  24936. }
  24937. this.value += step;
  24938. this.ensureLimits();
  24939. this.raiseOnChange();
  24940. return this;
  24941. };
  24942. PathCursor.prototype.ensureLimits = function () {
  24943. while (this.value > 1) {
  24944. this.value -= 1;
  24945. }
  24946. while (this.value < 0) {
  24947. this.value += 1;
  24948. }
  24949. return this;
  24950. };
  24951. // used by animation engine
  24952. PathCursor.prototype.markAsDirty = function (propertyName) {
  24953. this.ensureLimits();
  24954. this.raiseOnChange();
  24955. return this;
  24956. };
  24957. PathCursor.prototype.raiseOnChange = function () {
  24958. var _this = this;
  24959. this._onchange.forEach(function (f) { return f(_this); });
  24960. return this;
  24961. };
  24962. PathCursor.prototype.onchange = function (f) {
  24963. this._onchange.push(f);
  24964. return this;
  24965. };
  24966. return PathCursor;
  24967. }());
  24968. BABYLON.PathCursor = PathCursor;
  24969. var Animation = (function () {
  24970. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  24971. this.name = name;
  24972. this.targetProperty = targetProperty;
  24973. this.framePerSecond = framePerSecond;
  24974. this.dataType = dataType;
  24975. this.loopMode = loopMode;
  24976. this.enableBlending = enableBlending;
  24977. this._offsetsCache = {};
  24978. this._highLimitsCache = {};
  24979. this._stopped = false;
  24980. this._blendingFactor = 0;
  24981. // The set of event that will be linked to this animation
  24982. this._events = new Array();
  24983. this.allowMatricesInterpolation = false;
  24984. this.blendingSpeed = 0.01;
  24985. this._ranges = {};
  24986. this.targetPropertyPath = targetProperty.split(".");
  24987. this.dataType = dataType;
  24988. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  24989. }
  24990. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  24991. var dataType = undefined;
  24992. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  24993. dataType = Animation.ANIMATIONTYPE_FLOAT;
  24994. }
  24995. else if (from instanceof BABYLON.Quaternion) {
  24996. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  24997. }
  24998. else if (from instanceof BABYLON.Vector3) {
  24999. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25000. }
  25001. else if (from instanceof BABYLON.Vector2) {
  25002. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25003. }
  25004. else if (from instanceof BABYLON.Color3) {
  25005. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25006. }
  25007. if (dataType == undefined) {
  25008. return null;
  25009. }
  25010. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25011. var keys = [];
  25012. keys.push({ frame: 0, value: from });
  25013. keys.push({ frame: totalFrame, value: to });
  25014. animation.setKeys(keys);
  25015. if (easingFunction !== undefined) {
  25016. animation.setEasingFunction(easingFunction);
  25017. }
  25018. return animation;
  25019. };
  25020. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25021. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25022. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25023. };
  25024. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25025. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25026. node.animations.push(animation);
  25027. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25028. };
  25029. // Methods
  25030. /**
  25031. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25032. */
  25033. Animation.prototype.toString = function (fullDetails) {
  25034. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25035. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25036. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25037. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25038. if (fullDetails) {
  25039. ret += ", Ranges: {";
  25040. var first = true;
  25041. for (var name in this._ranges) {
  25042. if (!first) {
  25043. ret + ", ";
  25044. first = false;
  25045. }
  25046. ret += name;
  25047. }
  25048. ret += "}";
  25049. }
  25050. return ret;
  25051. };
  25052. /**
  25053. * Add an event to this animation.
  25054. */
  25055. Animation.prototype.addEvent = function (event) {
  25056. this._events.push(event);
  25057. };
  25058. /**
  25059. * Remove all events found at the given frame
  25060. * @param frame
  25061. */
  25062. Animation.prototype.removeEvents = function (frame) {
  25063. for (var index = 0; index < this._events.length; index++) {
  25064. if (this._events[index].frame === frame) {
  25065. this._events.splice(index, 1);
  25066. index--;
  25067. }
  25068. }
  25069. };
  25070. Animation.prototype.createRange = function (name, from, to) {
  25071. // check name not already in use; could happen for bones after serialized
  25072. if (!this._ranges[name]) {
  25073. this._ranges[name] = new AnimationRange(name, from, to);
  25074. }
  25075. };
  25076. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25077. if (deleteFrames === void 0) { deleteFrames = true; }
  25078. if (this._ranges[name]) {
  25079. if (deleteFrames) {
  25080. var from = this._ranges[name].from;
  25081. var to = this._ranges[name].to;
  25082. // this loop MUST go high to low for multiple splices to work
  25083. for (var key = this._keys.length - 1; key >= 0; key--) {
  25084. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25085. this._keys.splice(key, 1);
  25086. }
  25087. }
  25088. }
  25089. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25090. }
  25091. };
  25092. Animation.prototype.getRange = function (name) {
  25093. return this._ranges[name];
  25094. };
  25095. Animation.prototype.reset = function () {
  25096. this._offsetsCache = {};
  25097. this._highLimitsCache = {};
  25098. this.currentFrame = 0;
  25099. this._blendingFactor = 0;
  25100. this._originalBlendValue = null;
  25101. };
  25102. Animation.prototype.isStopped = function () {
  25103. return this._stopped;
  25104. };
  25105. Animation.prototype.getKeys = function () {
  25106. return this._keys;
  25107. };
  25108. Animation.prototype.getHighestFrame = function () {
  25109. var ret = 0;
  25110. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25111. if (ret < this._keys[key].frame) {
  25112. ret = this._keys[key].frame;
  25113. }
  25114. }
  25115. return ret;
  25116. };
  25117. Animation.prototype.getEasingFunction = function () {
  25118. return this._easingFunction;
  25119. };
  25120. Animation.prototype.setEasingFunction = function (easingFunction) {
  25121. this._easingFunction = easingFunction;
  25122. };
  25123. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25124. return startValue + (endValue - startValue) * gradient;
  25125. };
  25126. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25127. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25128. };
  25129. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25130. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25131. };
  25132. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25133. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25134. };
  25135. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25136. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25137. };
  25138. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25139. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25140. };
  25141. Animation.prototype.clone = function () {
  25142. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25143. if (this._keys) {
  25144. clone.setKeys(this._keys);
  25145. }
  25146. if (this._ranges) {
  25147. clone._ranges = {};
  25148. for (var name in this._ranges) {
  25149. clone._ranges[name] = this._ranges[name].clone();
  25150. }
  25151. }
  25152. return clone;
  25153. };
  25154. Animation.prototype.setKeys = function (values) {
  25155. this._keys = values.slice(0);
  25156. this._offsetsCache = {};
  25157. this._highLimitsCache = {};
  25158. };
  25159. Animation.prototype._getKeyValue = function (value) {
  25160. if (typeof value === "function") {
  25161. return value();
  25162. }
  25163. return value;
  25164. };
  25165. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25166. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25167. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25168. }
  25169. this.currentFrame = currentFrame;
  25170. // Try to get a hash to find the right key
  25171. 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));
  25172. if (this._keys[startKey].frame >= currentFrame) {
  25173. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25174. startKey--;
  25175. }
  25176. }
  25177. for (var key = startKey; key < this._keys.length; key++) {
  25178. if (this._keys[key + 1].frame >= currentFrame) {
  25179. var startValue = this._getKeyValue(this._keys[key].value);
  25180. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25181. // gradient : percent of currentFrame between the frame inf and the frame sup
  25182. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25183. // check for easingFunction and correction of gradient
  25184. if (this._easingFunction != null) {
  25185. gradient = this._easingFunction.ease(gradient);
  25186. }
  25187. switch (this.dataType) {
  25188. // Float
  25189. case Animation.ANIMATIONTYPE_FLOAT:
  25190. switch (loopMode) {
  25191. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25192. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25193. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25194. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25195. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25196. }
  25197. break;
  25198. // Quaternion
  25199. case Animation.ANIMATIONTYPE_QUATERNION:
  25200. var quaternion = null;
  25201. switch (loopMode) {
  25202. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25203. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25204. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25205. break;
  25206. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25207. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25208. break;
  25209. }
  25210. return quaternion;
  25211. // Vector3
  25212. case Animation.ANIMATIONTYPE_VECTOR3:
  25213. switch (loopMode) {
  25214. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25215. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25216. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25217. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25218. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25219. }
  25220. // Vector2
  25221. case Animation.ANIMATIONTYPE_VECTOR2:
  25222. switch (loopMode) {
  25223. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25224. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25225. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25226. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25227. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25228. }
  25229. // Color3
  25230. case Animation.ANIMATIONTYPE_COLOR3:
  25231. switch (loopMode) {
  25232. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25233. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25234. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25235. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25236. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25237. }
  25238. // Matrix
  25239. case Animation.ANIMATIONTYPE_MATRIX:
  25240. switch (loopMode) {
  25241. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25242. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25243. if (this.allowMatricesInterpolation) {
  25244. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25245. }
  25246. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25247. return startValue;
  25248. }
  25249. default:
  25250. break;
  25251. }
  25252. break;
  25253. }
  25254. }
  25255. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25256. };
  25257. Animation.prototype.setValue = function (currentValue, blend) {
  25258. if (blend === void 0) { blend = false; }
  25259. // Set value
  25260. var path;
  25261. var destination;
  25262. if (this.targetPropertyPath.length > 1) {
  25263. var property = this._target[this.targetPropertyPath[0]];
  25264. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25265. property = property[this.targetPropertyPath[index]];
  25266. }
  25267. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25268. destination = property;
  25269. }
  25270. else {
  25271. path = this.targetPropertyPath[0];
  25272. destination = this._target;
  25273. }
  25274. // Blending
  25275. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25276. if (!this._originalBlendValue) {
  25277. this._originalBlendValue = destination[path];
  25278. }
  25279. if (this._originalBlendValue.prototype) {
  25280. if (this._originalBlendValue.prototype.Lerp) {
  25281. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25282. }
  25283. else {
  25284. destination[path] = currentValue;
  25285. }
  25286. }
  25287. else {
  25288. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25289. }
  25290. this._blendingFactor += this.blendingSpeed;
  25291. }
  25292. else {
  25293. destination[path] = currentValue;
  25294. }
  25295. if (this._target.markAsDirty) {
  25296. this._target.markAsDirty(this.targetProperty);
  25297. }
  25298. };
  25299. Animation.prototype.goToFrame = function (frame) {
  25300. if (frame < this._keys[0].frame) {
  25301. frame = this._keys[0].frame;
  25302. }
  25303. else if (frame > this._keys[this._keys.length - 1].frame) {
  25304. frame = this._keys[this._keys.length - 1].frame;
  25305. }
  25306. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25307. this.setValue(currentValue);
  25308. };
  25309. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25310. if (blend === void 0) { blend = false; }
  25311. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25312. this._stopped = true;
  25313. return false;
  25314. }
  25315. var returnValue = true;
  25316. // Adding a start key at frame 0 if missing
  25317. if (this._keys[0].frame !== 0) {
  25318. var newKey = { frame: 0, value: this._keys[0].value };
  25319. this._keys.splice(0, 0, newKey);
  25320. }
  25321. // Check limits
  25322. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25323. from = this._keys[0].frame;
  25324. }
  25325. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25326. to = this._keys[this._keys.length - 1].frame;
  25327. }
  25328. // Compute ratio
  25329. var range = to - from;
  25330. var offsetValue;
  25331. // ratio represents the frame delta between from and to
  25332. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25333. var highLimitValue = 0;
  25334. if (ratio > range && !loop) {
  25335. returnValue = false;
  25336. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25337. }
  25338. else {
  25339. // Get max value if required
  25340. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25341. var keyOffset = to.toString() + from.toString();
  25342. if (!this._offsetsCache[keyOffset]) {
  25343. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25344. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25345. switch (this.dataType) {
  25346. // Float
  25347. case Animation.ANIMATIONTYPE_FLOAT:
  25348. this._offsetsCache[keyOffset] = toValue - fromValue;
  25349. break;
  25350. // Quaternion
  25351. case Animation.ANIMATIONTYPE_QUATERNION:
  25352. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25353. break;
  25354. // Vector3
  25355. case Animation.ANIMATIONTYPE_VECTOR3:
  25356. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25357. // Vector2
  25358. case Animation.ANIMATIONTYPE_VECTOR2:
  25359. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25360. // Color3
  25361. case Animation.ANIMATIONTYPE_COLOR3:
  25362. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25363. default:
  25364. break;
  25365. }
  25366. this._highLimitsCache[keyOffset] = toValue;
  25367. }
  25368. highLimitValue = this._highLimitsCache[keyOffset];
  25369. offsetValue = this._offsetsCache[keyOffset];
  25370. }
  25371. }
  25372. if (offsetValue === undefined) {
  25373. switch (this.dataType) {
  25374. // Float
  25375. case Animation.ANIMATIONTYPE_FLOAT:
  25376. offsetValue = 0;
  25377. break;
  25378. // Quaternion
  25379. case Animation.ANIMATIONTYPE_QUATERNION:
  25380. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25381. break;
  25382. // Vector3
  25383. case Animation.ANIMATIONTYPE_VECTOR3:
  25384. offsetValue = BABYLON.Vector3.Zero();
  25385. break;
  25386. // Vector2
  25387. case Animation.ANIMATIONTYPE_VECTOR2:
  25388. offsetValue = BABYLON.Vector2.Zero();
  25389. break;
  25390. // Color3
  25391. case Animation.ANIMATIONTYPE_COLOR3:
  25392. offsetValue = BABYLON.Color3.Black();
  25393. }
  25394. }
  25395. // Compute value
  25396. var repeatCount = (ratio / range) >> 0;
  25397. var currentFrame = returnValue ? from + ratio % range : to;
  25398. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25399. // Set value
  25400. this.setValue(currentValue);
  25401. // Check events
  25402. for (var index = 0; index < this._events.length; index++) {
  25403. if (currentFrame >= this._events[index].frame) {
  25404. var event = this._events[index];
  25405. if (!event.isDone) {
  25406. // If event should be done only once, remove it.
  25407. if (event.onlyOnce) {
  25408. this._events.splice(index, 1);
  25409. index--;
  25410. }
  25411. event.isDone = true;
  25412. event.action();
  25413. } // Don't do anything if the event has already be done.
  25414. }
  25415. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25416. // reset event, the animation is looping
  25417. this._events[index].isDone = false;
  25418. }
  25419. }
  25420. if (!returnValue) {
  25421. this._stopped = true;
  25422. }
  25423. return returnValue;
  25424. };
  25425. Animation.prototype.serialize = function () {
  25426. var serializationObject = {};
  25427. serializationObject.name = this.name;
  25428. serializationObject.property = this.targetProperty;
  25429. serializationObject.framePerSecond = this.framePerSecond;
  25430. serializationObject.dataType = this.dataType;
  25431. serializationObject.loopBehavior = this.loopMode;
  25432. var dataType = this.dataType;
  25433. serializationObject.keys = [];
  25434. var keys = this.getKeys();
  25435. for (var index = 0; index < keys.length; index++) {
  25436. var animationKey = keys[index];
  25437. var key = {};
  25438. key.frame = animationKey.frame;
  25439. switch (dataType) {
  25440. case Animation.ANIMATIONTYPE_FLOAT:
  25441. key.values = [animationKey.value];
  25442. break;
  25443. case Animation.ANIMATIONTYPE_QUATERNION:
  25444. case Animation.ANIMATIONTYPE_MATRIX:
  25445. case Animation.ANIMATIONTYPE_VECTOR3:
  25446. case Animation.ANIMATIONTYPE_COLOR3:
  25447. key.values = animationKey.value.asArray();
  25448. break;
  25449. }
  25450. serializationObject.keys.push(key);
  25451. }
  25452. serializationObject.ranges = [];
  25453. for (var name in this._ranges) {
  25454. var range = {};
  25455. range.name = name;
  25456. range.from = this._ranges[name].from;
  25457. range.to = this._ranges[name].to;
  25458. serializationObject.ranges.push(range);
  25459. }
  25460. return serializationObject;
  25461. };
  25462. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25463. get: function () {
  25464. return Animation._ANIMATIONTYPE_FLOAT;
  25465. },
  25466. enumerable: true,
  25467. configurable: true
  25468. });
  25469. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25470. get: function () {
  25471. return Animation._ANIMATIONTYPE_VECTOR3;
  25472. },
  25473. enumerable: true,
  25474. configurable: true
  25475. });
  25476. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25477. get: function () {
  25478. return Animation._ANIMATIONTYPE_VECTOR2;
  25479. },
  25480. enumerable: true,
  25481. configurable: true
  25482. });
  25483. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25484. get: function () {
  25485. return Animation._ANIMATIONTYPE_QUATERNION;
  25486. },
  25487. enumerable: true,
  25488. configurable: true
  25489. });
  25490. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25491. get: function () {
  25492. return Animation._ANIMATIONTYPE_MATRIX;
  25493. },
  25494. enumerable: true,
  25495. configurable: true
  25496. });
  25497. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25498. get: function () {
  25499. return Animation._ANIMATIONTYPE_COLOR3;
  25500. },
  25501. enumerable: true,
  25502. configurable: true
  25503. });
  25504. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25505. get: function () {
  25506. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25507. },
  25508. enumerable: true,
  25509. configurable: true
  25510. });
  25511. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25512. get: function () {
  25513. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25514. },
  25515. enumerable: true,
  25516. configurable: true
  25517. });
  25518. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25519. get: function () {
  25520. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25521. },
  25522. enumerable: true,
  25523. configurable: true
  25524. });
  25525. Animation.Parse = function (parsedAnimation) {
  25526. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25527. var dataType = parsedAnimation.dataType;
  25528. var keys = [];
  25529. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25530. var key = parsedAnimation.keys[index];
  25531. var data;
  25532. switch (dataType) {
  25533. case Animation.ANIMATIONTYPE_FLOAT:
  25534. data = key.values[0];
  25535. break;
  25536. case Animation.ANIMATIONTYPE_QUATERNION:
  25537. data = BABYLON.Quaternion.FromArray(key.values);
  25538. break;
  25539. case Animation.ANIMATIONTYPE_MATRIX:
  25540. data = BABYLON.Matrix.FromArray(key.values);
  25541. break;
  25542. case Animation.ANIMATIONTYPE_COLOR3:
  25543. data = BABYLON.Color3.FromArray(key.values);
  25544. break;
  25545. case Animation.ANIMATIONTYPE_VECTOR3:
  25546. default:
  25547. data = BABYLON.Vector3.FromArray(key.values);
  25548. break;
  25549. }
  25550. keys.push({
  25551. frame: key.frame,
  25552. value: data
  25553. });
  25554. }
  25555. animation.setKeys(keys);
  25556. if (parsedAnimation.ranges) {
  25557. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25558. data = parsedAnimation.ranges[index];
  25559. animation.createRange(data.name, data.from, data.to);
  25560. }
  25561. }
  25562. return animation;
  25563. };
  25564. Animation.AppendSerializedAnimations = function (source, destination) {
  25565. if (source.animations) {
  25566. destination.animations = [];
  25567. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25568. var animation = source.animations[animationIndex];
  25569. destination.animations.push(animation.serialize());
  25570. }
  25571. }
  25572. };
  25573. // Statics
  25574. Animation._ANIMATIONTYPE_FLOAT = 0;
  25575. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25576. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25577. Animation._ANIMATIONTYPE_MATRIX = 3;
  25578. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25579. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25580. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25581. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25582. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25583. return Animation;
  25584. }());
  25585. BABYLON.Animation = Animation;
  25586. })(BABYLON || (BABYLON = {}));
  25587. var BABYLON;
  25588. (function (BABYLON) {
  25589. var Animatable = (function () {
  25590. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25591. if (fromFrame === void 0) { fromFrame = 0; }
  25592. if (toFrame === void 0) { toFrame = 100; }
  25593. if (loopAnimation === void 0) { loopAnimation = false; }
  25594. if (speedRatio === void 0) { speedRatio = 1.0; }
  25595. this.target = target;
  25596. this.fromFrame = fromFrame;
  25597. this.toFrame = toFrame;
  25598. this.loopAnimation = loopAnimation;
  25599. this.speedRatio = speedRatio;
  25600. this.onAnimationEnd = onAnimationEnd;
  25601. this._animations = new Array();
  25602. this._paused = false;
  25603. this.animationStarted = false;
  25604. if (animations) {
  25605. this.appendAnimations(target, animations);
  25606. }
  25607. this._scene = scene;
  25608. scene._activeAnimatables.push(this);
  25609. }
  25610. // Methods
  25611. Animatable.prototype.getAnimations = function () {
  25612. return this._animations;
  25613. };
  25614. Animatable.prototype.appendAnimations = function (target, animations) {
  25615. for (var index = 0; index < animations.length; index++) {
  25616. var animation = animations[index];
  25617. animation._target = target;
  25618. this._animations.push(animation);
  25619. }
  25620. };
  25621. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25622. var animations = this._animations;
  25623. for (var index = 0; index < animations.length; index++) {
  25624. if (animations[index].targetProperty === property) {
  25625. return animations[index];
  25626. }
  25627. }
  25628. return null;
  25629. };
  25630. Animatable.prototype.reset = function () {
  25631. var animations = this._animations;
  25632. for (var index = 0; index < animations.length; index++) {
  25633. animations[index].reset();
  25634. }
  25635. this._localDelayOffset = null;
  25636. this._pausedDelay = null;
  25637. };
  25638. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25639. var animations = this._animations;
  25640. for (var index = 0; index < animations.length; index++) {
  25641. animations[index].enableBlending = true;
  25642. animations[index].blendingSpeed = blendingSpeed;
  25643. }
  25644. };
  25645. Animatable.prototype.disableBlending = function () {
  25646. var animations = this._animations;
  25647. for (var index = 0; index < animations.length; index++) {
  25648. animations[index].enableBlending = false;
  25649. }
  25650. };
  25651. Animatable.prototype.goToFrame = function (frame) {
  25652. var animations = this._animations;
  25653. for (var index = 0; index < animations.length; index++) {
  25654. animations[index].goToFrame(frame);
  25655. }
  25656. };
  25657. Animatable.prototype.pause = function () {
  25658. if (this._paused) {
  25659. return;
  25660. }
  25661. this._paused = true;
  25662. };
  25663. Animatable.prototype.restart = function () {
  25664. this._paused = false;
  25665. };
  25666. Animatable.prototype.stop = function () {
  25667. var index = this._scene._activeAnimatables.indexOf(this);
  25668. if (index > -1) {
  25669. this._scene._activeAnimatables.splice(index, 1);
  25670. var animations = this._animations;
  25671. for (var index = 0; index < animations.length; index++) {
  25672. animations[index].reset();
  25673. }
  25674. if (this.onAnimationEnd) {
  25675. this.onAnimationEnd();
  25676. }
  25677. }
  25678. };
  25679. Animatable.prototype._animate = function (delay) {
  25680. if (this._paused) {
  25681. this.animationStarted = false;
  25682. if (!this._pausedDelay) {
  25683. this._pausedDelay = delay;
  25684. }
  25685. return true;
  25686. }
  25687. if (!this._localDelayOffset) {
  25688. this._localDelayOffset = delay;
  25689. }
  25690. else if (this._pausedDelay) {
  25691. this._localDelayOffset += delay - this._pausedDelay;
  25692. this._pausedDelay = null;
  25693. }
  25694. // Animating
  25695. var running = false;
  25696. var animations = this._animations;
  25697. var index;
  25698. for (index = 0; index < animations.length; index++) {
  25699. var animation = animations[index];
  25700. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  25701. running = running || isRunning;
  25702. }
  25703. this.animationStarted = running;
  25704. if (!running) {
  25705. // Remove from active animatables
  25706. index = this._scene._activeAnimatables.indexOf(this);
  25707. this._scene._activeAnimatables.splice(index, 1);
  25708. }
  25709. if (!running && this.onAnimationEnd) {
  25710. this.onAnimationEnd();
  25711. this.onAnimationEnd = null;
  25712. }
  25713. return running;
  25714. };
  25715. return Animatable;
  25716. }());
  25717. BABYLON.Animatable = Animatable;
  25718. })(BABYLON || (BABYLON = {}));
  25719. var BABYLON;
  25720. (function (BABYLON) {
  25721. var EasingFunction = (function () {
  25722. function EasingFunction() {
  25723. // Properties
  25724. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  25725. }
  25726. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  25727. get: function () {
  25728. return EasingFunction._EASINGMODE_EASEIN;
  25729. },
  25730. enumerable: true,
  25731. configurable: true
  25732. });
  25733. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  25734. get: function () {
  25735. return EasingFunction._EASINGMODE_EASEOUT;
  25736. },
  25737. enumerable: true,
  25738. configurable: true
  25739. });
  25740. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  25741. get: function () {
  25742. return EasingFunction._EASINGMODE_EASEINOUT;
  25743. },
  25744. enumerable: true,
  25745. configurable: true
  25746. });
  25747. EasingFunction.prototype.setEasingMode = function (easingMode) {
  25748. var n = Math.min(Math.max(easingMode, 0), 2);
  25749. this._easingMode = n;
  25750. };
  25751. EasingFunction.prototype.getEasingMode = function () {
  25752. return this._easingMode;
  25753. };
  25754. EasingFunction.prototype.easeInCore = function (gradient) {
  25755. throw new Error('You must implement this method');
  25756. };
  25757. EasingFunction.prototype.ease = function (gradient) {
  25758. switch (this._easingMode) {
  25759. case EasingFunction.EASINGMODE_EASEIN:
  25760. return this.easeInCore(gradient);
  25761. case EasingFunction.EASINGMODE_EASEOUT:
  25762. return (1 - this.easeInCore(1 - gradient));
  25763. }
  25764. if (gradient >= 0.5) {
  25765. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  25766. }
  25767. return (this.easeInCore(gradient * 2) * 0.5);
  25768. };
  25769. //Statics
  25770. EasingFunction._EASINGMODE_EASEIN = 0;
  25771. EasingFunction._EASINGMODE_EASEOUT = 1;
  25772. EasingFunction._EASINGMODE_EASEINOUT = 2;
  25773. return EasingFunction;
  25774. }());
  25775. BABYLON.EasingFunction = EasingFunction;
  25776. var CircleEase = (function (_super) {
  25777. __extends(CircleEase, _super);
  25778. function CircleEase() {
  25779. _super.apply(this, arguments);
  25780. }
  25781. CircleEase.prototype.easeInCore = function (gradient) {
  25782. gradient = Math.max(0, Math.min(1, gradient));
  25783. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  25784. };
  25785. return CircleEase;
  25786. }(EasingFunction));
  25787. BABYLON.CircleEase = CircleEase;
  25788. var BackEase = (function (_super) {
  25789. __extends(BackEase, _super);
  25790. function BackEase(amplitude) {
  25791. if (amplitude === void 0) { amplitude = 1; }
  25792. _super.call(this);
  25793. this.amplitude = amplitude;
  25794. }
  25795. BackEase.prototype.easeInCore = function (gradient) {
  25796. var num = Math.max(0, this.amplitude);
  25797. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  25798. };
  25799. return BackEase;
  25800. }(EasingFunction));
  25801. BABYLON.BackEase = BackEase;
  25802. var BounceEase = (function (_super) {
  25803. __extends(BounceEase, _super);
  25804. function BounceEase(bounces, bounciness) {
  25805. if (bounces === void 0) { bounces = 3; }
  25806. if (bounciness === void 0) { bounciness = 2; }
  25807. _super.call(this);
  25808. this.bounces = bounces;
  25809. this.bounciness = bounciness;
  25810. }
  25811. BounceEase.prototype.easeInCore = function (gradient) {
  25812. var y = Math.max(0.0, this.bounces);
  25813. var bounciness = this.bounciness;
  25814. if (bounciness <= 1.0) {
  25815. bounciness = 1.001;
  25816. }
  25817. var num9 = Math.pow(bounciness, y);
  25818. var num5 = 1.0 - bounciness;
  25819. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  25820. var num15 = gradient * num4;
  25821. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  25822. var num3 = Math.floor(num65);
  25823. var num13 = num3 + 1.0;
  25824. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  25825. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  25826. var num7 = (num8 + num12) * 0.5;
  25827. var num6 = gradient - num7;
  25828. var num2 = num7 - num8;
  25829. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  25830. };
  25831. return BounceEase;
  25832. }(EasingFunction));
  25833. BABYLON.BounceEase = BounceEase;
  25834. var CubicEase = (function (_super) {
  25835. __extends(CubicEase, _super);
  25836. function CubicEase() {
  25837. _super.apply(this, arguments);
  25838. }
  25839. CubicEase.prototype.easeInCore = function (gradient) {
  25840. return (gradient * gradient * gradient);
  25841. };
  25842. return CubicEase;
  25843. }(EasingFunction));
  25844. BABYLON.CubicEase = CubicEase;
  25845. var ElasticEase = (function (_super) {
  25846. __extends(ElasticEase, _super);
  25847. function ElasticEase(oscillations, springiness) {
  25848. if (oscillations === void 0) { oscillations = 3; }
  25849. if (springiness === void 0) { springiness = 3; }
  25850. _super.call(this);
  25851. this.oscillations = oscillations;
  25852. this.springiness = springiness;
  25853. }
  25854. ElasticEase.prototype.easeInCore = function (gradient) {
  25855. var num2;
  25856. var num3 = Math.max(0.0, this.oscillations);
  25857. var num = Math.max(0.0, this.springiness);
  25858. if (num == 0) {
  25859. num2 = gradient;
  25860. }
  25861. else {
  25862. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  25863. }
  25864. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  25865. };
  25866. return ElasticEase;
  25867. }(EasingFunction));
  25868. BABYLON.ElasticEase = ElasticEase;
  25869. var ExponentialEase = (function (_super) {
  25870. __extends(ExponentialEase, _super);
  25871. function ExponentialEase(exponent) {
  25872. if (exponent === void 0) { exponent = 2; }
  25873. _super.call(this);
  25874. this.exponent = exponent;
  25875. }
  25876. ExponentialEase.prototype.easeInCore = function (gradient) {
  25877. if (this.exponent <= 0) {
  25878. return gradient;
  25879. }
  25880. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  25881. };
  25882. return ExponentialEase;
  25883. }(EasingFunction));
  25884. BABYLON.ExponentialEase = ExponentialEase;
  25885. var PowerEase = (function (_super) {
  25886. __extends(PowerEase, _super);
  25887. function PowerEase(power) {
  25888. if (power === void 0) { power = 2; }
  25889. _super.call(this);
  25890. this.power = power;
  25891. }
  25892. PowerEase.prototype.easeInCore = function (gradient) {
  25893. var y = Math.max(0.0, this.power);
  25894. return Math.pow(gradient, y);
  25895. };
  25896. return PowerEase;
  25897. }(EasingFunction));
  25898. BABYLON.PowerEase = PowerEase;
  25899. var QuadraticEase = (function (_super) {
  25900. __extends(QuadraticEase, _super);
  25901. function QuadraticEase() {
  25902. _super.apply(this, arguments);
  25903. }
  25904. QuadraticEase.prototype.easeInCore = function (gradient) {
  25905. return (gradient * gradient);
  25906. };
  25907. return QuadraticEase;
  25908. }(EasingFunction));
  25909. BABYLON.QuadraticEase = QuadraticEase;
  25910. var QuarticEase = (function (_super) {
  25911. __extends(QuarticEase, _super);
  25912. function QuarticEase() {
  25913. _super.apply(this, arguments);
  25914. }
  25915. QuarticEase.prototype.easeInCore = function (gradient) {
  25916. return (gradient * gradient * gradient * gradient);
  25917. };
  25918. return QuarticEase;
  25919. }(EasingFunction));
  25920. BABYLON.QuarticEase = QuarticEase;
  25921. var QuinticEase = (function (_super) {
  25922. __extends(QuinticEase, _super);
  25923. function QuinticEase() {
  25924. _super.apply(this, arguments);
  25925. }
  25926. QuinticEase.prototype.easeInCore = function (gradient) {
  25927. return (gradient * gradient * gradient * gradient * gradient);
  25928. };
  25929. return QuinticEase;
  25930. }(EasingFunction));
  25931. BABYLON.QuinticEase = QuinticEase;
  25932. var SineEase = (function (_super) {
  25933. __extends(SineEase, _super);
  25934. function SineEase() {
  25935. _super.apply(this, arguments);
  25936. }
  25937. SineEase.prototype.easeInCore = function (gradient) {
  25938. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  25939. };
  25940. return SineEase;
  25941. }(EasingFunction));
  25942. BABYLON.SineEase = SineEase;
  25943. var BezierCurveEase = (function (_super) {
  25944. __extends(BezierCurveEase, _super);
  25945. function BezierCurveEase(x1, y1, x2, y2) {
  25946. if (x1 === void 0) { x1 = 0; }
  25947. if (y1 === void 0) { y1 = 0; }
  25948. if (x2 === void 0) { x2 = 1; }
  25949. if (y2 === void 0) { y2 = 1; }
  25950. _super.call(this);
  25951. this.x1 = x1;
  25952. this.y1 = y1;
  25953. this.x2 = x2;
  25954. this.y2 = y2;
  25955. }
  25956. BezierCurveEase.prototype.easeInCore = function (gradient) {
  25957. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  25958. };
  25959. return BezierCurveEase;
  25960. }(EasingFunction));
  25961. BABYLON.BezierCurveEase = BezierCurveEase;
  25962. })(BABYLON || (BABYLON = {}));
  25963. var BABYLON;
  25964. (function (BABYLON) {
  25965. var Bone = (function (_super) {
  25966. __extends(Bone, _super);
  25967. function Bone(name, skeleton, parentBone, matrix, restPose) {
  25968. _super.call(this, name, skeleton.getScene());
  25969. this.name = name;
  25970. this.children = new Array();
  25971. this.animations = new Array();
  25972. this._worldTransform = new BABYLON.Matrix();
  25973. this._absoluteTransform = new BABYLON.Matrix();
  25974. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  25975. this._skeleton = skeleton;
  25976. this._matrix = matrix;
  25977. this._baseMatrix = matrix;
  25978. this._restPose = restPose ? restPose : matrix.clone();
  25979. skeleton.bones.push(this);
  25980. if (parentBone) {
  25981. this._parent = parentBone;
  25982. parentBone.children.push(this);
  25983. }
  25984. else {
  25985. this._parent = null;
  25986. }
  25987. this._updateDifferenceMatrix();
  25988. }
  25989. // Members
  25990. Bone.prototype.getParent = function () {
  25991. return this._parent;
  25992. };
  25993. Bone.prototype.getLocalMatrix = function () {
  25994. return this._matrix;
  25995. };
  25996. Bone.prototype.getBaseMatrix = function () {
  25997. return this._baseMatrix;
  25998. };
  25999. Bone.prototype.getRestPose = function () {
  26000. return this._restPose;
  26001. };
  26002. Bone.prototype.returnToRest = function () {
  26003. this.updateMatrix(this._restPose.clone());
  26004. };
  26005. Bone.prototype.getWorldMatrix = function () {
  26006. return this._worldTransform;
  26007. };
  26008. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26009. return this._invertedAbsoluteTransform;
  26010. };
  26011. Bone.prototype.getAbsoluteTransform = function () {
  26012. return this._absoluteTransform;
  26013. };
  26014. // Methods
  26015. Bone.prototype.updateMatrix = function (matrix) {
  26016. this._baseMatrix = matrix.clone();
  26017. this._matrix = matrix.clone();
  26018. this._skeleton._markAsDirty();
  26019. this._updateDifferenceMatrix();
  26020. };
  26021. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26022. if (!rootMatrix) {
  26023. rootMatrix = this._baseMatrix;
  26024. }
  26025. if (this._parent) {
  26026. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26027. }
  26028. else {
  26029. this._absoluteTransform.copyFrom(rootMatrix);
  26030. }
  26031. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26032. for (var index = 0; index < this.children.length; index++) {
  26033. this.children[index]._updateDifferenceMatrix();
  26034. }
  26035. };
  26036. Bone.prototype.markAsDirty = function () {
  26037. this._currentRenderId++;
  26038. this._skeleton._markAsDirty();
  26039. };
  26040. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26041. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26042. // all animation may be coming from a library skeleton, so may need to create animation
  26043. if (this.animations.length === 0) {
  26044. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26045. this.animations[0].setKeys([]);
  26046. }
  26047. // get animation info / verify there is such a range from the source bone
  26048. var sourceRange = source.animations[0].getRange(rangeName);
  26049. if (!sourceRange) {
  26050. return false;
  26051. }
  26052. var from = sourceRange.from;
  26053. var to = sourceRange.to;
  26054. var sourceKeys = source.animations[0].getKeys();
  26055. // rescaling prep
  26056. var sourceBoneLength = source.length;
  26057. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26058. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26059. var destKeys = this.animations[0].getKeys();
  26060. // loop vars declaration / initialization
  26061. var orig;
  26062. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26063. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26064. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26065. var mat;
  26066. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26067. orig = sourceKeys[key];
  26068. if (orig.frame >= from && orig.frame <= to) {
  26069. if (scalingReqd) {
  26070. orig.value.decompose(origScale, origRotation, origTranslation);
  26071. origTranslation.scaleInPlace(ratio);
  26072. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26073. }
  26074. else {
  26075. mat = orig.value;
  26076. }
  26077. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26078. }
  26079. }
  26080. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26081. return true;
  26082. };
  26083. return Bone;
  26084. }(BABYLON.Node));
  26085. BABYLON.Bone = Bone;
  26086. })(BABYLON || (BABYLON = {}));
  26087. var BABYLON;
  26088. (function (BABYLON) {
  26089. var Skeleton = (function () {
  26090. function Skeleton(name, id, scene) {
  26091. this.name = name;
  26092. this.id = id;
  26093. this.bones = new Array();
  26094. this.needInitialSkinMatrix = false;
  26095. this._isDirty = true;
  26096. this._meshesWithPoseMatrix = new Array();
  26097. this._identity = BABYLON.Matrix.Identity();
  26098. this._ranges = {};
  26099. this.bones = [];
  26100. this._scene = scene;
  26101. scene.skeletons.push(this);
  26102. //make sure it will recalculate the matrix next time prepare is called.
  26103. this._isDirty = true;
  26104. }
  26105. // Members
  26106. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26107. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26108. return mesh._bonesTransformMatrices;
  26109. }
  26110. return this._transformMatrices;
  26111. };
  26112. Skeleton.prototype.getScene = function () {
  26113. return this._scene;
  26114. };
  26115. // Methods
  26116. /**
  26117. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26118. */
  26119. Skeleton.prototype.toString = function (fullDetails) {
  26120. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26121. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26122. if (fullDetails) {
  26123. ret += ", Ranges: {";
  26124. var first = true;
  26125. for (var name in this._ranges) {
  26126. if (!first) {
  26127. ret + ", ";
  26128. first = false;
  26129. }
  26130. ret += name;
  26131. }
  26132. ret += "}";
  26133. }
  26134. return ret;
  26135. };
  26136. /**
  26137. * Get bone's index searching by name
  26138. * @param {string} name is bone's name to search for
  26139. * @return {number} Indice of the bone. Returns -1 if not found
  26140. */
  26141. Skeleton.prototype.getBoneIndexByName = function (name) {
  26142. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26143. if (this.bones[boneIndex].name === name) {
  26144. return boneIndex;
  26145. }
  26146. }
  26147. return -1;
  26148. };
  26149. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26150. // check name not already in use
  26151. if (!this._ranges[name]) {
  26152. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26153. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26154. if (this.bones[i].animations[0]) {
  26155. this.bones[i].animations[0].createRange(name, from, to);
  26156. }
  26157. }
  26158. }
  26159. };
  26160. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26161. if (deleteFrames === void 0) { deleteFrames = true; }
  26162. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26163. if (this.bones[i].animations[0]) {
  26164. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26165. }
  26166. }
  26167. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26168. };
  26169. Skeleton.prototype.getAnimationRange = function (name) {
  26170. return this._ranges[name];
  26171. };
  26172. /**
  26173. * Returns as an Array, all AnimationRanges defined on this skeleton
  26174. */
  26175. Skeleton.prototype.getAnimationRanges = function () {
  26176. var animationRanges = [];
  26177. var name;
  26178. var i = 0;
  26179. for (name in this._ranges) {
  26180. animationRanges[i] = this._ranges[name];
  26181. i++;
  26182. }
  26183. return animationRanges;
  26184. };
  26185. /**
  26186. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26187. */
  26188. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26189. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26190. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26191. return false;
  26192. }
  26193. var ret = true;
  26194. var frameOffset = this._getHighestAnimationFrame() + 1;
  26195. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26196. var boneDict = {};
  26197. var sourceBones = source.bones;
  26198. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26199. boneDict[sourceBones[i].name] = sourceBones[i];
  26200. }
  26201. if (this.bones.length !== sourceBones.length) {
  26202. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26203. ret = false;
  26204. }
  26205. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26206. var boneName = this.bones[i].name;
  26207. var sourceBone = boneDict[boneName];
  26208. if (sourceBone) {
  26209. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26210. }
  26211. else {
  26212. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26213. ret = false;
  26214. }
  26215. }
  26216. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26217. var range = source.getAnimationRange(name);
  26218. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26219. return ret;
  26220. };
  26221. Skeleton.prototype.returnToRest = function () {
  26222. for (var index = 0; index < this.bones.length; index++) {
  26223. this.bones[index].returnToRest();
  26224. }
  26225. };
  26226. Skeleton.prototype._getHighestAnimationFrame = function () {
  26227. var ret = 0;
  26228. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26229. if (this.bones[i].animations[0]) {
  26230. var highest = this.bones[i].animations[0].getHighestFrame();
  26231. if (ret < highest) {
  26232. ret = highest;
  26233. }
  26234. }
  26235. }
  26236. return ret;
  26237. };
  26238. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26239. var range = this.getAnimationRange(name);
  26240. if (!range) {
  26241. return null;
  26242. }
  26243. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26244. };
  26245. Skeleton.prototype._markAsDirty = function () {
  26246. this._isDirty = true;
  26247. };
  26248. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26249. this._meshesWithPoseMatrix.push(mesh);
  26250. };
  26251. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26252. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26253. if (index > -1) {
  26254. this._meshesWithPoseMatrix.splice(index, 1);
  26255. }
  26256. };
  26257. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26258. for (var index = 0; index < this.bones.length; index++) {
  26259. var bone = this.bones[index];
  26260. var parentBone = bone.getParent();
  26261. if (parentBone) {
  26262. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26263. }
  26264. else {
  26265. if (initialSkinMatrix) {
  26266. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26267. }
  26268. else {
  26269. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26270. }
  26271. }
  26272. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26273. }
  26274. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26275. };
  26276. Skeleton.prototype.prepare = function () {
  26277. if (!this._isDirty) {
  26278. return;
  26279. }
  26280. if (this.needInitialSkinMatrix) {
  26281. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26282. var mesh = this._meshesWithPoseMatrix[index];
  26283. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26284. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26285. }
  26286. var poseMatrix = mesh.getPoseMatrix();
  26287. // Prepare bones
  26288. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26289. var bone = this.bones[boneIndex];
  26290. if (!bone.getParent()) {
  26291. var matrix = bone.getBaseMatrix();
  26292. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26293. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26294. }
  26295. }
  26296. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26297. }
  26298. }
  26299. else {
  26300. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26301. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26302. }
  26303. this._computeTransformMatrices(this._transformMatrices, null);
  26304. }
  26305. this._isDirty = false;
  26306. this._scene._activeBones += this.bones.length;
  26307. };
  26308. Skeleton.prototype.getAnimatables = function () {
  26309. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26310. this._animatables = [];
  26311. for (var index = 0; index < this.bones.length; index++) {
  26312. this._animatables.push(this.bones[index]);
  26313. }
  26314. }
  26315. return this._animatables;
  26316. };
  26317. Skeleton.prototype.clone = function (name, id) {
  26318. var result = new Skeleton(name, id || name, this._scene);
  26319. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26320. for (var index = 0; index < this.bones.length; index++) {
  26321. var source = this.bones[index];
  26322. var parentBone = null;
  26323. if (source.getParent()) {
  26324. var parentIndex = this.bones.indexOf(source.getParent());
  26325. parentBone = result.bones[parentIndex];
  26326. }
  26327. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26328. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26329. }
  26330. if (this._ranges) {
  26331. result._ranges = {};
  26332. for (var rangeName in this._ranges) {
  26333. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26334. }
  26335. }
  26336. this._isDirty = true;
  26337. return result;
  26338. };
  26339. Skeleton.prototype.dispose = function () {
  26340. this._meshesWithPoseMatrix = [];
  26341. // Animations
  26342. this.getScene().stopAnimation(this);
  26343. // Remove from scene
  26344. this.getScene().removeSkeleton(this);
  26345. };
  26346. Skeleton.prototype.serialize = function () {
  26347. var serializationObject = {};
  26348. serializationObject.name = this.name;
  26349. serializationObject.id = this.id;
  26350. serializationObject.bones = [];
  26351. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26352. for (var index = 0; index < this.bones.length; index++) {
  26353. var bone = this.bones[index];
  26354. var serializedBone = {
  26355. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26356. name: bone.name,
  26357. matrix: bone.getLocalMatrix().toArray(),
  26358. rest: bone.getRestPose().toArray()
  26359. };
  26360. serializationObject.bones.push(serializedBone);
  26361. if (bone.length) {
  26362. serializedBone.length = bone.length;
  26363. }
  26364. if (bone.animations && bone.animations.length > 0) {
  26365. serializedBone.animation = bone.animations[0].serialize();
  26366. }
  26367. serializationObject.ranges = [];
  26368. for (var name in this._ranges) {
  26369. var range = {};
  26370. range.name = name;
  26371. range.from = this._ranges[name].from;
  26372. range.to = this._ranges[name].to;
  26373. serializationObject.ranges.push(range);
  26374. }
  26375. }
  26376. return serializationObject;
  26377. };
  26378. Skeleton.Parse = function (parsedSkeleton, scene) {
  26379. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26380. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26381. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26382. var parsedBone = parsedSkeleton.bones[index];
  26383. var parentBone = null;
  26384. if (parsedBone.parentBoneIndex > -1) {
  26385. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26386. }
  26387. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26388. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26389. if (parsedBone.length) {
  26390. bone.length = parsedBone.length;
  26391. }
  26392. if (parsedBone.animation) {
  26393. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26394. }
  26395. }
  26396. // placed after bones, so createAnimationRange can cascade down
  26397. if (parsedSkeleton.ranges) {
  26398. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26399. var data = parsedSkeleton.ranges[index];
  26400. skeleton.createAnimationRange(data.name, data.from, data.to);
  26401. }
  26402. }
  26403. return skeleton;
  26404. };
  26405. return Skeleton;
  26406. }());
  26407. BABYLON.Skeleton = Skeleton;
  26408. })(BABYLON || (BABYLON = {}));
  26409. var BABYLON;
  26410. (function (BABYLON) {
  26411. var PostProcess = (function () {
  26412. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26414. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26415. this.name = name;
  26416. this.width = -1;
  26417. this.height = -1;
  26418. this._reusable = false;
  26419. this._textures = new BABYLON.SmartArray(2);
  26420. this._currentRenderTextureInd = 0;
  26421. if (camera != null) {
  26422. this._camera = camera;
  26423. this._scene = camera.getScene();
  26424. camera.attachPostProcess(this);
  26425. this._engine = this._scene.getEngine();
  26426. }
  26427. else {
  26428. this._engine = engine;
  26429. }
  26430. this._renderRatio = ratio;
  26431. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26432. this._reusable = reusable || false;
  26433. this._textureType = textureType;
  26434. this._samplers = samplers || [];
  26435. this._samplers.push("textureSampler");
  26436. this._fragmentUrl = fragmentUrl;
  26437. this._parameters = parameters || [];
  26438. this.updateEffect(defines);
  26439. }
  26440. PostProcess.prototype.updateEffect = function (defines) {
  26441. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26442. };
  26443. PostProcess.prototype.isReusable = function () {
  26444. return this._reusable;
  26445. };
  26446. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26447. camera = camera || this._camera;
  26448. var scene = camera.getScene();
  26449. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26450. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26451. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26452. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26453. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26454. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26455. if (this._textures.length > 0) {
  26456. for (var i = 0; i < this._textures.length; i++) {
  26457. this._engine._releaseTexture(this._textures.data[i]);
  26458. }
  26459. this._textures.reset();
  26460. }
  26461. this.width = desiredWidth;
  26462. this.height = desiredHeight;
  26463. 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 }));
  26464. if (this._reusable) {
  26465. 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 }));
  26466. }
  26467. if (this.onSizeChanged) {
  26468. this.onSizeChanged();
  26469. }
  26470. }
  26471. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26472. if (this.onActivate) {
  26473. this.onActivate(camera);
  26474. }
  26475. // Clear
  26476. if (this.clearColor) {
  26477. this._engine.clear(this.clearColor, true, true);
  26478. }
  26479. else {
  26480. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26481. }
  26482. if (this._reusable) {
  26483. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26484. }
  26485. };
  26486. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26487. get: function () {
  26488. return this._effect.isSupported;
  26489. },
  26490. enumerable: true,
  26491. configurable: true
  26492. });
  26493. PostProcess.prototype.apply = function () {
  26494. // Check
  26495. if (!this._effect.isReady())
  26496. return null;
  26497. // States
  26498. this._engine.enableEffect(this._effect);
  26499. this._engine.setState(false);
  26500. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26501. this._engine.setDepthBuffer(false);
  26502. this._engine.setDepthWrite(false);
  26503. // Texture
  26504. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26505. // Parameters
  26506. if (this.onApply) {
  26507. this.onApply(this._effect);
  26508. }
  26509. return this._effect;
  26510. };
  26511. PostProcess.prototype.dispose = function (camera) {
  26512. camera = camera || this._camera;
  26513. if (this._textures.length > 0) {
  26514. for (var i = 0; i < this._textures.length; i++) {
  26515. this._engine._releaseTexture(this._textures.data[i]);
  26516. }
  26517. this._textures.reset();
  26518. }
  26519. if (!camera) {
  26520. return;
  26521. }
  26522. camera.detachPostProcess(this);
  26523. var index = camera._postProcesses.indexOf(this);
  26524. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26525. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26526. }
  26527. };
  26528. return PostProcess;
  26529. }());
  26530. BABYLON.PostProcess = PostProcess;
  26531. })(BABYLON || (BABYLON = {}));
  26532. var BABYLON;
  26533. (function (BABYLON) {
  26534. var PostProcessManager = (function () {
  26535. function PostProcessManager(scene) {
  26536. this._vertexDeclaration = [2];
  26537. this._vertexStrideSize = 2 * 4;
  26538. this._scene = scene;
  26539. }
  26540. PostProcessManager.prototype._prepareBuffers = function () {
  26541. if (this._vertexBuffer) {
  26542. return;
  26543. }
  26544. // VBO
  26545. var vertices = [];
  26546. vertices.push(1, 1);
  26547. vertices.push(-1, 1);
  26548. vertices.push(-1, -1);
  26549. vertices.push(1, -1);
  26550. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26551. // Indices
  26552. var indices = [];
  26553. indices.push(0);
  26554. indices.push(1);
  26555. indices.push(2);
  26556. indices.push(0);
  26557. indices.push(2);
  26558. indices.push(3);
  26559. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26560. };
  26561. // Methods
  26562. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26563. var postProcesses = this._scene.activeCamera._postProcesses;
  26564. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26565. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26566. return false;
  26567. }
  26568. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26569. return true;
  26570. };
  26571. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26572. var engine = this._scene.getEngine();
  26573. for (var index = 0; index < postProcesses.length; index++) {
  26574. if (index < postProcesses.length - 1) {
  26575. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26576. }
  26577. else {
  26578. if (targetTexture) {
  26579. engine.bindFramebuffer(targetTexture);
  26580. }
  26581. else {
  26582. engine.restoreDefaultFramebuffer();
  26583. }
  26584. }
  26585. var pp = postProcesses[index];
  26586. var effect = pp.apply();
  26587. if (effect) {
  26588. if (pp.onBeforeRender) {
  26589. pp.onBeforeRender(effect);
  26590. }
  26591. // VBOs
  26592. this._prepareBuffers();
  26593. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26594. // Draw order
  26595. engine.draw(true, 0, 6);
  26596. if (pp.onAfterRender) {
  26597. pp.onAfterRender(effect);
  26598. }
  26599. }
  26600. }
  26601. // Restore depth buffer
  26602. engine.setDepthBuffer(true);
  26603. engine.setDepthWrite(true);
  26604. };
  26605. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26606. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26607. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26608. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26609. return;
  26610. }
  26611. var engine = this._scene.getEngine();
  26612. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26613. if (index < postProcessesTakenIndices.length - 1) {
  26614. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26615. }
  26616. else {
  26617. if (targetTexture) {
  26618. engine.bindFramebuffer(targetTexture, faceIndex);
  26619. }
  26620. else {
  26621. engine.restoreDefaultFramebuffer();
  26622. }
  26623. }
  26624. if (doNotPresent) {
  26625. break;
  26626. }
  26627. var pp = postProcesses[postProcessesTakenIndices[index]];
  26628. var effect = pp.apply();
  26629. if (effect) {
  26630. if (pp.onBeforeRender) {
  26631. pp.onBeforeRender(effect);
  26632. }
  26633. // VBOs
  26634. this._prepareBuffers();
  26635. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26636. // Draw order
  26637. engine.draw(true, 0, 6);
  26638. if (pp.onAfterRender) {
  26639. pp.onAfterRender(effect);
  26640. }
  26641. }
  26642. }
  26643. // Restore depth buffer
  26644. engine.setDepthBuffer(true);
  26645. engine.setDepthWrite(true);
  26646. };
  26647. PostProcessManager.prototype.dispose = function () {
  26648. if (this._vertexBuffer) {
  26649. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  26650. this._vertexBuffer = null;
  26651. }
  26652. if (this._indexBuffer) {
  26653. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26654. this._indexBuffer = null;
  26655. }
  26656. };
  26657. return PostProcessManager;
  26658. }());
  26659. BABYLON.PostProcessManager = PostProcessManager;
  26660. })(BABYLON || (BABYLON = {}));
  26661. var BABYLON;
  26662. (function (BABYLON) {
  26663. var PassPostProcess = (function (_super) {
  26664. __extends(PassPostProcess, _super);
  26665. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26666. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  26667. }
  26668. return PassPostProcess;
  26669. }(BABYLON.PostProcess));
  26670. BABYLON.PassPostProcess = PassPostProcess;
  26671. })(BABYLON || (BABYLON = {}));
  26672. var BABYLON;
  26673. (function (BABYLON) {
  26674. /**
  26675. * This is a holder class for the physics joint created by the physics plugin.
  26676. * It holds a set of functions to control the underlying joint.
  26677. */
  26678. var PhysicsJoint = (function () {
  26679. function PhysicsJoint(type, jointData) {
  26680. this.type = type;
  26681. this.jointData = jointData;
  26682. jointData.nativeParams = jointData.nativeParams || {};
  26683. }
  26684. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  26685. get: function () {
  26686. return this._physicsJoint;
  26687. },
  26688. set: function (newJoint) {
  26689. if (this._physicsJoint) {
  26690. }
  26691. this._physicsJoint = newJoint;
  26692. },
  26693. enumerable: true,
  26694. configurable: true
  26695. });
  26696. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  26697. set: function (physicsPlugin) {
  26698. this._physicsPlugin = physicsPlugin;
  26699. },
  26700. enumerable: true,
  26701. configurable: true
  26702. });
  26703. /**
  26704. * Execute a function that is physics-plugin specific.
  26705. * @param {Function} func the function that will be executed.
  26706. * It accepts two parameters: the physics world and the physics joint.
  26707. */
  26708. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  26709. func(this._physicsPlugin.world, this._physicsJoint);
  26710. };
  26711. //TODO check if the native joints are the same
  26712. //Joint Types
  26713. PhysicsJoint.DistanceJoint = 0;
  26714. PhysicsJoint.HingeJoint = 1;
  26715. PhysicsJoint.BallAndSocketJoint = 2;
  26716. PhysicsJoint.WheelJoint = 3;
  26717. PhysicsJoint.SliderJoint = 4;
  26718. //OIMO
  26719. PhysicsJoint.PrismaticJoint = 5;
  26720. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  26721. PhysicsJoint.UniversalJoint = 6;
  26722. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  26723. //Cannon
  26724. //Similar to a Ball-Joint. Different in params
  26725. PhysicsJoint.PointToPointJoint = 8;
  26726. //Cannon only at the moment
  26727. PhysicsJoint.SpringJoint = 9;
  26728. return PhysicsJoint;
  26729. }());
  26730. BABYLON.PhysicsJoint = PhysicsJoint;
  26731. /**
  26732. * A class representing a physics distance joint.
  26733. */
  26734. var DistanceJoint = (function (_super) {
  26735. __extends(DistanceJoint, _super);
  26736. function DistanceJoint(jointData) {
  26737. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  26738. }
  26739. /**
  26740. * Update the predefined distance.
  26741. */
  26742. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  26743. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  26744. };
  26745. return DistanceJoint;
  26746. }(PhysicsJoint));
  26747. BABYLON.DistanceJoint = DistanceJoint;
  26748. /**
  26749. * This class represents a single hinge physics joint
  26750. */
  26751. var HingeJoint = (function (_super) {
  26752. __extends(HingeJoint, _super);
  26753. function HingeJoint(jointData) {
  26754. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  26755. }
  26756. /**
  26757. * Set the motor values.
  26758. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26759. * @param {number} force the force to apply
  26760. * @param {number} maxForce max force for this motor.
  26761. */
  26762. HingeJoint.prototype.setMotor = function (force, maxForce) {
  26763. this._physicsPlugin.setMotor(this, force, maxForce);
  26764. };
  26765. /**
  26766. * Set the motor's limits.
  26767. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26768. */
  26769. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  26770. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  26771. };
  26772. return HingeJoint;
  26773. }(PhysicsJoint));
  26774. BABYLON.HingeJoint = HingeJoint;
  26775. /**
  26776. * This class represents a dual hinge physics joint (same as wheel joint)
  26777. */
  26778. var Hinge2Joint = (function (_super) {
  26779. __extends(Hinge2Joint, _super);
  26780. function Hinge2Joint(jointData) {
  26781. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  26782. }
  26783. /**
  26784. * Set the motor values.
  26785. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26786. * @param {number} force the force to apply
  26787. * @param {number} maxForce max force for this motor.
  26788. * @param {motorIndex} the motor's index, 0 or 1.
  26789. */
  26790. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  26791. if (motorIndex === void 0) { motorIndex = 0; }
  26792. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  26793. };
  26794. /**
  26795. * Set the motor limits.
  26796. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26797. * @param {number} upperLimit the upper limit
  26798. * @param {number} lowerLimit lower limit
  26799. * @param {motorIndex} the motor's index, 0 or 1.
  26800. */
  26801. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  26802. if (motorIndex === void 0) { motorIndex = 0; }
  26803. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  26804. };
  26805. return Hinge2Joint;
  26806. }(PhysicsJoint));
  26807. BABYLON.Hinge2Joint = Hinge2Joint;
  26808. })(BABYLON || (BABYLON = {}));
  26809. var BABYLON;
  26810. (function (BABYLON) {
  26811. var PhysicsImpostor = (function () {
  26812. function PhysicsImpostor(object, type, _options, _scene) {
  26813. var _this = this;
  26814. if (_options === void 0) { _options = { mass: 0 }; }
  26815. this.object = object;
  26816. this.type = type;
  26817. this._options = _options;
  26818. this._scene = _scene;
  26819. this._bodyUpdateRequired = false;
  26820. this._onBeforePhysicsStepCallbacks = new Array();
  26821. this._onAfterPhysicsStepCallbacks = new Array();
  26822. this._onPhysicsCollideCallbacks = [];
  26823. this._deltaPosition = BABYLON.Vector3.Zero();
  26824. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  26825. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  26826. /**
  26827. * this function is executed by the physics engine.
  26828. */
  26829. this.beforeStep = function () {
  26830. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  26831. //conjugate deltaRotation
  26832. if (_this._deltaRotationConjugated) {
  26833. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  26834. }
  26835. else {
  26836. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  26837. }
  26838. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  26839. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  26840. func(_this);
  26841. });
  26842. };
  26843. /**
  26844. * this function is executed by the physics engine.
  26845. */
  26846. this.afterStep = function () {
  26847. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  26848. func(_this);
  26849. });
  26850. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  26851. _this.object.position.addInPlace(_this._deltaPosition);
  26852. if (_this._deltaRotation) {
  26853. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  26854. }
  26855. };
  26856. //event and body object due to cannon's event-based architecture.
  26857. this.onCollide = function (e) {
  26858. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  26859. if (otherImpostor) {
  26860. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  26861. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  26862. }).forEach(function (obj) {
  26863. obj.callback(_this, otherImpostor);
  26864. });
  26865. }
  26866. };
  26867. //sanity check!
  26868. if (!this.object) {
  26869. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  26870. return;
  26871. }
  26872. //legacy support for old syntax.
  26873. if (!this._scene && object.getScene) {
  26874. this._scene = object.getScene();
  26875. }
  26876. this._physicsEngine = this._scene.getPhysicsEngine();
  26877. if (!this._physicsEngine) {
  26878. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  26879. }
  26880. else {
  26881. //set the object's quaternion, if not set
  26882. if (!this.object.rotationQuaternion) {
  26883. if (this.object.rotation) {
  26884. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  26885. }
  26886. else {
  26887. this.object.rotationQuaternion = new BABYLON.Quaternion();
  26888. }
  26889. }
  26890. //default options params
  26891. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  26892. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  26893. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  26894. this._joints = [];
  26895. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  26896. if (!this.object.parent) {
  26897. this._init();
  26898. }
  26899. }
  26900. }
  26901. /**
  26902. * This function will completly initialize this impostor.
  26903. * It will create a new body - but only if this mesh has no parent.
  26904. * If it has, this impostor will not be used other than to define the impostor
  26905. * of the child mesh.
  26906. */
  26907. PhysicsImpostor.prototype._init = function () {
  26908. this._physicsEngine.removeImpostor(this);
  26909. this.physicsBody = null;
  26910. this._parent = this._parent || this._getPhysicsParent();
  26911. if (!this.parent) {
  26912. this._physicsEngine.addImpostor(this);
  26913. }
  26914. };
  26915. PhysicsImpostor.prototype._getPhysicsParent = function () {
  26916. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  26917. var parentMesh = this.object.parent;
  26918. return parentMesh.physicsImpostor;
  26919. }
  26920. return;
  26921. };
  26922. /**
  26923. * Should a new body be generated.
  26924. */
  26925. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  26926. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  26927. };
  26928. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  26929. this.forceUpdate();
  26930. };
  26931. /**
  26932. * Force a regeneration of this or the parent's impostor's body.
  26933. * Use under cautious - This will remove all joints already implemented.
  26934. */
  26935. PhysicsImpostor.prototype.forceUpdate = function () {
  26936. this._init();
  26937. if (this.parent) {
  26938. this.parent.forceUpdate();
  26939. }
  26940. };
  26941. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  26942. /*public get mesh(): AbstractMesh {
  26943. return this._mesh;
  26944. }*/
  26945. /**
  26946. * Gets the body that holds this impostor. Either its own, or its parent.
  26947. */
  26948. get: function () {
  26949. return this._parent ? this._parent.physicsBody : this._physicsBody;
  26950. },
  26951. /**
  26952. * Set the physics body. Used mainly by the physics engine/plugin
  26953. */
  26954. set: function (physicsBody) {
  26955. if (this._physicsBody) {
  26956. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  26957. }
  26958. this._physicsBody = physicsBody;
  26959. this.resetUpdateFlags();
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  26965. get: function () {
  26966. return this._parent;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  26972. this._bodyUpdateRequired = false;
  26973. };
  26974. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  26975. if (this.object.getBoundingInfo) {
  26976. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  26977. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  26978. }
  26979. else {
  26980. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  26981. }
  26982. };
  26983. PhysicsImpostor.prototype.getObjectCenter = function () {
  26984. if (this.object.getBoundingInfo) {
  26985. return this.object.getBoundingInfo().boundingBox.center;
  26986. }
  26987. else {
  26988. return this.object.position;
  26989. }
  26990. };
  26991. /**
  26992. * Get a specific parametes from the options parameter.
  26993. */
  26994. PhysicsImpostor.prototype.getParam = function (paramName) {
  26995. return this._options[paramName];
  26996. };
  26997. /**
  26998. * Sets a specific parameter in the options given to the physics plugin
  26999. */
  27000. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27001. this._options[paramName] = value;
  27002. this._bodyUpdateRequired = true;
  27003. };
  27004. /**
  27005. * Specifically change the body's mass option. Won't recreate the physics body object
  27006. */
  27007. PhysicsImpostor.prototype.setMass = function (mass) {
  27008. if (this.getParam("mass") !== mass) {
  27009. this.setParam("mass", mass);
  27010. }
  27011. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27012. };
  27013. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27014. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27015. };
  27016. /**
  27017. * Set the body's linear velocity.
  27018. */
  27019. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27020. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27021. };
  27022. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27023. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27024. };
  27025. /**
  27026. * Set the body's linear velocity.
  27027. */
  27028. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27029. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27030. };
  27031. /**
  27032. * Execute a function with the physics plugin native code.
  27033. * Provide a function the will have two variables - the world object and the physics body object.
  27034. */
  27035. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27036. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27037. };
  27038. /**
  27039. * Register a function that will be executed before the physics world is stepping forward.
  27040. */
  27041. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27042. this._onBeforePhysicsStepCallbacks.push(func);
  27043. };
  27044. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27045. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27046. if (index > -1) {
  27047. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27048. }
  27049. else {
  27050. BABYLON.Tools.Warn("Function to remove was not found");
  27051. }
  27052. };
  27053. /**
  27054. * Register a function that will be executed after the physics step
  27055. */
  27056. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27057. this._onAfterPhysicsStepCallbacks.push(func);
  27058. };
  27059. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27060. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27061. if (index > -1) {
  27062. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27063. }
  27064. else {
  27065. BABYLON.Tools.Warn("Function to remove was not found");
  27066. }
  27067. };
  27068. /**
  27069. * register a function that will be executed when this impostor collides against a different body.
  27070. */
  27071. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27072. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27073. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27074. };
  27075. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27076. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27077. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27078. if (index > -1) {
  27079. this._onPhysicsCollideCallbacks.splice(index, 1);
  27080. }
  27081. else {
  27082. BABYLON.Tools.Warn("Function to remove was not found");
  27083. }
  27084. };
  27085. /**
  27086. * Apply a force
  27087. */
  27088. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27089. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27090. };
  27091. /**
  27092. * Apply an impulse
  27093. */
  27094. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27095. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27096. };
  27097. /**
  27098. * A help function to create a joint.
  27099. */
  27100. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27101. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27102. this.addJoint(otherImpostor, joint);
  27103. };
  27104. /**
  27105. * Add a joint to this impostor with a different impostor.
  27106. */
  27107. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27108. this._joints.push({
  27109. otherImpostor: otherImpostor,
  27110. joint: joint
  27111. });
  27112. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27113. };
  27114. /**
  27115. * Will keep this body still, in a sleep mode.
  27116. */
  27117. PhysicsImpostor.prototype.sleep = function () {
  27118. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27119. };
  27120. /**
  27121. * Wake the body up.
  27122. */
  27123. PhysicsImpostor.prototype.wakeUp = function () {
  27124. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27125. };
  27126. PhysicsImpostor.prototype.clone = function (newObject) {
  27127. if (!newObject)
  27128. return null;
  27129. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27130. };
  27131. PhysicsImpostor.prototype.dispose = function () {
  27132. this.physicsBody = null;
  27133. if (this.parent) {
  27134. this.parent.forceUpdate();
  27135. }
  27136. else {
  27137. }
  27138. };
  27139. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27140. this._deltaPosition.copyFrom(position);
  27141. };
  27142. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27143. if (!this._deltaRotation) {
  27144. this._deltaRotation = new BABYLON.Quaternion();
  27145. }
  27146. this._deltaRotation.copyFrom(rotation);
  27147. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27148. };
  27149. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27150. //Impostor types
  27151. PhysicsImpostor.NoImpostor = 0;
  27152. PhysicsImpostor.SphereImpostor = 1;
  27153. PhysicsImpostor.BoxImpostor = 2;
  27154. PhysicsImpostor.PlaneImpostor = 3;
  27155. PhysicsImpostor.MeshImpostor = 4;
  27156. PhysicsImpostor.CylinderImpostor = 7;
  27157. PhysicsImpostor.ParticleImpostor = 8;
  27158. PhysicsImpostor.HeightmapImpostor = 9;
  27159. return PhysicsImpostor;
  27160. }());
  27161. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27162. })(BABYLON || (BABYLON = {}));
  27163. var BABYLON;
  27164. (function (BABYLON) {
  27165. var PhysicsEngine = (function () {
  27166. function PhysicsEngine(gravity, _physicsPlugin) {
  27167. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27168. this._physicsPlugin = _physicsPlugin;
  27169. //new methods and parameters
  27170. this._impostors = [];
  27171. this._joints = [];
  27172. if (!this._physicsPlugin.isSupported()) {
  27173. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27174. + "Please make sure it is included.");
  27175. }
  27176. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27177. this.setGravity(gravity);
  27178. this.setTimeStep();
  27179. }
  27180. PhysicsEngine.prototype.setGravity = function (gravity) {
  27181. this.gravity = gravity;
  27182. this._physicsPlugin.setGravity(this.gravity);
  27183. };
  27184. /**
  27185. * Set the time step of the physics engine.
  27186. * default is 1/60.
  27187. * To slow it down, enter 1/600 for example.
  27188. * To speed it up, 1/30
  27189. * @param {number} newTimeStep the new timestep to apply to this world.
  27190. */
  27191. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27192. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27193. this._physicsPlugin.setTimeStep(newTimeStep);
  27194. };
  27195. PhysicsEngine.prototype.dispose = function () {
  27196. this._impostors.forEach(function (impostor) {
  27197. impostor.dispose();
  27198. });
  27199. this._physicsPlugin.dispose();
  27200. };
  27201. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27202. return this._physicsPlugin.name;
  27203. };
  27204. /**
  27205. * Adding a new impostor for the impostor tracking.
  27206. * This will be done by the impostor itself.
  27207. * @param {PhysicsImpostor} impostor the impostor to add
  27208. */
  27209. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27210. impostor.uniqueId = this._impostors.push(impostor);
  27211. //if no parent, generate the body
  27212. if (!impostor.parent) {
  27213. this._physicsPlugin.generatePhysicsBody(impostor);
  27214. }
  27215. };
  27216. /**
  27217. * Remove an impostor from the engine.
  27218. * This impostor and its mesh will not longer be updated by the physics engine.
  27219. * @param {PhysicsImpostor} impostor the impostor to remove
  27220. */
  27221. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27222. var index = this._impostors.indexOf(impostor);
  27223. if (index > -1) {
  27224. var removed = this._impostors.splice(index, 1);
  27225. //Is it needed?
  27226. if (removed.length) {
  27227. //this will also remove it from the world.
  27228. removed[0].physicsBody = null;
  27229. }
  27230. }
  27231. };
  27232. /**
  27233. * Add a joint to the physics engine
  27234. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27235. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27236. * @param {PhysicsJoint} the joint that will connect both impostors.
  27237. */
  27238. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27239. var impostorJoint = {
  27240. mainImpostor: mainImpostor,
  27241. connectedImpostor: connectedImpostor,
  27242. joint: joint
  27243. };
  27244. joint.physicsPlugin = this._physicsPlugin;
  27245. this._joints.push(impostorJoint);
  27246. this._physicsPlugin.generateJoint(impostorJoint);
  27247. };
  27248. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27249. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27250. return (impostorJoint.connectedImpostor === connectedImpostor
  27251. && impostorJoint.joint === joint
  27252. && impostorJoint.mainImpostor === mainImpostor);
  27253. });
  27254. if (matchingJoints.length) {
  27255. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27256. }
  27257. };
  27258. /**
  27259. * Called by the scene. no need to call it.
  27260. */
  27261. PhysicsEngine.prototype._step = function (delta) {
  27262. var _this = this;
  27263. //check if any mesh has no body / requires an update
  27264. this._impostors.forEach(function (impostor) {
  27265. if (impostor.isBodyInitRequired()) {
  27266. _this._physicsPlugin.generatePhysicsBody(impostor);
  27267. }
  27268. });
  27269. if (delta > 0.1) {
  27270. delta = 0.1;
  27271. }
  27272. else if (delta <= 0) {
  27273. delta = 1.0 / 60.0;
  27274. }
  27275. this._physicsPlugin.executeStep(delta, this._impostors);
  27276. };
  27277. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27278. return this._physicsPlugin;
  27279. };
  27280. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27281. for (var i = 0; i < this._impostors.length; ++i) {
  27282. if (this._impostors[i].object === object) {
  27283. return this._impostors[i];
  27284. }
  27285. }
  27286. };
  27287. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27288. for (var i = 0; i < this._impostors.length; ++i) {
  27289. if (this._impostors[i].physicsBody === body) {
  27290. return this._impostors[i];
  27291. }
  27292. }
  27293. };
  27294. // Statics, Legacy support.
  27295. /**
  27296. * @Deprecated
  27297. *
  27298. */
  27299. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27300. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27301. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27302. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27303. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27304. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27305. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27306. PhysicsEngine.CapsuleImpostor = -1;
  27307. PhysicsEngine.ConeImpostor = -1;
  27308. PhysicsEngine.ConvexHullImpostor = -1;
  27309. PhysicsEngine.Epsilon = 0.001;
  27310. return PhysicsEngine;
  27311. }());
  27312. BABYLON.PhysicsEngine = PhysicsEngine;
  27313. })(BABYLON || (BABYLON = {}));
  27314. var BABYLON;
  27315. (function (BABYLON) {
  27316. var VertexData = (function () {
  27317. function VertexData() {
  27318. }
  27319. VertexData.prototype.set = function (data, kind) {
  27320. switch (kind) {
  27321. case BABYLON.VertexBuffer.PositionKind:
  27322. this.positions = data;
  27323. break;
  27324. case BABYLON.VertexBuffer.NormalKind:
  27325. this.normals = data;
  27326. break;
  27327. case BABYLON.VertexBuffer.UVKind:
  27328. this.uvs = data;
  27329. break;
  27330. case BABYLON.VertexBuffer.UV2Kind:
  27331. this.uvs2 = data;
  27332. break;
  27333. case BABYLON.VertexBuffer.UV3Kind:
  27334. this.uvs3 = data;
  27335. break;
  27336. case BABYLON.VertexBuffer.UV4Kind:
  27337. this.uvs4 = data;
  27338. break;
  27339. case BABYLON.VertexBuffer.UV5Kind:
  27340. this.uvs5 = data;
  27341. break;
  27342. case BABYLON.VertexBuffer.UV6Kind:
  27343. this.uvs6 = data;
  27344. break;
  27345. case BABYLON.VertexBuffer.ColorKind:
  27346. this.colors = data;
  27347. break;
  27348. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27349. this.matricesIndices = data;
  27350. break;
  27351. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27352. this.matricesWeights = data;
  27353. break;
  27354. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27355. this.matricesIndicesExtra = data;
  27356. break;
  27357. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27358. this.matricesWeightsExtra = data;
  27359. break;
  27360. }
  27361. };
  27362. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27363. this._applyTo(mesh, updatable);
  27364. };
  27365. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27366. this._applyTo(geometry, updatable);
  27367. };
  27368. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27369. this._update(mesh);
  27370. };
  27371. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27372. this._update(geometry);
  27373. };
  27374. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27375. if (this.positions) {
  27376. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27377. }
  27378. if (this.normals) {
  27379. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27380. }
  27381. if (this.uvs) {
  27382. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27383. }
  27384. if (this.uvs2) {
  27385. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27386. }
  27387. if (this.uvs3) {
  27388. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27389. }
  27390. if (this.uvs4) {
  27391. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27392. }
  27393. if (this.uvs5) {
  27394. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27395. }
  27396. if (this.uvs6) {
  27397. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27398. }
  27399. if (this.colors) {
  27400. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27401. }
  27402. if (this.matricesIndices) {
  27403. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27404. }
  27405. if (this.matricesWeights) {
  27406. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27407. }
  27408. if (this.matricesIndicesExtra) {
  27409. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27410. }
  27411. if (this.matricesWeightsExtra) {
  27412. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27413. }
  27414. if (this.indices) {
  27415. meshOrGeometry.setIndices(this.indices);
  27416. }
  27417. };
  27418. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27419. if (this.positions) {
  27420. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27421. }
  27422. if (this.normals) {
  27423. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27424. }
  27425. if (this.uvs) {
  27426. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27427. }
  27428. if (this.uvs2) {
  27429. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27430. }
  27431. if (this.uvs3) {
  27432. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27433. }
  27434. if (this.uvs4) {
  27435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27436. }
  27437. if (this.uvs5) {
  27438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27439. }
  27440. if (this.uvs6) {
  27441. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27442. }
  27443. if (this.colors) {
  27444. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27445. }
  27446. if (this.matricesIndices) {
  27447. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27448. }
  27449. if (this.matricesWeights) {
  27450. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27451. }
  27452. if (this.matricesIndicesExtra) {
  27453. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27454. }
  27455. if (this.matricesWeightsExtra) {
  27456. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27457. }
  27458. if (this.indices) {
  27459. meshOrGeometry.setIndices(this.indices);
  27460. }
  27461. };
  27462. VertexData.prototype.transform = function (matrix) {
  27463. var transformed = BABYLON.Vector3.Zero();
  27464. var index;
  27465. if (this.positions) {
  27466. var position = BABYLON.Vector3.Zero();
  27467. for (index = 0; index < this.positions.length; index += 3) {
  27468. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27469. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27470. this.positions[index] = transformed.x;
  27471. this.positions[index + 1] = transformed.y;
  27472. this.positions[index + 2] = transformed.z;
  27473. }
  27474. }
  27475. if (this.normals) {
  27476. var normal = BABYLON.Vector3.Zero();
  27477. for (index = 0; index < this.normals.length; index += 3) {
  27478. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27479. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27480. this.normals[index] = transformed.x;
  27481. this.normals[index + 1] = transformed.y;
  27482. this.normals[index + 2] = transformed.z;
  27483. }
  27484. }
  27485. };
  27486. VertexData.prototype.merge = function (other) {
  27487. if (other.indices) {
  27488. if (!this.indices) {
  27489. this.indices = [];
  27490. }
  27491. var offset = this.positions ? this.positions.length / 3 : 0;
  27492. for (var index = 0; index < other.indices.length; index++) {
  27493. //TODO check type - if Int32Array!
  27494. this.indices.push(other.indices[index] + offset);
  27495. }
  27496. }
  27497. this.positions = this._mergeElement(this.positions, other.positions);
  27498. this.normals = this._mergeElement(this.normals, other.normals);
  27499. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27500. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27501. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27502. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27503. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27504. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27505. this.colors = this._mergeElement(this.colors, other.colors);
  27506. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27507. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27508. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27509. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27510. };
  27511. VertexData.prototype._mergeElement = function (source, other) {
  27512. if (!other)
  27513. return source;
  27514. if (!source)
  27515. return other;
  27516. var len = other.length + source.length;
  27517. var isSrcTypedArray = source instanceof Float32Array;
  27518. var isOthTypedArray = other instanceof Float32Array;
  27519. // use non-loop method when the source is Float32Array
  27520. if (isSrcTypedArray) {
  27521. var ret32 = new Float32Array(len);
  27522. ret32.set(source);
  27523. ret32.set(other, source.length);
  27524. return ret32;
  27525. }
  27526. else if (!isOthTypedArray) {
  27527. return source.concat(other);
  27528. }
  27529. else {
  27530. var ret = source.slice(0); // copy source to a separate array
  27531. for (var i = 0, len = other.length; i < len; i++) {
  27532. ret.push(other[i]);
  27533. }
  27534. return ret;
  27535. }
  27536. };
  27537. VertexData.prototype.serialize = function () {
  27538. var serializationObject = this.serialize();
  27539. if (this.positions) {
  27540. serializationObject.positions = this.positions;
  27541. }
  27542. if (this.normals) {
  27543. serializationObject.normals = this.normals;
  27544. }
  27545. if (this.uvs) {
  27546. serializationObject.uvs = this.uvs;
  27547. }
  27548. if (this.uvs2) {
  27549. serializationObject.uvs2 = this.uvs2;
  27550. }
  27551. if (this.uvs3) {
  27552. serializationObject.uvs3 = this.uvs3;
  27553. }
  27554. if (this.uvs4) {
  27555. serializationObject.uvs4 = this.uvs4;
  27556. }
  27557. if (this.uvs5) {
  27558. serializationObject.uvs5 = this.uvs5;
  27559. }
  27560. if (this.uvs6) {
  27561. serializationObject.uvs6 = this.uvs6;
  27562. }
  27563. if (this.colors) {
  27564. serializationObject.colors = this.colors;
  27565. }
  27566. if (this.matricesIndices) {
  27567. serializationObject.matricesIndices = this.matricesIndices;
  27568. serializationObject.matricesIndices._isExpanded = true;
  27569. }
  27570. if (this.matricesWeights) {
  27571. serializationObject.matricesWeights = this.matricesWeights;
  27572. }
  27573. if (this.matricesIndicesExtra) {
  27574. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27575. serializationObject.matricesIndicesExtra._isExpanded = true;
  27576. }
  27577. if (this.matricesWeightsExtra) {
  27578. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27579. }
  27580. serializationObject.indices = this.indices;
  27581. return serializationObject;
  27582. };
  27583. // Statics
  27584. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27585. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27586. };
  27587. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  27588. return VertexData._ExtractFrom(geometry, copyWhenShared);
  27589. };
  27590. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  27591. var result = new VertexData();
  27592. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27593. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  27594. }
  27595. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27596. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  27597. }
  27598. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27599. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  27600. }
  27601. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27602. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  27603. }
  27604. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27605. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  27606. }
  27607. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27608. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  27609. }
  27610. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27611. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  27612. }
  27613. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27614. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  27615. }
  27616. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27617. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  27618. }
  27619. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27620. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  27621. }
  27622. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27623. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  27624. }
  27625. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27626. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  27627. }
  27628. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27629. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  27630. }
  27631. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27632. return result;
  27633. };
  27634. VertexData.CreateRibbon = function (options) {
  27635. var pathArray = options.pathArray;
  27636. var closeArray = options.closeArray || false;
  27637. var closePath = options.closePath || false;
  27638. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27639. var offset = options.offset || defaultOffset;
  27640. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27641. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27642. var positions = [];
  27643. var indices = [];
  27644. var normals = [];
  27645. var uvs = [];
  27646. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27647. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27648. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27649. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27650. var minlg; // minimal length among all paths from pathArray
  27651. var lg = []; // array of path lengths : nb of vertex per path
  27652. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27653. var p; // path iterator
  27654. var i; // point iterator
  27655. var j; // point iterator
  27656. // if single path in pathArray
  27657. if (pathArray.length < 2) {
  27658. var ar1 = [];
  27659. var ar2 = [];
  27660. for (i = 0; i < pathArray[0].length - offset; i++) {
  27661. ar1.push(pathArray[0][i]);
  27662. ar2.push(pathArray[0][i + offset]);
  27663. }
  27664. pathArray = [ar1, ar2];
  27665. }
  27666. // positions and horizontal distances (u)
  27667. var idc = 0;
  27668. var closePathCorr = (closePath) ? 1 : 0;
  27669. var path;
  27670. var l;
  27671. minlg = pathArray[0].length;
  27672. var vectlg;
  27673. var dist;
  27674. for (p = 0; p < pathArray.length; p++) {
  27675. uTotalDistance[p] = 0;
  27676. us[p] = [0];
  27677. path = pathArray[p];
  27678. l = path.length;
  27679. minlg = (minlg < l) ? minlg : l;
  27680. j = 0;
  27681. while (j < l) {
  27682. positions.push(path[j].x, path[j].y, path[j].z);
  27683. if (j > 0) {
  27684. vectlg = path[j].subtract(path[j - 1]).length();
  27685. dist = vectlg + uTotalDistance[p];
  27686. us[p].push(dist);
  27687. uTotalDistance[p] = dist;
  27688. }
  27689. j++;
  27690. }
  27691. if (closePath) {
  27692. j--;
  27693. positions.push(path[0].x, path[0].y, path[0].z);
  27694. vectlg = path[j].subtract(path[0]).length();
  27695. dist = vectlg + uTotalDistance[p];
  27696. us[p].push(dist);
  27697. uTotalDistance[p] = dist;
  27698. }
  27699. lg[p] = l + closePathCorr;
  27700. idx[p] = idc;
  27701. idc += (l + closePathCorr);
  27702. }
  27703. // vertical distances (v)
  27704. var path1;
  27705. var path2;
  27706. var vertex1;
  27707. var vertex2;
  27708. for (i = 0; i < minlg + closePathCorr; i++) {
  27709. vTotalDistance[i] = 0;
  27710. vs[i] = [0];
  27711. for (p = 0; p < pathArray.length - 1; p++) {
  27712. path1 = pathArray[p];
  27713. path2 = pathArray[p + 1];
  27714. if (i === minlg) {
  27715. vertex1 = path1[0];
  27716. vertex2 = path2[0];
  27717. }
  27718. else {
  27719. vertex1 = path1[i];
  27720. vertex2 = path2[i];
  27721. }
  27722. vectlg = vertex2.subtract(vertex1).length();
  27723. dist = vectlg + vTotalDistance[i];
  27724. vs[i].push(dist);
  27725. vTotalDistance[i] = dist;
  27726. }
  27727. if (closeArray) {
  27728. path1 = pathArray[p];
  27729. path2 = pathArray[0];
  27730. if (i === minlg) {
  27731. vertex2 = path2[0];
  27732. }
  27733. vectlg = vertex2.subtract(vertex1).length();
  27734. dist = vectlg + vTotalDistance[i];
  27735. vTotalDistance[i] = dist;
  27736. }
  27737. }
  27738. // uvs
  27739. var u;
  27740. var v;
  27741. for (p = 0; p < pathArray.length; p++) {
  27742. for (i = 0; i < minlg + closePathCorr; i++) {
  27743. u = us[p][i] / uTotalDistance[p];
  27744. v = vs[i][p] / vTotalDistance[i];
  27745. uvs.push(u, v);
  27746. }
  27747. }
  27748. // indices
  27749. p = 0; // path index
  27750. var pi = 0; // positions array index
  27751. var l1 = lg[p] - 1; // path1 length
  27752. var l2 = lg[p + 1] - 1; // path2 length
  27753. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27754. var shft = idx[1] - idx[0]; // shift
  27755. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27756. while (pi <= min && p < path1nb) {
  27757. // 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
  27758. indices.push(pi, pi + shft, pi + 1);
  27759. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27760. pi += 1;
  27761. if (pi === min) {
  27762. p++;
  27763. if (p === lg.length - 1) {
  27764. shft = idx[0] - idx[p];
  27765. l1 = lg[p] - 1;
  27766. l2 = lg[0] - 1;
  27767. }
  27768. else {
  27769. shft = idx[p + 1] - idx[p];
  27770. l1 = lg[p] - 1;
  27771. l2 = lg[p + 1] - 1;
  27772. }
  27773. pi = idx[p];
  27774. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27775. }
  27776. }
  27777. // normals
  27778. VertexData.ComputeNormals(positions, indices, normals);
  27779. if (closePath) {
  27780. var indexFirst = 0;
  27781. var indexLast = 0;
  27782. for (p = 0; p < pathArray.length; p++) {
  27783. indexFirst = idx[p] * 3;
  27784. if (p + 1 < pathArray.length) {
  27785. indexLast = (idx[p + 1] - 1) * 3;
  27786. }
  27787. else {
  27788. indexLast = normals.length - 3;
  27789. }
  27790. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27791. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27792. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27793. normals[indexLast] = normals[indexFirst];
  27794. normals[indexLast + 1] = normals[indexFirst + 1];
  27795. normals[indexLast + 2] = normals[indexFirst + 2];
  27796. }
  27797. }
  27798. // sides
  27799. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27800. // Result
  27801. var vertexData = new VertexData();
  27802. vertexData.indices = indices;
  27803. vertexData.positions = positions;
  27804. vertexData.normals = normals;
  27805. vertexData.uvs = uvs;
  27806. if (closePath) {
  27807. vertexData._idx = idx;
  27808. }
  27809. return vertexData;
  27810. };
  27811. VertexData.CreateBox = function (options) {
  27812. var normalsSource = [
  27813. new BABYLON.Vector3(0, 0, 1),
  27814. new BABYLON.Vector3(0, 0, -1),
  27815. new BABYLON.Vector3(1, 0, 0),
  27816. new BABYLON.Vector3(-1, 0, 0),
  27817. new BABYLON.Vector3(0, 1, 0),
  27818. new BABYLON.Vector3(0, -1, 0)
  27819. ];
  27820. var indices = [];
  27821. var positions = [];
  27822. var normals = [];
  27823. var uvs = [];
  27824. var width = options.width || options.size || 1;
  27825. var height = options.height || options.size || 1;
  27826. var depth = options.depth || options.size || 1;
  27827. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27828. var faceUV = options.faceUV || new Array(6);
  27829. var faceColors = options.faceColors;
  27830. var colors = [];
  27831. // default face colors and UV if undefined
  27832. for (var f = 0; f < 6; f++) {
  27833. if (faceUV[f] === undefined) {
  27834. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27835. }
  27836. if (faceColors && faceColors[f] === undefined) {
  27837. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27838. }
  27839. }
  27840. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27841. // Create each face in turn.
  27842. for (var index = 0; index < normalsSource.length; index++) {
  27843. var normal = normalsSource[index];
  27844. // Get two vectors perpendicular to the face normal and to each other.
  27845. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27846. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27847. // Six indices (two triangles) per face.
  27848. var verticesLength = positions.length / 3;
  27849. indices.push(verticesLength);
  27850. indices.push(verticesLength + 1);
  27851. indices.push(verticesLength + 2);
  27852. indices.push(verticesLength);
  27853. indices.push(verticesLength + 2);
  27854. indices.push(verticesLength + 3);
  27855. // Four vertices per face.
  27856. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27857. positions.push(vertex.x, vertex.y, vertex.z);
  27858. normals.push(normal.x, normal.y, normal.z);
  27859. uvs.push(faceUV[index].z, faceUV[index].w);
  27860. if (faceColors) {
  27861. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27862. }
  27863. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27864. positions.push(vertex.x, vertex.y, vertex.z);
  27865. normals.push(normal.x, normal.y, normal.z);
  27866. uvs.push(faceUV[index].x, faceUV[index].w);
  27867. if (faceColors) {
  27868. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27869. }
  27870. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27871. positions.push(vertex.x, vertex.y, vertex.z);
  27872. normals.push(normal.x, normal.y, normal.z);
  27873. uvs.push(faceUV[index].x, faceUV[index].y);
  27874. if (faceColors) {
  27875. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27876. }
  27877. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27878. positions.push(vertex.x, vertex.y, vertex.z);
  27879. normals.push(normal.x, normal.y, normal.z);
  27880. uvs.push(faceUV[index].z, faceUV[index].y);
  27881. if (faceColors) {
  27882. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27883. }
  27884. }
  27885. // sides
  27886. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27887. // Result
  27888. var vertexData = new VertexData();
  27889. vertexData.indices = indices;
  27890. vertexData.positions = positions;
  27891. vertexData.normals = normals;
  27892. vertexData.uvs = uvs;
  27893. if (faceColors) {
  27894. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27895. vertexData.colors = totalColors;
  27896. }
  27897. return vertexData;
  27898. };
  27899. VertexData.CreateSphere = function (options) {
  27900. var segments = options.segments || 32;
  27901. var diameterX = options.diameterX || options.diameter || 1;
  27902. var diameterY = options.diameterY || options.diameter || 1;
  27903. var diameterZ = options.diameterZ || options.diameter || 1;
  27904. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27905. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27906. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27907. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27908. var totalZRotationSteps = 2 + segments;
  27909. var totalYRotationSteps = 2 * totalZRotationSteps;
  27910. var indices = [];
  27911. var positions = [];
  27912. var normals = [];
  27913. var uvs = [];
  27914. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27915. var normalizedZ = zRotationStep / totalZRotationSteps;
  27916. var angleZ = normalizedZ * Math.PI * slice;
  27917. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27918. var normalizedY = yRotationStep / totalYRotationSteps;
  27919. var angleY = normalizedY * Math.PI * 2 * arc;
  27920. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27921. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27922. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27923. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27924. var vertex = complete.multiply(radius);
  27925. var normal = complete.divide(radius).normalize();
  27926. positions.push(vertex.x, vertex.y, vertex.z);
  27927. normals.push(normal.x, normal.y, normal.z);
  27928. uvs.push(normalizedY, normalizedZ);
  27929. }
  27930. if (zRotationStep > 0) {
  27931. var verticesCount = positions.length / 3;
  27932. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27933. indices.push((firstIndex));
  27934. indices.push((firstIndex + 1));
  27935. indices.push(firstIndex + totalYRotationSteps + 1);
  27936. indices.push((firstIndex + totalYRotationSteps + 1));
  27937. indices.push((firstIndex + 1));
  27938. indices.push((firstIndex + totalYRotationSteps + 2));
  27939. }
  27940. }
  27941. }
  27942. // Sides
  27943. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27944. // Result
  27945. var vertexData = new VertexData();
  27946. vertexData.indices = indices;
  27947. vertexData.positions = positions;
  27948. vertexData.normals = normals;
  27949. vertexData.uvs = uvs;
  27950. return vertexData;
  27951. };
  27952. // Cylinder and cone
  27953. VertexData.CreateCylinder = function (options) {
  27954. var height = options.height || 2;
  27955. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27956. var diameterBottom = options.diameterBottom || options.diameter || 1;
  27957. var tessellation = options.tessellation || 24;
  27958. var subdivisions = options.subdivisions || 1;
  27959. var hasRings = options.hasRings;
  27960. var enclose = options.enclose;
  27961. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27962. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27963. var faceUV = options.faceUV || new Array(3);
  27964. var faceColors = options.faceColors;
  27965. // default face colors and UV if undefined
  27966. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27967. var ringNb = (hasRings) ? subdivisions : 1;
  27968. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27969. var f;
  27970. for (f = 0; f < surfaceNb; f++) {
  27971. if (faceColors && faceColors[f] === undefined) {
  27972. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27973. }
  27974. }
  27975. for (f = 0; f < surfaceNb; f++) {
  27976. if (faceUV && faceUV[f] === undefined) {
  27977. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27978. }
  27979. }
  27980. var indices = [];
  27981. var positions = [];
  27982. var normals = [];
  27983. var uvs = [];
  27984. var colors = [];
  27985. var angle_step = Math.PI * 2 * arc / tessellation;
  27986. var angle;
  27987. var h;
  27988. var radius;
  27989. var tan = (diameterBottom - diameterTop) / 2 / height;
  27990. var ringVertex = BABYLON.Vector3.Zero();
  27991. var ringNormal = BABYLON.Vector3.Zero();
  27992. var ringFirstVertex = BABYLON.Vector3.Zero();
  27993. var ringFirstNormal = BABYLON.Vector3.Zero();
  27994. var quadNormal = BABYLON.Vector3.Zero();
  27995. var Y = BABYLON.Axis.Y;
  27996. // positions, normals, uvs
  27997. var i;
  27998. var j;
  27999. var r;
  28000. var ringIdx = 1;
  28001. var s = 1; // surface index
  28002. var cs = 0;
  28003. var v = 0;
  28004. for (i = 0; i <= subdivisions; i++) {
  28005. h = i / subdivisions;
  28006. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28007. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28008. for (r = 0; r < ringIdx; r++) {
  28009. if (hasRings) {
  28010. s += r;
  28011. }
  28012. if (enclose) {
  28013. s += 2 * r;
  28014. }
  28015. for (j = 0; j <= tessellation; j++) {
  28016. angle = j * angle_step;
  28017. // position
  28018. ringVertex.x = Math.cos(-angle) * radius;
  28019. ringVertex.y = -height / 2 + h * height;
  28020. ringVertex.z = Math.sin(-angle) * radius;
  28021. // normal
  28022. if (diameterTop === 0 && i === subdivisions) {
  28023. // if no top cap, reuse former normals
  28024. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28025. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28026. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28027. }
  28028. else {
  28029. ringNormal.x = ringVertex.x;
  28030. ringNormal.z = ringVertex.z;
  28031. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28032. ringNormal.normalize();
  28033. }
  28034. // keep first ring vertex values for enclose
  28035. if (j === 0) {
  28036. ringFirstVertex.copyFrom(ringVertex);
  28037. ringFirstNormal.copyFrom(ringNormal);
  28038. }
  28039. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28040. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28041. if (hasRings) {
  28042. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28043. }
  28044. else {
  28045. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28046. }
  28047. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28048. if (faceColors) {
  28049. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28050. }
  28051. }
  28052. // if enclose, add four vertices and their dedicated normals
  28053. if (arc !== 1 && enclose) {
  28054. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28055. positions.push(0, ringVertex.y, 0);
  28056. positions.push(0, ringVertex.y, 0);
  28057. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28058. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28059. quadNormal.normalize();
  28060. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28061. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28062. quadNormal.normalize();
  28063. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28064. if (hasRings) {
  28065. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28066. }
  28067. else {
  28068. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28069. }
  28070. uvs.push(faceUV[s + 1].x, v);
  28071. uvs.push(faceUV[s + 1].z, v);
  28072. if (hasRings) {
  28073. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28074. }
  28075. else {
  28076. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28077. }
  28078. uvs.push(faceUV[s + 2].x, v);
  28079. uvs.push(faceUV[s + 2].z, v);
  28080. if (faceColors) {
  28081. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28082. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28083. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28084. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28085. }
  28086. }
  28087. if (cs !== s) {
  28088. cs = s;
  28089. }
  28090. }
  28091. }
  28092. // indices
  28093. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28094. var s;
  28095. i = 0;
  28096. for (s = 0; s < subdivisions; s++) {
  28097. for (j = 0; j < tessellation; j++) {
  28098. var i0 = i * (e + 1) + j;
  28099. var i1 = (i + 1) * (e + 1) + j;
  28100. var i2 = i * (e + 1) + (j + 1);
  28101. var i3 = (i + 1) * (e + 1) + (j + 1);
  28102. indices.push(i0, i1, i2);
  28103. indices.push(i3, i2, i1);
  28104. }
  28105. if (arc !== 1 && enclose) {
  28106. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28107. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28108. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28109. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28110. }
  28111. i = (hasRings) ? (i + 2) : (i + 1);
  28112. }
  28113. // Caps
  28114. var createCylinderCap = function (isTop) {
  28115. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28116. if (radius === 0) {
  28117. return;
  28118. }
  28119. // Cap positions, normals & uvs
  28120. var angle;
  28121. var circleVector;
  28122. var i;
  28123. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28124. var c;
  28125. if (faceColors) {
  28126. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28127. }
  28128. // cap center
  28129. var vbase = positions.length / 3;
  28130. var offset = isTop ? height / 2 : -height / 2;
  28131. var center = new BABYLON.Vector3(0, offset, 0);
  28132. positions.push(center.x, center.y, center.z);
  28133. normals.push(0, isTop ? 1 : -1, 0);
  28134. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28135. if (faceColors) {
  28136. colors.push(c.r, c.g, c.b, c.a);
  28137. }
  28138. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28139. for (i = 0; i <= tessellation; i++) {
  28140. angle = Math.PI * 2 * i * arc / tessellation;
  28141. var cos = Math.cos(-angle);
  28142. var sin = Math.sin(-angle);
  28143. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28144. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28145. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28146. normals.push(0, isTop ? 1 : -1, 0);
  28147. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28148. if (faceColors) {
  28149. colors.push(c.r, c.g, c.b, c.a);
  28150. }
  28151. }
  28152. // Cap indices
  28153. for (i = 0; i < tessellation; i++) {
  28154. if (!isTop) {
  28155. indices.push(vbase);
  28156. indices.push(vbase + (i + 1));
  28157. indices.push(vbase + (i + 2));
  28158. }
  28159. else {
  28160. indices.push(vbase);
  28161. indices.push(vbase + (i + 2));
  28162. indices.push(vbase + (i + 1));
  28163. }
  28164. }
  28165. };
  28166. // add caps to geometry
  28167. createCylinderCap(false);
  28168. createCylinderCap(true);
  28169. // Sides
  28170. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28171. var vertexData = new VertexData();
  28172. vertexData.indices = indices;
  28173. vertexData.positions = positions;
  28174. vertexData.normals = normals;
  28175. vertexData.uvs = uvs;
  28176. if (faceColors) {
  28177. vertexData.colors = colors;
  28178. }
  28179. return vertexData;
  28180. };
  28181. VertexData.CreateTorus = function (options) {
  28182. var indices = [];
  28183. var positions = [];
  28184. var normals = [];
  28185. var uvs = [];
  28186. var diameter = options.diameter || 1;
  28187. var thickness = options.thickness || 0.5;
  28188. var tessellation = options.tessellation || 16;
  28189. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28190. var stride = tessellation + 1;
  28191. for (var i = 0; i <= tessellation; i++) {
  28192. var u = i / tessellation;
  28193. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28194. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28195. for (var j = 0; j <= tessellation; j++) {
  28196. var v = 1 - j / tessellation;
  28197. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28198. var dx = Math.cos(innerAngle);
  28199. var dy = Math.sin(innerAngle);
  28200. // Create a vertex.
  28201. var normal = new BABYLON.Vector3(dx, dy, 0);
  28202. var position = normal.scale(thickness / 2);
  28203. var textureCoordinate = new BABYLON.Vector2(u, v);
  28204. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28205. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28206. positions.push(position.x, position.y, position.z);
  28207. normals.push(normal.x, normal.y, normal.z);
  28208. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28209. // And create indices for two triangles.
  28210. var nextI = (i + 1) % stride;
  28211. var nextJ = (j + 1) % stride;
  28212. indices.push(i * stride + j);
  28213. indices.push(i * stride + nextJ);
  28214. indices.push(nextI * stride + j);
  28215. indices.push(i * stride + nextJ);
  28216. indices.push(nextI * stride + nextJ);
  28217. indices.push(nextI * stride + j);
  28218. }
  28219. }
  28220. // Sides
  28221. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28222. // Result
  28223. var vertexData = new VertexData();
  28224. vertexData.indices = indices;
  28225. vertexData.positions = positions;
  28226. vertexData.normals = normals;
  28227. vertexData.uvs = uvs;
  28228. return vertexData;
  28229. };
  28230. VertexData.CreateLineSystem = function (options) {
  28231. var indices = [];
  28232. var positions = [];
  28233. var lines = options.lines;
  28234. var idx = 0;
  28235. for (var l = 0; l < lines.length; l++) {
  28236. var points = lines[l];
  28237. for (var index = 0; index < points.length; index++) {
  28238. positions.push(points[index].x, points[index].y, points[index].z);
  28239. if (index > 0) {
  28240. indices.push(idx - 1);
  28241. indices.push(idx);
  28242. }
  28243. idx++;
  28244. }
  28245. }
  28246. var vertexData = new VertexData();
  28247. vertexData.indices = indices;
  28248. vertexData.positions = positions;
  28249. return vertexData;
  28250. };
  28251. VertexData.CreateDashedLines = function (options) {
  28252. var dashSize = options.dashSize || 3;
  28253. var gapSize = options.gapSize || 1;
  28254. var dashNb = options.dashNb || 200;
  28255. var points = options.points;
  28256. var positions = new Array();
  28257. var indices = new Array();
  28258. var curvect = BABYLON.Vector3.Zero();
  28259. var lg = 0;
  28260. var nb = 0;
  28261. var shft = 0;
  28262. var dashshft = 0;
  28263. var curshft = 0;
  28264. var idx = 0;
  28265. var i = 0;
  28266. for (i = 0; i < points.length - 1; i++) {
  28267. points[i + 1].subtractToRef(points[i], curvect);
  28268. lg += curvect.length();
  28269. }
  28270. shft = lg / dashNb;
  28271. dashshft = dashSize * shft / (dashSize + gapSize);
  28272. for (i = 0; i < points.length - 1; i++) {
  28273. points[i + 1].subtractToRef(points[i], curvect);
  28274. nb = Math.floor(curvect.length() / shft);
  28275. curvect.normalize();
  28276. for (var j = 0; j < nb; j++) {
  28277. curshft = shft * j;
  28278. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28279. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28280. indices.push(idx, idx + 1);
  28281. idx += 2;
  28282. }
  28283. }
  28284. // Result
  28285. var vertexData = new VertexData();
  28286. vertexData.positions = positions;
  28287. vertexData.indices = indices;
  28288. return vertexData;
  28289. };
  28290. VertexData.CreateGround = function (options) {
  28291. var indices = [];
  28292. var positions = [];
  28293. var normals = [];
  28294. var uvs = [];
  28295. var row, col;
  28296. var width = options.width || 1;
  28297. var height = options.height || 1;
  28298. var subdivisions = options.subdivisions || 1;
  28299. for (row = 0; row <= subdivisions; row++) {
  28300. for (col = 0; col <= subdivisions; col++) {
  28301. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28302. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28303. positions.push(position.x, position.y, position.z);
  28304. normals.push(normal.x, normal.y, normal.z);
  28305. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28306. }
  28307. }
  28308. for (row = 0; row < subdivisions; row++) {
  28309. for (col = 0; col < subdivisions; col++) {
  28310. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28311. indices.push(col + 1 + row * (subdivisions + 1));
  28312. indices.push(col + row * (subdivisions + 1));
  28313. indices.push(col + (row + 1) * (subdivisions + 1));
  28314. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28315. indices.push(col + row * (subdivisions + 1));
  28316. }
  28317. }
  28318. // Result
  28319. var vertexData = new VertexData();
  28320. vertexData.indices = indices;
  28321. vertexData.positions = positions;
  28322. vertexData.normals = normals;
  28323. vertexData.uvs = uvs;
  28324. return vertexData;
  28325. };
  28326. VertexData.CreateTiledGround = function (options) {
  28327. var xmin = options.xmin;
  28328. var zmin = options.zmin;
  28329. var xmax = options.xmax;
  28330. var zmax = options.zmax;
  28331. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28332. var precision = options.precision || { w: 1, h: 1 };
  28333. var indices = [];
  28334. var positions = [];
  28335. var normals = [];
  28336. var uvs = [];
  28337. var row, col, tileRow, tileCol;
  28338. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28339. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28340. precision.w = (precision.w < 1) ? 1 : precision.w;
  28341. precision.h = (precision.h < 1) ? 1 : precision.h;
  28342. var tileSize = {
  28343. 'w': (xmax - xmin) / subdivisions.w,
  28344. 'h': (zmax - zmin) / subdivisions.h
  28345. };
  28346. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28347. // Indices
  28348. var base = positions.length / 3;
  28349. var rowLength = precision.w + 1;
  28350. for (row = 0; row < precision.h; row++) {
  28351. for (col = 0; col < precision.w; col++) {
  28352. var square = [
  28353. base + col + row * rowLength,
  28354. base + (col + 1) + row * rowLength,
  28355. base + (col + 1) + (row + 1) * rowLength,
  28356. base + col + (row + 1) * rowLength
  28357. ];
  28358. indices.push(square[1]);
  28359. indices.push(square[2]);
  28360. indices.push(square[3]);
  28361. indices.push(square[0]);
  28362. indices.push(square[1]);
  28363. indices.push(square[3]);
  28364. }
  28365. }
  28366. // Position, normals and uvs
  28367. var position = BABYLON.Vector3.Zero();
  28368. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28369. for (row = 0; row <= precision.h; row++) {
  28370. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28371. for (col = 0; col <= precision.w; col++) {
  28372. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28373. position.y = 0;
  28374. positions.push(position.x, position.y, position.z);
  28375. normals.push(normal.x, normal.y, normal.z);
  28376. uvs.push(col / precision.w, row / precision.h);
  28377. }
  28378. }
  28379. }
  28380. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28381. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28382. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28383. }
  28384. }
  28385. // Result
  28386. var vertexData = new VertexData();
  28387. vertexData.indices = indices;
  28388. vertexData.positions = positions;
  28389. vertexData.normals = normals;
  28390. vertexData.uvs = uvs;
  28391. return vertexData;
  28392. };
  28393. VertexData.CreateGroundFromHeightMap = function (options) {
  28394. var indices = [];
  28395. var positions = [];
  28396. var normals = [];
  28397. var uvs = [];
  28398. var row, col;
  28399. // Vertices
  28400. for (row = 0; row <= options.subdivisions; row++) {
  28401. for (col = 0; col <= options.subdivisions; col++) {
  28402. 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));
  28403. // Compute height
  28404. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28405. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28406. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28407. var r = options.buffer[pos] / 255.0;
  28408. var g = options.buffer[pos + 1] / 255.0;
  28409. var b = options.buffer[pos + 2] / 255.0;
  28410. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28411. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28412. // Add vertex
  28413. positions.push(position.x, position.y, position.z);
  28414. normals.push(0, 0, 0);
  28415. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28416. }
  28417. }
  28418. // Indices
  28419. for (row = 0; row < options.subdivisions; row++) {
  28420. for (col = 0; col < options.subdivisions; col++) {
  28421. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28422. indices.push(col + 1 + row * (options.subdivisions + 1));
  28423. indices.push(col + row * (options.subdivisions + 1));
  28424. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28425. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28426. indices.push(col + row * (options.subdivisions + 1));
  28427. }
  28428. }
  28429. // Normals
  28430. VertexData.ComputeNormals(positions, indices, normals);
  28431. // Result
  28432. var vertexData = new VertexData();
  28433. vertexData.indices = indices;
  28434. vertexData.positions = positions;
  28435. vertexData.normals = normals;
  28436. vertexData.uvs = uvs;
  28437. return vertexData;
  28438. };
  28439. VertexData.CreatePlane = function (options) {
  28440. var indices = [];
  28441. var positions = [];
  28442. var normals = [];
  28443. var uvs = [];
  28444. var width = options.width || options.size || 1;
  28445. var height = options.height || options.size || 1;
  28446. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28447. // Vertices
  28448. var halfWidth = width / 2.0;
  28449. var halfHeight = height / 2.0;
  28450. positions.push(-halfWidth, -halfHeight, 0);
  28451. normals.push(0, 0, -1.0);
  28452. uvs.push(0.0, 0.0);
  28453. positions.push(halfWidth, -halfHeight, 0);
  28454. normals.push(0, 0, -1.0);
  28455. uvs.push(1.0, 0.0);
  28456. positions.push(halfWidth, halfHeight, 0);
  28457. normals.push(0, 0, -1.0);
  28458. uvs.push(1.0, 1.0);
  28459. positions.push(-halfWidth, halfHeight, 0);
  28460. normals.push(0, 0, -1.0);
  28461. uvs.push(0.0, 1.0);
  28462. // Indices
  28463. indices.push(0);
  28464. indices.push(1);
  28465. indices.push(2);
  28466. indices.push(0);
  28467. indices.push(2);
  28468. indices.push(3);
  28469. // Sides
  28470. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28471. // Result
  28472. var vertexData = new VertexData();
  28473. vertexData.indices = indices;
  28474. vertexData.positions = positions;
  28475. vertexData.normals = normals;
  28476. vertexData.uvs = uvs;
  28477. return vertexData;
  28478. };
  28479. VertexData.CreateDisc = function (options) {
  28480. var positions = [];
  28481. var indices = [];
  28482. var normals = [];
  28483. var uvs = [];
  28484. var radius = options.radius || 0.5;
  28485. var tessellation = options.tessellation || 64;
  28486. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28487. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28488. // positions and uvs
  28489. positions.push(0, 0, 0); // disc center first
  28490. uvs.push(0.5, 0.5);
  28491. var theta = Math.PI * 2 * arc;
  28492. var step = theta / tessellation;
  28493. for (var a = 0; a < theta; a += step) {
  28494. var x = Math.cos(a);
  28495. var y = Math.sin(a);
  28496. var u = (x + 1) / 2;
  28497. var v = (1 - y) / 2;
  28498. positions.push(radius * x, radius * y, 0);
  28499. uvs.push(u, v);
  28500. }
  28501. if (arc === 1) {
  28502. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28503. uvs.push(uvs[2], uvs[3]);
  28504. }
  28505. //indices
  28506. var vertexNb = positions.length / 3;
  28507. for (var i = 1; i < vertexNb - 1; i++) {
  28508. indices.push(i + 1, 0, i);
  28509. }
  28510. // result
  28511. VertexData.ComputeNormals(positions, indices, normals);
  28512. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28513. var vertexData = new VertexData();
  28514. vertexData.indices = indices;
  28515. vertexData.positions = positions;
  28516. vertexData.normals = normals;
  28517. vertexData.uvs = uvs;
  28518. return vertexData;
  28519. };
  28520. VertexData.CreateIcoSphere = function (options) {
  28521. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28522. var radius = options.radius || 1;
  28523. var flat = (options.flat === undefined) ? true : options.flat;
  28524. var subdivisions = options.subdivisions || 4;
  28525. var radiusX = options.radiusX || radius;
  28526. var radiusY = options.radiusY || radius;
  28527. var radiusZ = options.radiusZ || radius;
  28528. var t = (1 + Math.sqrt(5)) / 2;
  28529. // 12 vertex x,y,z
  28530. var ico_vertices = [
  28531. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28532. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28533. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28534. ];
  28535. // index of 3 vertex makes a face of icopshere
  28536. var ico_indices = [
  28537. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28538. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28539. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28540. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28541. ];
  28542. // vertex for uv have aliased position, not for UV
  28543. var vertices_unalias_id = [
  28544. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28545. // vertex alias
  28546. 0,
  28547. 2,
  28548. 3,
  28549. 3,
  28550. 3,
  28551. 4,
  28552. 7,
  28553. 8,
  28554. 9,
  28555. 9,
  28556. 10,
  28557. 11 // 23: B + 12
  28558. ];
  28559. // uv as integer step (not pixels !)
  28560. var ico_vertexuv = [
  28561. 5, 1, 3, 1, 6, 4, 0, 0,
  28562. 5, 3, 4, 2, 2, 2, 4, 0,
  28563. 2, 0, 1, 1, 6, 0, 6, 2,
  28564. // vertex alias (for same vertex on different faces)
  28565. 0, 4,
  28566. 3, 3,
  28567. 4, 4,
  28568. 3, 1,
  28569. 4, 2,
  28570. 4, 4,
  28571. 0, 2,
  28572. 1, 1,
  28573. 2, 2,
  28574. 3, 3,
  28575. 1, 3,
  28576. 2, 4 // 23: B + 12
  28577. ];
  28578. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28579. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28580. // First island of uv mapping
  28581. // v = 4h 3+ 2
  28582. // v = 3h 9+ 4
  28583. // v = 2h 9+ 5 B
  28584. // v = 1h 9 1 0
  28585. // v = 0h 3 8 7 A
  28586. // u = 0 1 2 3 4 5 6 *a
  28587. // Second island of uv mapping
  28588. // v = 4h 0+ B+ 4+
  28589. // v = 3h A+ 2+
  28590. // v = 2h 7+ 6 3+
  28591. // v = 1h 8+ 3+
  28592. // v = 0h
  28593. // u = 0 1 2 3 4 5 6 *a
  28594. // Face layout on texture UV mapping
  28595. // ============
  28596. // \ 4 /\ 16 / ======
  28597. // \ / \ / /\ 11 /
  28598. // \/ 7 \/ / \ /
  28599. // ======= / 10 \/
  28600. // /\ 17 /\ =======
  28601. // / \ / \ \ 15 /\
  28602. // / 8 \/ 12 \ \ / \
  28603. // ============ \/ 6 \
  28604. // \ 18 /\ ============
  28605. // \ / \ \ 5 /\ 0 /
  28606. // \/ 13 \ \ / \ /
  28607. // ======= \/ 1 \/
  28608. // =============
  28609. // /\ 19 /\ 2 /\
  28610. // / \ / \ / \
  28611. // / 14 \/ 9 \/ 3 \
  28612. // ===================
  28613. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28614. var ustep = 138 / 1024;
  28615. var vstep = 239 / 1024;
  28616. var uoffset = 60 / 1024;
  28617. var voffset = 26 / 1024;
  28618. // Second island should have margin, not to touch the first island
  28619. // avoid any borderline artefact in pixel rounding
  28620. var island_u_offset = -40 / 1024;
  28621. var island_v_offset = +20 / 1024;
  28622. // face is either island 0 or 1 :
  28623. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28624. var island = [
  28625. 0, 0, 0, 0, 1,
  28626. 0, 0, 1, 1, 0,
  28627. 0, 0, 1, 1, 0,
  28628. 0, 1, 1, 1, 0 // 15 - 19
  28629. ];
  28630. var indices = [];
  28631. var positions = [];
  28632. var normals = [];
  28633. var uvs = [];
  28634. var current_indice = 0;
  28635. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28636. var face_vertex_pos = new Array(3);
  28637. var face_vertex_uv = new Array(3);
  28638. var v012;
  28639. for (v012 = 0; v012 < 3; v012++) {
  28640. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28641. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28642. }
  28643. // create all with normals
  28644. for (var face = 0; face < 20; face++) {
  28645. // 3 vertex per face
  28646. for (v012 = 0; v012 < 3; v012++) {
  28647. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28648. var v_id = ico_indices[3 * face + v012];
  28649. // vertex have 3D position (x,y,z)
  28650. 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]);
  28651. // Normalize to get normal, then scale to radius
  28652. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28653. // uv Coordinates from vertex ID
  28654. 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);
  28655. }
  28656. // Subdivide the face (interpolate pos, norm, uv)
  28657. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28658. // - norm is linear interpolation of vertex corner normal
  28659. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28660. // - uv is linear interpolation
  28661. //
  28662. // Topology is as below for sub-divide by 2
  28663. // vertex shown as v0,v1,v2
  28664. // interp index is i1 to progress in range [v0,v1[
  28665. // interp index is i2 to progress in range [v0,v2[
  28666. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28667. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28668. //
  28669. //
  28670. // i2 v2
  28671. // ^ ^
  28672. // / / \
  28673. // / / \
  28674. // / / \
  28675. // / / (0,1) \
  28676. // / #---------\
  28677. // / / \ (0,0)'/ \
  28678. // / / \ / \
  28679. // / / \ / \
  28680. // / / (0,0) \ / (1,0) \
  28681. // / #---------#---------\
  28682. // v0 v1
  28683. //
  28684. // --------------------> i1
  28685. //
  28686. // interp of (i1,i2):
  28687. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28688. // along i1 : lerp(x0,x1, i1/(S-i2))
  28689. //
  28690. // centroid of triangle is needed to get help normal computation
  28691. // (c1,c2) are used for centroid location
  28692. var interp_vertex = function (i1, i2, c1, c2) {
  28693. // vertex is interpolated from
  28694. // - face_vertex_pos[0..2]
  28695. // - face_vertex_uv[0..2]
  28696. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28697. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28698. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28699. pos_interp.normalize();
  28700. var vertex_normal;
  28701. if (flat) {
  28702. // in flat mode, recalculate normal as face centroid normal
  28703. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28704. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28705. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28706. }
  28707. else {
  28708. // in smooth mode, recalculate normal from each single vertex position
  28709. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28710. }
  28711. // Vertex normal need correction due to X,Y,Z radius scaling
  28712. vertex_normal.x /= radiusX;
  28713. vertex_normal.y /= radiusY;
  28714. vertex_normal.z /= radiusZ;
  28715. vertex_normal.normalize();
  28716. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28717. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28718. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28719. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28720. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28721. uvs.push(uv_interp.x, uv_interp.y);
  28722. // push each vertex has member of a face
  28723. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28724. indices.push(current_indice);
  28725. current_indice++;
  28726. };
  28727. for (var i2 = 0; i2 < subdivisions; i2++) {
  28728. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28729. // face : (i1,i2) for /\ :
  28730. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28731. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28732. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28733. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28734. if (i1 + i2 + 1 < subdivisions) {
  28735. // face : (i1,i2)' for \/ :
  28736. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28737. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28738. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28739. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28740. }
  28741. }
  28742. }
  28743. }
  28744. // Sides
  28745. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28746. // Result
  28747. var vertexData = new VertexData();
  28748. vertexData.indices = indices;
  28749. vertexData.positions = positions;
  28750. vertexData.normals = normals;
  28751. vertexData.uvs = uvs;
  28752. return vertexData;
  28753. };
  28754. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28755. VertexData.CreatePolyhedron = function (options) {
  28756. // provided polyhedron types :
  28757. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28758. // 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)
  28759. var polyhedra = [];
  28760. 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]] };
  28761. 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]] };
  28762. polyhedra[2] = {
  28763. 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]],
  28764. 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]]
  28765. };
  28766. polyhedra[3] = {
  28767. 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]],
  28768. 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]]
  28769. };
  28770. polyhedra[4] = {
  28771. 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]],
  28772. 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]]
  28773. };
  28774. 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]] };
  28775. 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]] };
  28776. 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]] };
  28777. 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]] };
  28778. 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]] };
  28779. 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]] };
  28780. 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]] };
  28781. 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]] };
  28782. 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]] };
  28783. polyhedra[14] = {
  28784. 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]],
  28785. 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]]
  28786. };
  28787. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28788. var size = options.size;
  28789. var sizeX = options.sizeX || size || 1;
  28790. var sizeY = options.sizeY || size || 1;
  28791. var sizeZ = options.sizeZ || size || 1;
  28792. var data = options.custom || polyhedra[type];
  28793. var nbfaces = data.face.length;
  28794. var faceUV = options.faceUV || new Array(nbfaces);
  28795. var faceColors = options.faceColors;
  28796. var flat = (options.flat === undefined) ? true : options.flat;
  28797. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28798. var positions = [];
  28799. var indices = [];
  28800. var normals = [];
  28801. var uvs = [];
  28802. var colors = [];
  28803. var index = 0;
  28804. var faceIdx = 0; // face cursor in the array "indexes"
  28805. var indexes = [];
  28806. var i = 0;
  28807. var f = 0;
  28808. var u, v, ang, x, y, tmp;
  28809. // default face colors and UV if undefined
  28810. if (flat) {
  28811. for (f = 0; f < nbfaces; f++) {
  28812. if (faceColors && faceColors[f] === undefined) {
  28813. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28814. }
  28815. if (faceUV && faceUV[f] === undefined) {
  28816. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28817. }
  28818. }
  28819. }
  28820. if (!flat) {
  28821. for (i = 0; i < data.vertex.length; i++) {
  28822. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28823. uvs.push(0, 0);
  28824. }
  28825. for (f = 0; f < nbfaces; f++) {
  28826. for (i = 0; i < data.face[f].length - 2; i++) {
  28827. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28828. }
  28829. }
  28830. }
  28831. else {
  28832. for (f = 0; f < nbfaces; f++) {
  28833. var fl = data.face[f].length; // number of vertices of the current face
  28834. ang = 2 * Math.PI / fl;
  28835. x = 0.5 * Math.tan(ang / 2);
  28836. y = 0.5;
  28837. // positions, uvs, colors
  28838. for (i = 0; i < fl; i++) {
  28839. // positions
  28840. 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);
  28841. indexes.push(index);
  28842. index++;
  28843. // uvs
  28844. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28845. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28846. uvs.push(u, v);
  28847. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28848. y = x * Math.sin(ang) + y * Math.cos(ang);
  28849. x = tmp;
  28850. // colors
  28851. if (faceColors) {
  28852. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28853. }
  28854. }
  28855. // indices from indexes
  28856. for (i = 0; i < fl - 2; i++) {
  28857. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28858. }
  28859. faceIdx += fl;
  28860. }
  28861. }
  28862. VertexData.ComputeNormals(positions, indices, normals);
  28863. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28864. var vertexData = new VertexData();
  28865. vertexData.positions = positions;
  28866. vertexData.indices = indices;
  28867. vertexData.normals = normals;
  28868. vertexData.uvs = uvs;
  28869. if (faceColors && flat) {
  28870. vertexData.colors = colors;
  28871. }
  28872. return vertexData;
  28873. };
  28874. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28875. VertexData.CreateTorusKnot = function (options) {
  28876. var indices = [];
  28877. var positions = [];
  28878. var normals = [];
  28879. var uvs = [];
  28880. var radius = options.radius || 2;
  28881. var tube = options.tube || 0.5;
  28882. var radialSegments = options.radialSegments || 32;
  28883. var tubularSegments = options.tubularSegments || 32;
  28884. var p = options.p || 2;
  28885. var q = options.q || 3;
  28886. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28887. // Helper
  28888. var getPos = function (angle) {
  28889. var cu = Math.cos(angle);
  28890. var su = Math.sin(angle);
  28891. var quOverP = q / p * angle;
  28892. var cs = Math.cos(quOverP);
  28893. var tx = radius * (2 + cs) * 0.5 * cu;
  28894. var ty = radius * (2 + cs) * su * 0.5;
  28895. var tz = radius * Math.sin(quOverP) * 0.5;
  28896. return new BABYLON.Vector3(tx, ty, tz);
  28897. };
  28898. // Vertices
  28899. var i;
  28900. var j;
  28901. for (i = 0; i <= radialSegments; i++) {
  28902. var modI = i % radialSegments;
  28903. var u = modI / radialSegments * 2 * p * Math.PI;
  28904. var p1 = getPos(u);
  28905. var p2 = getPos(u + 0.01);
  28906. var tang = p2.subtract(p1);
  28907. var n = p2.add(p1);
  28908. var bitan = BABYLON.Vector3.Cross(tang, n);
  28909. n = BABYLON.Vector3.Cross(bitan, tang);
  28910. bitan.normalize();
  28911. n.normalize();
  28912. for (j = 0; j < tubularSegments; j++) {
  28913. var modJ = j % tubularSegments;
  28914. var v = modJ / tubularSegments * 2 * Math.PI;
  28915. var cx = -tube * Math.cos(v);
  28916. var cy = tube * Math.sin(v);
  28917. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28918. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28919. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28920. uvs.push(i / radialSegments);
  28921. uvs.push(j / tubularSegments);
  28922. }
  28923. }
  28924. for (i = 0; i < radialSegments; i++) {
  28925. for (j = 0; j < tubularSegments; j++) {
  28926. var jNext = (j + 1) % tubularSegments;
  28927. var a = i * tubularSegments + j;
  28928. var b = (i + 1) * tubularSegments + j;
  28929. var c = (i + 1) * tubularSegments + jNext;
  28930. var d = i * tubularSegments + jNext;
  28931. indices.push(d);
  28932. indices.push(b);
  28933. indices.push(a);
  28934. indices.push(d);
  28935. indices.push(c);
  28936. indices.push(b);
  28937. }
  28938. }
  28939. // Normals
  28940. VertexData.ComputeNormals(positions, indices, normals);
  28941. // Sides
  28942. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28943. // Result
  28944. var vertexData = new VertexData();
  28945. vertexData.indices = indices;
  28946. vertexData.positions = positions;
  28947. vertexData.normals = normals;
  28948. vertexData.uvs = uvs;
  28949. return vertexData;
  28950. };
  28951. // Tools
  28952. /**
  28953. * @param {any} - positions (number[] or Float32Array)
  28954. * @param {any} - indices (number[] or Uint16Array)
  28955. * @param {any} - normals (number[] or Float32Array)
  28956. */
  28957. VertexData.ComputeNormals = function (positions, indices, normals) {
  28958. var index = 0;
  28959. var p1p2x = 0.0;
  28960. var p1p2y = 0.0;
  28961. var p1p2z = 0.0;
  28962. var p3p2x = 0.0;
  28963. var p3p2y = 0.0;
  28964. var p3p2z = 0.0;
  28965. var faceNormalx = 0.0;
  28966. var faceNormaly = 0.0;
  28967. var faceNormalz = 0.0;
  28968. var length = 0.0;
  28969. var i1 = 0;
  28970. var i2 = 0;
  28971. var i3 = 0;
  28972. for (index = 0; index < positions.length; index++) {
  28973. normals[index] = 0.0;
  28974. }
  28975. // indice triplet = 1 face
  28976. var nbFaces = indices.length / 3;
  28977. for (index = 0; index < nbFaces; index++) {
  28978. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  28979. i2 = indices[index * 3 + 1];
  28980. i3 = indices[index * 3 + 2];
  28981. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  28982. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  28983. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  28984. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  28985. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  28986. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  28987. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  28988. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  28989. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  28990. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28991. length = (length === 0) ? 1.0 : length;
  28992. faceNormalx /= length; // normalize this normal
  28993. faceNormaly /= length;
  28994. faceNormalz /= length;
  28995. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  28996. normals[i1 * 3 + 1] += faceNormaly;
  28997. normals[i1 * 3 + 2] += faceNormalz;
  28998. normals[i2 * 3] += faceNormalx;
  28999. normals[i2 * 3 + 1] += faceNormaly;
  29000. normals[i2 * 3 + 2] += faceNormalz;
  29001. normals[i3 * 3] += faceNormalx;
  29002. normals[i3 * 3 + 1] += faceNormaly;
  29003. normals[i3 * 3 + 2] += faceNormalz;
  29004. }
  29005. // last normalization of each normal
  29006. for (index = 0; index < normals.length / 3; index++) {
  29007. faceNormalx = normals[index * 3];
  29008. faceNormaly = normals[index * 3 + 1];
  29009. faceNormalz = normals[index * 3 + 2];
  29010. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29011. length = (length === 0) ? 1.0 : length;
  29012. faceNormalx /= length;
  29013. faceNormaly /= length;
  29014. faceNormalz /= length;
  29015. normals[index * 3] = faceNormalx;
  29016. normals[index * 3 + 1] = faceNormaly;
  29017. normals[index * 3 + 2] = faceNormalz;
  29018. }
  29019. };
  29020. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29021. var li = indices.length;
  29022. var ln = normals.length;
  29023. var i;
  29024. var n;
  29025. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29026. switch (sideOrientation) {
  29027. case BABYLON.Mesh.FRONTSIDE:
  29028. // nothing changed
  29029. break;
  29030. case BABYLON.Mesh.BACKSIDE:
  29031. var tmp;
  29032. // indices
  29033. for (i = 0; i < li; i += 3) {
  29034. tmp = indices[i];
  29035. indices[i] = indices[i + 2];
  29036. indices[i + 2] = tmp;
  29037. }
  29038. // normals
  29039. for (n = 0; n < ln; n++) {
  29040. normals[n] = -normals[n];
  29041. }
  29042. break;
  29043. case BABYLON.Mesh.DOUBLESIDE:
  29044. // positions
  29045. var lp = positions.length;
  29046. var l = lp / 3;
  29047. for (var p = 0; p < lp; p++) {
  29048. positions[lp + p] = positions[p];
  29049. }
  29050. // indices
  29051. for (i = 0; i < li; i += 3) {
  29052. indices[i + li] = indices[i + 2] + l;
  29053. indices[i + 1 + li] = indices[i + 1] + l;
  29054. indices[i + 2 + li] = indices[i] + l;
  29055. }
  29056. // normals
  29057. for (n = 0; n < ln; n++) {
  29058. normals[ln + n] = -normals[n];
  29059. }
  29060. // uvs
  29061. var lu = uvs.length;
  29062. for (var u = 0; u < lu; u++) {
  29063. uvs[u + lu] = uvs[u];
  29064. }
  29065. break;
  29066. }
  29067. };
  29068. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29069. var vertexData = new VertexData();
  29070. // positions
  29071. var positions = parsedVertexData.positions;
  29072. if (positions) {
  29073. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29074. }
  29075. // normals
  29076. var normals = parsedVertexData.normals;
  29077. if (normals) {
  29078. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29079. }
  29080. // uvs
  29081. var uvs = parsedVertexData.uvs;
  29082. if (uvs) {
  29083. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29084. }
  29085. // uv2s
  29086. var uv2s = parsedVertexData.uv2s;
  29087. if (uv2s) {
  29088. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29089. }
  29090. // uv3s
  29091. var uv3s = parsedVertexData.uv3s;
  29092. if (uv3s) {
  29093. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29094. }
  29095. // uv4s
  29096. var uv4s = parsedVertexData.uv4s;
  29097. if (uv4s) {
  29098. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29099. }
  29100. // uv5s
  29101. var uv5s = parsedVertexData.uv5s;
  29102. if (uv5s) {
  29103. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29104. }
  29105. // uv6s
  29106. var uv6s = parsedVertexData.uv6s;
  29107. if (uv6s) {
  29108. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29109. }
  29110. // colors
  29111. var colors = parsedVertexData.colors;
  29112. if (colors) {
  29113. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29114. }
  29115. // matricesIndices
  29116. var matricesIndices = parsedVertexData.matricesIndices;
  29117. if (matricesIndices) {
  29118. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29119. }
  29120. // matricesWeights
  29121. var matricesWeights = parsedVertexData.matricesWeights;
  29122. if (matricesWeights) {
  29123. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29124. }
  29125. // indices
  29126. var indices = parsedVertexData.indices;
  29127. if (indices) {
  29128. vertexData.indices = indices;
  29129. }
  29130. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29131. };
  29132. return VertexData;
  29133. }());
  29134. BABYLON.VertexData = VertexData;
  29135. })(BABYLON || (BABYLON = {}));
  29136. var BABYLON;
  29137. (function (BABYLON) {
  29138. var Tags = (function () {
  29139. function Tags() {
  29140. }
  29141. Tags.EnableFor = function (obj) {
  29142. obj._tags = obj._tags || {};
  29143. obj.hasTags = function () {
  29144. return Tags.HasTags(obj);
  29145. };
  29146. obj.addTags = function (tagsString) {
  29147. return Tags.AddTagsTo(obj, tagsString);
  29148. };
  29149. obj.removeTags = function (tagsString) {
  29150. return Tags.RemoveTagsFrom(obj, tagsString);
  29151. };
  29152. obj.matchesTagsQuery = function (tagsQuery) {
  29153. return Tags.MatchesQuery(obj, tagsQuery);
  29154. };
  29155. };
  29156. Tags.DisableFor = function (obj) {
  29157. delete obj._tags;
  29158. delete obj.hasTags;
  29159. delete obj.addTags;
  29160. delete obj.removeTags;
  29161. delete obj.matchesTagsQuery;
  29162. };
  29163. Tags.HasTags = function (obj) {
  29164. if (!obj._tags) {
  29165. return false;
  29166. }
  29167. return !BABYLON.Tools.IsEmpty(obj._tags);
  29168. };
  29169. Tags.GetTags = function (obj, asString) {
  29170. if (asString === void 0) { asString = true; }
  29171. if (!obj._tags) {
  29172. return null;
  29173. }
  29174. if (asString) {
  29175. var tagsArray = [];
  29176. for (var tag in obj._tags) {
  29177. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29178. tagsArray.push(tag);
  29179. }
  29180. }
  29181. return tagsArray.join(" ");
  29182. }
  29183. else {
  29184. return obj._tags;
  29185. }
  29186. };
  29187. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29188. // a tag cannot start with '||', '&&', and '!'
  29189. // it cannot contain whitespaces
  29190. Tags.AddTagsTo = function (obj, tagsString) {
  29191. if (!tagsString) {
  29192. return;
  29193. }
  29194. if (typeof tagsString !== "string") {
  29195. return;
  29196. }
  29197. var tags = tagsString.split(" ");
  29198. for (var t in tags) {
  29199. Tags._AddTagTo(obj, tags[t]);
  29200. }
  29201. };
  29202. Tags._AddTagTo = function (obj, tag) {
  29203. tag = tag.trim();
  29204. if (tag === "" || tag === "true" || tag === "false") {
  29205. return;
  29206. }
  29207. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29208. return;
  29209. }
  29210. Tags.EnableFor(obj);
  29211. obj._tags[tag] = true;
  29212. };
  29213. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29214. if (!Tags.HasTags(obj)) {
  29215. return;
  29216. }
  29217. var tags = tagsString.split(" ");
  29218. for (var t in tags) {
  29219. Tags._RemoveTagFrom(obj, tags[t]);
  29220. }
  29221. };
  29222. Tags._RemoveTagFrom = function (obj, tag) {
  29223. delete obj._tags[tag];
  29224. };
  29225. Tags.MatchesQuery = function (obj, tagsQuery) {
  29226. if (tagsQuery === undefined) {
  29227. return true;
  29228. }
  29229. if (tagsQuery === "") {
  29230. return Tags.HasTags(obj);
  29231. }
  29232. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29233. };
  29234. return Tags;
  29235. }());
  29236. BABYLON.Tags = Tags;
  29237. })(BABYLON || (BABYLON = {}));
  29238. var BABYLON;
  29239. (function (BABYLON) {
  29240. var Internals;
  29241. (function (Internals) {
  29242. var AndOrNotEvaluator = (function () {
  29243. function AndOrNotEvaluator() {
  29244. }
  29245. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29246. if (!query.match(/\([^\(\)]*\)/g)) {
  29247. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29248. }
  29249. else {
  29250. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29251. // remove parenthesis
  29252. r = r.slice(1, r.length - 1);
  29253. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29254. });
  29255. }
  29256. if (query === "true") {
  29257. return true;
  29258. }
  29259. if (query === "false") {
  29260. return false;
  29261. }
  29262. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29263. };
  29264. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29265. evaluateCallback = evaluateCallback || (function (r) {
  29266. return r === "true" ? true : false;
  29267. });
  29268. var result;
  29269. var or = parenthesisContent.split("||");
  29270. for (var i in or) {
  29271. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29272. var and = ori.split("&&");
  29273. if (and.length > 1) {
  29274. for (var j = 0; j < and.length; ++j) {
  29275. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29276. if (andj !== "true" && andj !== "false") {
  29277. if (andj[0] === "!") {
  29278. result = !evaluateCallback(andj.substring(1));
  29279. }
  29280. else {
  29281. result = evaluateCallback(andj);
  29282. }
  29283. }
  29284. else {
  29285. result = andj === "true" ? true : false;
  29286. }
  29287. if (!result) {
  29288. ori = "false";
  29289. break;
  29290. }
  29291. }
  29292. }
  29293. if (result || ori === "true") {
  29294. result = true;
  29295. break;
  29296. }
  29297. // result equals false (or undefined)
  29298. if (ori !== "true" && ori !== "false") {
  29299. if (ori[0] === "!") {
  29300. result = !evaluateCallback(ori.substring(1));
  29301. }
  29302. else {
  29303. result = evaluateCallback(ori);
  29304. }
  29305. }
  29306. else {
  29307. result = ori === "true" ? true : false;
  29308. }
  29309. }
  29310. // the whole parenthesis scope is replaced by 'true' or 'false'
  29311. return result ? "true" : "false";
  29312. };
  29313. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29314. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29315. // remove whitespaces
  29316. r = r.replace(/[\s]/g, function () { return ""; });
  29317. return r.length % 2 ? "!" : "";
  29318. });
  29319. booleanString = booleanString.trim();
  29320. if (booleanString === "!true") {
  29321. booleanString = "false";
  29322. }
  29323. else if (booleanString === "!false") {
  29324. booleanString = "true";
  29325. }
  29326. return booleanString;
  29327. };
  29328. return AndOrNotEvaluator;
  29329. }());
  29330. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29331. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29332. })(BABYLON || (BABYLON = {}));
  29333. var BABYLON;
  29334. (function (BABYLON) {
  29335. var PostProcessRenderPass = (function () {
  29336. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29337. this._enabled = true;
  29338. this._refCount = 0;
  29339. this._name = name;
  29340. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29341. this.setRenderList(renderList);
  29342. this._renderTexture.onBeforeRender = beforeRender;
  29343. this._renderTexture.onAfterRender = afterRender;
  29344. this._scene = scene;
  29345. this._renderList = renderList;
  29346. }
  29347. // private
  29348. PostProcessRenderPass.prototype._incRefCount = function () {
  29349. if (this._refCount === 0) {
  29350. this._scene.customRenderTargets.push(this._renderTexture);
  29351. }
  29352. return ++this._refCount;
  29353. };
  29354. PostProcessRenderPass.prototype._decRefCount = function () {
  29355. this._refCount--;
  29356. if (this._refCount <= 0) {
  29357. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29358. }
  29359. return this._refCount;
  29360. };
  29361. PostProcessRenderPass.prototype._update = function () {
  29362. this.setRenderList(this._renderList);
  29363. };
  29364. // public
  29365. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29366. this._renderTexture.renderList = renderList;
  29367. };
  29368. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29369. return this._renderTexture;
  29370. };
  29371. return PostProcessRenderPass;
  29372. }());
  29373. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29374. })(BABYLON || (BABYLON = {}));
  29375. var BABYLON;
  29376. (function (BABYLON) {
  29377. var PostProcessRenderEffect = (function () {
  29378. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29379. this._engine = engine;
  29380. this._name = name;
  29381. this._singleInstance = singleInstance || true;
  29382. this._getPostProcess = getPostProcess;
  29383. this._cameras = [];
  29384. this._indicesForCamera = [];
  29385. this._postProcesses = {};
  29386. this._renderPasses = {};
  29387. this._renderEffectAsPasses = {};
  29388. }
  29389. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29390. get: function () {
  29391. for (var index in this._postProcesses) {
  29392. if (!this._postProcesses[index].isSupported) {
  29393. return false;
  29394. }
  29395. }
  29396. return true;
  29397. },
  29398. enumerable: true,
  29399. configurable: true
  29400. });
  29401. PostProcessRenderEffect.prototype._update = function () {
  29402. for (var renderPassName in this._renderPasses) {
  29403. this._renderPasses[renderPassName]._update();
  29404. }
  29405. };
  29406. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29407. this._renderPasses[renderPass._name] = renderPass;
  29408. this._linkParameters();
  29409. };
  29410. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29411. delete this._renderPasses[renderPass._name];
  29412. this._linkParameters();
  29413. };
  29414. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29415. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29416. this._linkParameters();
  29417. };
  29418. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29419. for (var renderPassName in this._renderPasses) {
  29420. if (renderPassName === passName) {
  29421. return this._renderPasses[passName];
  29422. }
  29423. }
  29424. };
  29425. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29426. this._renderPasses = {};
  29427. this._linkParameters();
  29428. };
  29429. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29430. var cameraKey;
  29431. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29432. for (var i = 0; i < _cam.length; i++) {
  29433. var camera = _cam[i];
  29434. var cameraName = camera.name;
  29435. if (this._singleInstance) {
  29436. cameraKey = 0;
  29437. }
  29438. else {
  29439. cameraKey = cameraName;
  29440. }
  29441. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29442. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29443. if (!this._indicesForCamera[cameraName]) {
  29444. this._indicesForCamera[cameraName] = [];
  29445. }
  29446. this._indicesForCamera[cameraName].push(index);
  29447. if (this._cameras.indexOf(camera) === -1) {
  29448. this._cameras[cameraName] = camera;
  29449. }
  29450. for (var passName in this._renderPasses) {
  29451. this._renderPasses[passName]._incRefCount();
  29452. }
  29453. }
  29454. this._linkParameters();
  29455. };
  29456. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29457. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29458. for (var i = 0; i < _cam.length; i++) {
  29459. var camera = _cam[i];
  29460. var cameraName = camera.name;
  29461. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29462. var index = this._cameras.indexOf(cameraName);
  29463. this._indicesForCamera.splice(index, 1);
  29464. this._cameras.splice(index, 1);
  29465. for (var passName in this._renderPasses) {
  29466. this._renderPasses[passName]._decRefCount();
  29467. }
  29468. }
  29469. };
  29470. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29471. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29472. for (var i = 0; i < _cam.length; i++) {
  29473. var camera = _cam[i];
  29474. var cameraName = camera.name;
  29475. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29476. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29477. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29478. }
  29479. }
  29480. for (var passName in this._renderPasses) {
  29481. this._renderPasses[passName]._incRefCount();
  29482. }
  29483. }
  29484. };
  29485. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29486. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29487. for (var i = 0; i < _cam.length; i++) {
  29488. var camera = _cam[i];
  29489. var cameraName = camera.Name;
  29490. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29491. for (var passName in this._renderPasses) {
  29492. this._renderPasses[passName]._decRefCount();
  29493. }
  29494. }
  29495. };
  29496. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29497. if (this._singleInstance) {
  29498. return this._postProcesses[0];
  29499. }
  29500. else {
  29501. return this._postProcesses[camera.name];
  29502. }
  29503. };
  29504. PostProcessRenderEffect.prototype._linkParameters = function () {
  29505. var _this = this;
  29506. for (var index in this._postProcesses) {
  29507. if (this.applyParameters) {
  29508. this.applyParameters(this._postProcesses[index]);
  29509. }
  29510. this._postProcesses[index].onBeforeRender = function (effect) {
  29511. _this._linkTextures(effect);
  29512. };
  29513. }
  29514. };
  29515. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29516. for (var renderPassName in this._renderPasses) {
  29517. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29518. }
  29519. for (var renderEffectName in this._renderEffectAsPasses) {
  29520. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29521. }
  29522. };
  29523. return PostProcessRenderEffect;
  29524. }());
  29525. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29526. })(BABYLON || (BABYLON = {}));
  29527. var BABYLON;
  29528. (function (BABYLON) {
  29529. var PostProcessRenderPipeline = (function () {
  29530. function PostProcessRenderPipeline(engine, name) {
  29531. this._engine = engine;
  29532. this._name = name;
  29533. this._renderEffects = {};
  29534. this._renderEffectsForIsolatedPass = {};
  29535. this._cameras = [];
  29536. }
  29537. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29538. get: function () {
  29539. for (var renderEffectName in this._renderEffects) {
  29540. if (!this._renderEffects[renderEffectName].isSupported) {
  29541. return false;
  29542. }
  29543. }
  29544. return true;
  29545. },
  29546. enumerable: true,
  29547. configurable: true
  29548. });
  29549. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29550. this._renderEffects[renderEffect._name] = renderEffect;
  29551. };
  29552. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29553. var renderEffects = this._renderEffects[renderEffectName];
  29554. if (!renderEffects) {
  29555. return;
  29556. }
  29557. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29558. };
  29559. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29560. var renderEffects = this._renderEffects[renderEffectName];
  29561. if (!renderEffects) {
  29562. return;
  29563. }
  29564. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29565. };
  29566. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29567. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29568. var indicesToDelete = [];
  29569. var i;
  29570. for (i = 0; i < _cam.length; i++) {
  29571. var camera = _cam[i];
  29572. var cameraName = camera.name;
  29573. if (this._cameras.indexOf(camera) === -1) {
  29574. this._cameras[cameraName] = camera;
  29575. }
  29576. else if (unique) {
  29577. indicesToDelete.push(i);
  29578. }
  29579. }
  29580. for (i = 0; i < indicesToDelete.length; i++) {
  29581. cameras.splice(indicesToDelete[i], 1);
  29582. }
  29583. for (var renderEffectName in this._renderEffects) {
  29584. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29585. }
  29586. };
  29587. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  29588. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29589. for (var renderEffectName in this._renderEffects) {
  29590. this._renderEffects[renderEffectName]._detachCameras(_cam);
  29591. }
  29592. for (var i = 0; i < _cam.length; i++) {
  29593. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  29594. }
  29595. };
  29596. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  29597. var _this = this;
  29598. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29599. var pass = null;
  29600. var renderEffectName;
  29601. for (renderEffectName in this._renderEffects) {
  29602. pass = this._renderEffects[renderEffectName].getPass(passName);
  29603. if (pass != null) {
  29604. break;
  29605. }
  29606. }
  29607. if (pass === null) {
  29608. return;
  29609. }
  29610. for (renderEffectName in this._renderEffects) {
  29611. this._renderEffects[renderEffectName]._disable(_cam);
  29612. }
  29613. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  29614. for (var i = 0; i < _cam.length; i++) {
  29615. var camera = _cam[i];
  29616. var cameraName = camera.name;
  29617. 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); });
  29618. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  29619. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  29620. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  29621. }
  29622. };
  29623. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  29624. var _this = this;
  29625. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29626. for (var i = 0; i < _cam.length; i++) {
  29627. var camera = _cam[i];
  29628. var cameraName = camera.name;
  29629. 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); });
  29630. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  29631. }
  29632. for (var renderEffectName in this._renderEffects) {
  29633. this._renderEffects[renderEffectName]._enable(_cam);
  29634. }
  29635. };
  29636. PostProcessRenderPipeline.prototype._update = function () {
  29637. for (var renderEffectName in this._renderEffects) {
  29638. this._renderEffects[renderEffectName]._update();
  29639. }
  29640. for (var i = 0; i < this._cameras.length; i++) {
  29641. var cameraName = this._cameras[i].name;
  29642. if (this._renderEffectsForIsolatedPass[cameraName]) {
  29643. this._renderEffectsForIsolatedPass[cameraName]._update();
  29644. }
  29645. }
  29646. };
  29647. PostProcessRenderPipeline.prototype.dispose = function () {
  29648. // Must be implemented by children
  29649. };
  29650. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  29651. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  29652. return PostProcessRenderPipeline;
  29653. }());
  29654. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  29655. })(BABYLON || (BABYLON = {}));
  29656. var BABYLON;
  29657. (function (BABYLON) {
  29658. var PostProcessRenderPipelineManager = (function () {
  29659. function PostProcessRenderPipelineManager() {
  29660. this._renderPipelines = {};
  29661. }
  29662. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  29663. this._renderPipelines[renderPipeline._name] = renderPipeline;
  29664. };
  29665. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  29666. var renderPipeline = this._renderPipelines[renderPipelineName];
  29667. if (!renderPipeline) {
  29668. return;
  29669. }
  29670. renderPipeline._attachCameras(cameras, unique);
  29671. };
  29672. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  29673. var renderPipeline = this._renderPipelines[renderPipelineName];
  29674. if (!renderPipeline) {
  29675. return;
  29676. }
  29677. renderPipeline._detachCameras(cameras);
  29678. };
  29679. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29680. var renderPipeline = this._renderPipelines[renderPipelineName];
  29681. if (!renderPipeline) {
  29682. return;
  29683. }
  29684. renderPipeline._enableEffect(renderEffectName, cameras);
  29685. };
  29686. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29687. var renderPipeline = this._renderPipelines[renderPipelineName];
  29688. if (!renderPipeline) {
  29689. return;
  29690. }
  29691. renderPipeline._disableEffect(renderEffectName, cameras);
  29692. };
  29693. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  29694. var renderPipeline = this._renderPipelines[renderPipelineName];
  29695. if (!renderPipeline) {
  29696. return;
  29697. }
  29698. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  29699. };
  29700. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  29701. var renderPipeline = this._renderPipelines[renderPipelineName];
  29702. if (!renderPipeline) {
  29703. return;
  29704. }
  29705. renderPipeline._disableDisplayOnlyPass(cameras);
  29706. };
  29707. PostProcessRenderPipelineManager.prototype.update = function () {
  29708. for (var renderPipelineName in this._renderPipelines) {
  29709. var pipeline = this._renderPipelines[renderPipelineName];
  29710. if (!pipeline.isSupported) {
  29711. pipeline.dispose();
  29712. delete this._renderPipelines[renderPipelineName];
  29713. }
  29714. else {
  29715. pipeline._update();
  29716. }
  29717. }
  29718. };
  29719. return PostProcessRenderPipelineManager;
  29720. }());
  29721. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  29722. })(BABYLON || (BABYLON = {}));
  29723. var BABYLON;
  29724. (function (BABYLON) {
  29725. var BoundingBoxRenderer = (function () {
  29726. function BoundingBoxRenderer(scene) {
  29727. this.frontColor = new BABYLON.Color3(1, 1, 1);
  29728. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  29729. this.showBackLines = true;
  29730. this.renderList = new BABYLON.SmartArray(32);
  29731. this._scene = scene;
  29732. }
  29733. BoundingBoxRenderer.prototype._prepareRessources = function () {
  29734. if (this._colorShader) {
  29735. return;
  29736. }
  29737. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  29738. attributes: ["position"],
  29739. uniforms: ["worldViewProjection", "color"]
  29740. });
  29741. var engine = this._scene.getEngine();
  29742. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  29743. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  29744. 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]);
  29745. };
  29746. BoundingBoxRenderer.prototype.reset = function () {
  29747. this.renderList.reset();
  29748. };
  29749. BoundingBoxRenderer.prototype.render = function () {
  29750. if (this.renderList.length === 0) {
  29751. return;
  29752. }
  29753. this._prepareRessources();
  29754. if (!this._colorShader.isReady()) {
  29755. return;
  29756. }
  29757. var engine = this._scene.getEngine();
  29758. engine.setDepthWrite(false);
  29759. this._colorShader._preBind();
  29760. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  29761. var boundingBox = this.renderList.data[boundingBoxIndex];
  29762. var min = boundingBox.minimum;
  29763. var max = boundingBox.maximum;
  29764. var diff = max.subtract(min);
  29765. var median = min.add(diff.scale(0.5));
  29766. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  29767. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  29768. .multiply(boundingBox.getWorldMatrix());
  29769. // VBOs
  29770. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  29771. if (this.showBackLines) {
  29772. // Back
  29773. engine.setDepthFunctionToGreaterOrEqual();
  29774. this._scene.resetCachedMaterial();
  29775. this._colorShader.setColor4("color", this.backColor.toColor4());
  29776. this._colorShader.bind(worldMatrix);
  29777. // Draw order
  29778. engine.draw(false, 0, 24);
  29779. }
  29780. // Front
  29781. engine.setDepthFunctionToLess();
  29782. this._scene.resetCachedMaterial();
  29783. this._colorShader.setColor4("color", this.frontColor.toColor4());
  29784. this._colorShader.bind(worldMatrix);
  29785. // Draw order
  29786. engine.draw(false, 0, 24);
  29787. }
  29788. this._colorShader.unbind();
  29789. engine.setDepthFunctionToLessOrEqual();
  29790. engine.setDepthWrite(true);
  29791. };
  29792. BoundingBoxRenderer.prototype.dispose = function () {
  29793. if (!this._colorShader) {
  29794. return;
  29795. }
  29796. this._colorShader.dispose();
  29797. this._vb.dispose();
  29798. this._scene.getEngine()._releaseBuffer(this._ib);
  29799. };
  29800. return BoundingBoxRenderer;
  29801. }());
  29802. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  29803. })(BABYLON || (BABYLON = {}));
  29804. var BABYLON;
  29805. (function (BABYLON) {
  29806. var Condition = (function () {
  29807. function Condition(actionManager) {
  29808. this._actionManager = actionManager;
  29809. }
  29810. Condition.prototype.isValid = function () {
  29811. return true;
  29812. };
  29813. Condition.prototype._getProperty = function (propertyPath) {
  29814. return this._actionManager._getProperty(propertyPath);
  29815. };
  29816. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  29817. return this._actionManager._getEffectiveTarget(target, propertyPath);
  29818. };
  29819. return Condition;
  29820. }());
  29821. BABYLON.Condition = Condition;
  29822. var ValueCondition = (function (_super) {
  29823. __extends(ValueCondition, _super);
  29824. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  29825. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  29826. _super.call(this, actionManager);
  29827. this.propertyPath = propertyPath;
  29828. this.value = value;
  29829. this.operator = operator;
  29830. this._target = this._getEffectiveTarget(target, this.propertyPath);
  29831. this._property = this._getProperty(this.propertyPath);
  29832. }
  29833. Object.defineProperty(ValueCondition, "IsEqual", {
  29834. get: function () {
  29835. return ValueCondition._IsEqual;
  29836. },
  29837. enumerable: true,
  29838. configurable: true
  29839. });
  29840. Object.defineProperty(ValueCondition, "IsDifferent", {
  29841. get: function () {
  29842. return ValueCondition._IsDifferent;
  29843. },
  29844. enumerable: true,
  29845. configurable: true
  29846. });
  29847. Object.defineProperty(ValueCondition, "IsGreater", {
  29848. get: function () {
  29849. return ValueCondition._IsGreater;
  29850. },
  29851. enumerable: true,
  29852. configurable: true
  29853. });
  29854. Object.defineProperty(ValueCondition, "IsLesser", {
  29855. get: function () {
  29856. return ValueCondition._IsLesser;
  29857. },
  29858. enumerable: true,
  29859. configurable: true
  29860. });
  29861. // Methods
  29862. ValueCondition.prototype.isValid = function () {
  29863. switch (this.operator) {
  29864. case ValueCondition.IsGreater:
  29865. return this._target[this._property] > this.value;
  29866. case ValueCondition.IsLesser:
  29867. return this._target[this._property] < this.value;
  29868. case ValueCondition.IsEqual:
  29869. case ValueCondition.IsDifferent:
  29870. var check;
  29871. if (this.value.equals) {
  29872. check = this.value.equals(this._target[this._property]);
  29873. }
  29874. else {
  29875. check = this.value === this._target[this._property];
  29876. }
  29877. return this.operator === ValueCondition.IsEqual ? check : !check;
  29878. }
  29879. return false;
  29880. };
  29881. // Statics
  29882. ValueCondition._IsEqual = 0;
  29883. ValueCondition._IsDifferent = 1;
  29884. ValueCondition._IsGreater = 2;
  29885. ValueCondition._IsLesser = 3;
  29886. return ValueCondition;
  29887. }(Condition));
  29888. BABYLON.ValueCondition = ValueCondition;
  29889. var PredicateCondition = (function (_super) {
  29890. __extends(PredicateCondition, _super);
  29891. function PredicateCondition(actionManager, predicate) {
  29892. _super.call(this, actionManager);
  29893. this.predicate = predicate;
  29894. }
  29895. PredicateCondition.prototype.isValid = function () {
  29896. return this.predicate();
  29897. };
  29898. return PredicateCondition;
  29899. }(Condition));
  29900. BABYLON.PredicateCondition = PredicateCondition;
  29901. var StateCondition = (function (_super) {
  29902. __extends(StateCondition, _super);
  29903. function StateCondition(actionManager, target, value) {
  29904. _super.call(this, actionManager);
  29905. this.value = value;
  29906. this._target = target;
  29907. }
  29908. // Methods
  29909. StateCondition.prototype.isValid = function () {
  29910. return this._target.state === this.value;
  29911. };
  29912. return StateCondition;
  29913. }(Condition));
  29914. BABYLON.StateCondition = StateCondition;
  29915. })(BABYLON || (BABYLON = {}));
  29916. var BABYLON;
  29917. (function (BABYLON) {
  29918. var Action = (function () {
  29919. function Action(triggerOptions, condition) {
  29920. this.triggerOptions = triggerOptions;
  29921. if (triggerOptions.parameter) {
  29922. this.trigger = triggerOptions.trigger;
  29923. this._triggerParameter = triggerOptions.parameter;
  29924. }
  29925. else {
  29926. this.trigger = triggerOptions;
  29927. }
  29928. this._nextActiveAction = this;
  29929. this._condition = condition;
  29930. }
  29931. // Methods
  29932. Action.prototype._prepare = function () {
  29933. };
  29934. Action.prototype.getTriggerParameter = function () {
  29935. return this._triggerParameter;
  29936. };
  29937. Action.prototype._executeCurrent = function (evt) {
  29938. if (this._nextActiveAction._condition) {
  29939. var condition = this._nextActiveAction._condition;
  29940. var currentRenderId = this._actionManager.getScene().getRenderId();
  29941. // We cache the current evaluation for the current frame
  29942. if (condition._evaluationId === currentRenderId) {
  29943. if (!condition._currentResult) {
  29944. return;
  29945. }
  29946. }
  29947. else {
  29948. condition._evaluationId = currentRenderId;
  29949. if (!condition.isValid()) {
  29950. condition._currentResult = false;
  29951. return;
  29952. }
  29953. condition._currentResult = true;
  29954. }
  29955. }
  29956. this._nextActiveAction.execute(evt);
  29957. this.skipToNextActiveAction();
  29958. };
  29959. Action.prototype.execute = function (evt) {
  29960. };
  29961. Action.prototype.skipToNextActiveAction = function () {
  29962. if (this._nextActiveAction._child) {
  29963. if (!this._nextActiveAction._child._actionManager) {
  29964. this._nextActiveAction._child._actionManager = this._actionManager;
  29965. }
  29966. this._nextActiveAction = this._nextActiveAction._child;
  29967. }
  29968. else {
  29969. this._nextActiveAction = this;
  29970. }
  29971. };
  29972. Action.prototype.then = function (action) {
  29973. this._child = action;
  29974. action._actionManager = this._actionManager;
  29975. action._prepare();
  29976. return action;
  29977. };
  29978. Action.prototype._getProperty = function (propertyPath) {
  29979. return this._actionManager._getProperty(propertyPath);
  29980. };
  29981. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  29982. return this._actionManager._getEffectiveTarget(target, propertyPath);
  29983. };
  29984. return Action;
  29985. }());
  29986. BABYLON.Action = Action;
  29987. })(BABYLON || (BABYLON = {}));
  29988. var BABYLON;
  29989. (function (BABYLON) {
  29990. /**
  29991. * ActionEvent is the event beint sent when an action is triggered.
  29992. */
  29993. var ActionEvent = (function () {
  29994. /**
  29995. * @constructor
  29996. * @param source The mesh or sprite that triggered the action.
  29997. * @param pointerX The X mouse cursor position at the time of the event
  29998. * @param pointerY The Y mouse cursor position at the time of the event
  29999. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30000. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30001. */
  30002. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30003. this.source = source;
  30004. this.pointerX = pointerX;
  30005. this.pointerY = pointerY;
  30006. this.meshUnderPointer = meshUnderPointer;
  30007. this.sourceEvent = sourceEvent;
  30008. this.additionalData = additionalData;
  30009. }
  30010. /**
  30011. * Helper function to auto-create an ActionEvent from a source mesh.
  30012. * @param source The source mesh that triggered the event
  30013. * @param evt {Event} The original (browser) event
  30014. */
  30015. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30016. var scene = source.getScene();
  30017. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30018. };
  30019. /**
  30020. * Helper function to auto-create an ActionEvent from a source mesh.
  30021. * @param source The source sprite that triggered the event
  30022. * @param scene Scene associated with the sprite
  30023. * @param evt {Event} The original (browser) event
  30024. */
  30025. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30026. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30027. };
  30028. /**
  30029. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30030. * @param scene the scene where the event occurred
  30031. * @param evt {Event} The original (browser) event
  30032. */
  30033. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30034. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30035. };
  30036. return ActionEvent;
  30037. }());
  30038. BABYLON.ActionEvent = ActionEvent;
  30039. /**
  30040. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30041. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30042. */
  30043. var ActionManager = (function () {
  30044. function ActionManager(scene) {
  30045. // Members
  30046. this.actions = new Array();
  30047. this._scene = scene;
  30048. scene._actionManagers.push(this);
  30049. }
  30050. Object.defineProperty(ActionManager, "NothingTrigger", {
  30051. get: function () {
  30052. return ActionManager._NothingTrigger;
  30053. },
  30054. enumerable: true,
  30055. configurable: true
  30056. });
  30057. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30058. get: function () {
  30059. return ActionManager._OnPickTrigger;
  30060. },
  30061. enumerable: true,
  30062. configurable: true
  30063. });
  30064. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30065. get: function () {
  30066. return ActionManager._OnLeftPickTrigger;
  30067. },
  30068. enumerable: true,
  30069. configurable: true
  30070. });
  30071. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30072. get: function () {
  30073. return ActionManager._OnRightPickTrigger;
  30074. },
  30075. enumerable: true,
  30076. configurable: true
  30077. });
  30078. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30079. get: function () {
  30080. return ActionManager._OnCenterPickTrigger;
  30081. },
  30082. enumerable: true,
  30083. configurable: true
  30084. });
  30085. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30086. get: function () {
  30087. return ActionManager._OnPickDownTrigger;
  30088. },
  30089. enumerable: true,
  30090. configurable: true
  30091. });
  30092. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30093. get: function () {
  30094. return ActionManager._OnPickUpTrigger;
  30095. },
  30096. enumerable: true,
  30097. configurable: true
  30098. });
  30099. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30100. /// This trigger will only be raised if you also declared a OnPickDown
  30101. get: function () {
  30102. return ActionManager._OnPickOutTrigger;
  30103. },
  30104. enumerable: true,
  30105. configurable: true
  30106. });
  30107. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30108. get: function () {
  30109. return ActionManager._OnLongPressTrigger;
  30110. },
  30111. enumerable: true,
  30112. configurable: true
  30113. });
  30114. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30115. get: function () {
  30116. return ActionManager._OnPointerOverTrigger;
  30117. },
  30118. enumerable: true,
  30119. configurable: true
  30120. });
  30121. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30122. get: function () {
  30123. return ActionManager._OnPointerOutTrigger;
  30124. },
  30125. enumerable: true,
  30126. configurable: true
  30127. });
  30128. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30129. get: function () {
  30130. return ActionManager._OnEveryFrameTrigger;
  30131. },
  30132. enumerable: true,
  30133. configurable: true
  30134. });
  30135. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30136. get: function () {
  30137. return ActionManager._OnIntersectionEnterTrigger;
  30138. },
  30139. enumerable: true,
  30140. configurable: true
  30141. });
  30142. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30143. get: function () {
  30144. return ActionManager._OnIntersectionExitTrigger;
  30145. },
  30146. enumerable: true,
  30147. configurable: true
  30148. });
  30149. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30150. get: function () {
  30151. return ActionManager._OnKeyDownTrigger;
  30152. },
  30153. enumerable: true,
  30154. configurable: true
  30155. });
  30156. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30157. get: function () {
  30158. return ActionManager._OnKeyUpTrigger;
  30159. },
  30160. enumerable: true,
  30161. configurable: true
  30162. });
  30163. // Methods
  30164. ActionManager.prototype.dispose = function () {
  30165. var index = this._scene._actionManagers.indexOf(this);
  30166. if (index > -1) {
  30167. this._scene._actionManagers.splice(index, 1);
  30168. }
  30169. };
  30170. ActionManager.prototype.getScene = function () {
  30171. return this._scene;
  30172. };
  30173. /**
  30174. * Does this action manager handles actions of any of the given triggers
  30175. * @param {number[]} triggers - the triggers to be tested
  30176. * @return {boolean} whether one (or more) of the triggers is handeled
  30177. */
  30178. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30179. for (var index = 0; index < this.actions.length; index++) {
  30180. var action = this.actions[index];
  30181. if (triggers.indexOf(action.trigger) > -1) {
  30182. return true;
  30183. }
  30184. }
  30185. return false;
  30186. };
  30187. /**
  30188. * Does this action manager handles actions of a given trigger
  30189. * @param {number} trigger - the trigger to be tested
  30190. * @return {boolean} whether the trigger is handeled
  30191. */
  30192. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30193. for (var index = 0; index < this.actions.length; index++) {
  30194. var action = this.actions[index];
  30195. if (action.trigger === trigger) {
  30196. return true;
  30197. }
  30198. }
  30199. return false;
  30200. };
  30201. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30202. /**
  30203. * Does this action manager has pointer triggers
  30204. * @return {boolean} whether or not it has pointer triggers
  30205. */
  30206. get: function () {
  30207. for (var index = 0; index < this.actions.length; index++) {
  30208. var action = this.actions[index];
  30209. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30210. return true;
  30211. }
  30212. }
  30213. return false;
  30214. },
  30215. enumerable: true,
  30216. configurable: true
  30217. });
  30218. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30219. /**
  30220. * Does this action manager has pick triggers
  30221. * @return {boolean} whether or not it has pick triggers
  30222. */
  30223. get: function () {
  30224. for (var index = 0; index < this.actions.length; index++) {
  30225. var action = this.actions[index];
  30226. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30227. return true;
  30228. }
  30229. }
  30230. return false;
  30231. },
  30232. enumerable: true,
  30233. configurable: true
  30234. });
  30235. /**
  30236. * Registers an action to this action manager
  30237. * @param {BABYLON.Action} action - the action to be registered
  30238. * @return {BABYLON.Action} the action amended (prepared) after registration
  30239. */
  30240. ActionManager.prototype.registerAction = function (action) {
  30241. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30242. if (this.getScene().actionManager !== this) {
  30243. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30244. return null;
  30245. }
  30246. }
  30247. this.actions.push(action);
  30248. action._actionManager = this;
  30249. action._prepare();
  30250. return action;
  30251. };
  30252. /**
  30253. * Process a specific trigger
  30254. * @param {number} trigger - the trigger to process
  30255. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30256. */
  30257. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30258. for (var index = 0; index < this.actions.length; index++) {
  30259. var action = this.actions[index];
  30260. if (action.trigger === trigger) {
  30261. if (trigger === ActionManager.OnKeyUpTrigger
  30262. || trigger === ActionManager.OnKeyDownTrigger) {
  30263. var parameter = action.getTriggerParameter();
  30264. if (parameter) {
  30265. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30266. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30267. if (actualkey !== parameter.toLowerCase()) {
  30268. continue;
  30269. }
  30270. }
  30271. }
  30272. action._executeCurrent(evt);
  30273. }
  30274. }
  30275. };
  30276. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30277. var properties = propertyPath.split(".");
  30278. for (var index = 0; index < properties.length - 1; index++) {
  30279. target = target[properties[index]];
  30280. }
  30281. return target;
  30282. };
  30283. ActionManager.prototype._getProperty = function (propertyPath) {
  30284. var properties = propertyPath.split(".");
  30285. return properties[properties.length - 1];
  30286. };
  30287. ActionManager.Parse = function (parsedActions, object, scene) {
  30288. var actionManager = new BABYLON.ActionManager(scene);
  30289. if (object === null)
  30290. scene.actionManager = actionManager;
  30291. else
  30292. object.actionManager = actionManager;
  30293. // instanciate a new object
  30294. var instanciate = function (name, params) {
  30295. var newInstance = Object.create(BABYLON[name].prototype);
  30296. newInstance.constructor.apply(newInstance, params);
  30297. return newInstance;
  30298. };
  30299. var parseParameter = function (name, value, target, propertyPath) {
  30300. if (propertyPath === null) {
  30301. // String, boolean or float
  30302. var floatValue = parseFloat(value);
  30303. if (value === "true" || value === "false")
  30304. return value === "true";
  30305. else
  30306. return isNaN(floatValue) ? value : floatValue;
  30307. }
  30308. var effectiveTarget = propertyPath.split(".");
  30309. var values = value.split(",");
  30310. // Get effective Target
  30311. for (var i = 0; i < effectiveTarget.length; i++) {
  30312. target = target[effectiveTarget[i]];
  30313. }
  30314. // Return appropriate value with its type
  30315. if (typeof (target) === "boolean")
  30316. return values[0] === "true";
  30317. if (typeof (target) === "string")
  30318. return values[0];
  30319. // Parameters with multiple values such as Vector3 etc.
  30320. var split = new Array();
  30321. for (var i = 0; i < values.length; i++)
  30322. split.push(parseFloat(values[i]));
  30323. if (target instanceof BABYLON.Vector3)
  30324. return BABYLON.Vector3.FromArray(split);
  30325. if (target instanceof BABYLON.Vector4)
  30326. return BABYLON.Vector4.FromArray(split);
  30327. if (target instanceof BABYLON.Color3)
  30328. return BABYLON.Color3.FromArray(split);
  30329. if (target instanceof BABYLON.Color4)
  30330. return BABYLON.Color4.FromArray(split);
  30331. return parseFloat(values[0]);
  30332. };
  30333. // traverse graph per trigger
  30334. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30335. if (combineArray === void 0) { combineArray = null; }
  30336. if (parsedAction.detached)
  30337. return;
  30338. var parameters = new Array();
  30339. var target = null;
  30340. var propertyPath = null;
  30341. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30342. // Parameters
  30343. if (parsedAction.type === 2)
  30344. parameters.push(actionManager);
  30345. else
  30346. parameters.push(trigger);
  30347. if (combine) {
  30348. var actions = new Array();
  30349. for (var j = 0; j < parsedAction.combine.length; j++) {
  30350. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30351. }
  30352. parameters.push(actions);
  30353. }
  30354. else {
  30355. for (var i = 0; i < parsedAction.properties.length; i++) {
  30356. var value = parsedAction.properties[i].value;
  30357. var name = parsedAction.properties[i].name;
  30358. var targetType = parsedAction.properties[i].targetType;
  30359. if (name === "target")
  30360. if (targetType !== null && targetType === "SceneProperties")
  30361. value = target = scene;
  30362. else
  30363. value = target = scene.getNodeByName(value);
  30364. else if (name === "parent")
  30365. value = scene.getNodeByName(value);
  30366. else if (name === "sound")
  30367. value = scene.getSoundByName(value);
  30368. else if (name !== "propertyPath") {
  30369. if (parsedAction.type === 2 && name === "operator")
  30370. value = BABYLON.ValueCondition[value];
  30371. else
  30372. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30373. }
  30374. else {
  30375. propertyPath = value;
  30376. }
  30377. parameters.push(value);
  30378. }
  30379. }
  30380. if (combineArray === null) {
  30381. parameters.push(condition);
  30382. }
  30383. else {
  30384. parameters.push(null);
  30385. }
  30386. // If interpolate value action
  30387. if (parsedAction.name === "InterpolateValueAction") {
  30388. var param = parameters[parameters.length - 2];
  30389. parameters[parameters.length - 1] = param;
  30390. parameters[parameters.length - 2] = condition;
  30391. }
  30392. // Action or condition(s) and not CombineAction
  30393. var newAction = instanciate(parsedAction.name, parameters);
  30394. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30395. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30396. if (action)
  30397. action.then(nothing);
  30398. else
  30399. actionManager.registerAction(nothing);
  30400. action = nothing;
  30401. }
  30402. if (combineArray === null) {
  30403. if (newAction instanceof BABYLON.Condition) {
  30404. condition = newAction;
  30405. newAction = action;
  30406. }
  30407. else {
  30408. condition = null;
  30409. if (action)
  30410. action.then(newAction);
  30411. else
  30412. actionManager.registerAction(newAction);
  30413. }
  30414. }
  30415. else {
  30416. combineArray.push(newAction);
  30417. }
  30418. for (var i = 0; i < parsedAction.children.length; i++)
  30419. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30420. };
  30421. // triggers
  30422. for (var i = 0; i < parsedActions.children.length; i++) {
  30423. var triggerParams;
  30424. var trigger = parsedActions.children[i];
  30425. if (trigger.properties.length > 0) {
  30426. var param = trigger.properties[0].value;
  30427. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30428. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30429. }
  30430. else
  30431. triggerParams = BABYLON.ActionManager[trigger.name];
  30432. for (var j = 0; j < trigger.children.length; j++) {
  30433. if (!trigger.detached)
  30434. traverse(trigger.children[j], triggerParams, null, null);
  30435. }
  30436. }
  30437. };
  30438. // Statics
  30439. ActionManager._NothingTrigger = 0;
  30440. ActionManager._OnPickTrigger = 1;
  30441. ActionManager._OnLeftPickTrigger = 2;
  30442. ActionManager._OnRightPickTrigger = 3;
  30443. ActionManager._OnCenterPickTrigger = 4;
  30444. ActionManager._OnPickDownTrigger = 5;
  30445. ActionManager._OnPickUpTrigger = 6;
  30446. ActionManager._OnLongPressTrigger = 7;
  30447. ActionManager._OnPointerOverTrigger = 8;
  30448. ActionManager._OnPointerOutTrigger = 9;
  30449. ActionManager._OnEveryFrameTrigger = 10;
  30450. ActionManager._OnIntersectionEnterTrigger = 11;
  30451. ActionManager._OnIntersectionExitTrigger = 12;
  30452. ActionManager._OnKeyDownTrigger = 13;
  30453. ActionManager._OnKeyUpTrigger = 14;
  30454. ActionManager._OnPickOutTrigger = 15;
  30455. ActionManager.DragMovementThreshold = 10; // in pixels
  30456. ActionManager.LongPressDelay = 500; // in milliseconds
  30457. return ActionManager;
  30458. }());
  30459. BABYLON.ActionManager = ActionManager;
  30460. })(BABYLON || (BABYLON = {}));
  30461. var BABYLON;
  30462. (function (BABYLON) {
  30463. var InterpolateValueAction = (function (_super) {
  30464. __extends(InterpolateValueAction, _super);
  30465. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  30466. if (duration === void 0) { duration = 1000; }
  30467. _super.call(this, triggerOptions, condition);
  30468. this.propertyPath = propertyPath;
  30469. this.value = value;
  30470. this.duration = duration;
  30471. this.stopOtherAnimations = stopOtherAnimations;
  30472. this.onInterpolationDone = onInterpolationDone;
  30473. this._target = target;
  30474. }
  30475. InterpolateValueAction.prototype._prepare = function () {
  30476. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30477. this._property = this._getProperty(this.propertyPath);
  30478. };
  30479. InterpolateValueAction.prototype.execute = function () {
  30480. var scene = this._actionManager.getScene();
  30481. var keys = [
  30482. {
  30483. frame: 0,
  30484. value: this._target[this._property]
  30485. }, {
  30486. frame: 100,
  30487. value: this.value
  30488. }
  30489. ];
  30490. var dataType;
  30491. if (typeof this.value === "number") {
  30492. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  30493. }
  30494. else if (this.value instanceof BABYLON.Color3) {
  30495. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  30496. }
  30497. else if (this.value instanceof BABYLON.Vector3) {
  30498. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  30499. }
  30500. else if (this.value instanceof BABYLON.Matrix) {
  30501. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  30502. }
  30503. else if (this.value instanceof BABYLON.Quaternion) {
  30504. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  30505. }
  30506. else {
  30507. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  30508. return;
  30509. }
  30510. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30511. animation.setKeys(keys);
  30512. if (this.stopOtherAnimations) {
  30513. scene.stopAnimation(this._target);
  30514. }
  30515. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  30516. };
  30517. return InterpolateValueAction;
  30518. }(BABYLON.Action));
  30519. BABYLON.InterpolateValueAction = InterpolateValueAction;
  30520. })(BABYLON || (BABYLON = {}));
  30521. var BABYLON;
  30522. (function (BABYLON) {
  30523. var SwitchBooleanAction = (function (_super) {
  30524. __extends(SwitchBooleanAction, _super);
  30525. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  30526. _super.call(this, triggerOptions, condition);
  30527. this.propertyPath = propertyPath;
  30528. this._target = target;
  30529. }
  30530. SwitchBooleanAction.prototype._prepare = function () {
  30531. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30532. this._property = this._getProperty(this.propertyPath);
  30533. };
  30534. SwitchBooleanAction.prototype.execute = function () {
  30535. this._target[this._property] = !this._target[this._property];
  30536. };
  30537. return SwitchBooleanAction;
  30538. }(BABYLON.Action));
  30539. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  30540. var SetStateAction = (function (_super) {
  30541. __extends(SetStateAction, _super);
  30542. function SetStateAction(triggerOptions, target, value, condition) {
  30543. _super.call(this, triggerOptions, condition);
  30544. this.value = value;
  30545. this._target = target;
  30546. }
  30547. SetStateAction.prototype.execute = function () {
  30548. this._target.state = this.value;
  30549. };
  30550. return SetStateAction;
  30551. }(BABYLON.Action));
  30552. BABYLON.SetStateAction = SetStateAction;
  30553. var SetValueAction = (function (_super) {
  30554. __extends(SetValueAction, _super);
  30555. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  30556. _super.call(this, triggerOptions, condition);
  30557. this.propertyPath = propertyPath;
  30558. this.value = value;
  30559. this._target = target;
  30560. }
  30561. SetValueAction.prototype._prepare = function () {
  30562. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30563. this._property = this._getProperty(this.propertyPath);
  30564. };
  30565. SetValueAction.prototype.execute = function () {
  30566. this._target[this._property] = this.value;
  30567. };
  30568. return SetValueAction;
  30569. }(BABYLON.Action));
  30570. BABYLON.SetValueAction = SetValueAction;
  30571. var IncrementValueAction = (function (_super) {
  30572. __extends(IncrementValueAction, _super);
  30573. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  30574. _super.call(this, triggerOptions, condition);
  30575. this.propertyPath = propertyPath;
  30576. this.value = value;
  30577. this._target = target;
  30578. }
  30579. IncrementValueAction.prototype._prepare = function () {
  30580. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30581. this._property = this._getProperty(this.propertyPath);
  30582. if (typeof this._target[this._property] !== "number") {
  30583. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  30584. }
  30585. };
  30586. IncrementValueAction.prototype.execute = function () {
  30587. this._target[this._property] += this.value;
  30588. };
  30589. return IncrementValueAction;
  30590. }(BABYLON.Action));
  30591. BABYLON.IncrementValueAction = IncrementValueAction;
  30592. var PlayAnimationAction = (function (_super) {
  30593. __extends(PlayAnimationAction, _super);
  30594. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  30595. _super.call(this, triggerOptions, condition);
  30596. this.from = from;
  30597. this.to = to;
  30598. this.loop = loop;
  30599. this._target = target;
  30600. }
  30601. PlayAnimationAction.prototype._prepare = function () {
  30602. };
  30603. PlayAnimationAction.prototype.execute = function () {
  30604. var scene = this._actionManager.getScene();
  30605. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  30606. };
  30607. return PlayAnimationAction;
  30608. }(BABYLON.Action));
  30609. BABYLON.PlayAnimationAction = PlayAnimationAction;
  30610. var StopAnimationAction = (function (_super) {
  30611. __extends(StopAnimationAction, _super);
  30612. function StopAnimationAction(triggerOptions, target, condition) {
  30613. _super.call(this, triggerOptions, condition);
  30614. this._target = target;
  30615. }
  30616. StopAnimationAction.prototype._prepare = function () {
  30617. };
  30618. StopAnimationAction.prototype.execute = function () {
  30619. var scene = this._actionManager.getScene();
  30620. scene.stopAnimation(this._target);
  30621. };
  30622. return StopAnimationAction;
  30623. }(BABYLON.Action));
  30624. BABYLON.StopAnimationAction = StopAnimationAction;
  30625. var DoNothingAction = (function (_super) {
  30626. __extends(DoNothingAction, _super);
  30627. function DoNothingAction(triggerOptions, condition) {
  30628. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  30629. _super.call(this, triggerOptions, condition);
  30630. }
  30631. DoNothingAction.prototype.execute = function () {
  30632. };
  30633. return DoNothingAction;
  30634. }(BABYLON.Action));
  30635. BABYLON.DoNothingAction = DoNothingAction;
  30636. var CombineAction = (function (_super) {
  30637. __extends(CombineAction, _super);
  30638. function CombineAction(triggerOptions, children, condition) {
  30639. _super.call(this, triggerOptions, condition);
  30640. this.children = children;
  30641. }
  30642. CombineAction.prototype._prepare = function () {
  30643. for (var index = 0; index < this.children.length; index++) {
  30644. this.children[index]._actionManager = this._actionManager;
  30645. this.children[index]._prepare();
  30646. }
  30647. };
  30648. CombineAction.prototype.execute = function (evt) {
  30649. for (var index = 0; index < this.children.length; index++) {
  30650. this.children[index].execute(evt);
  30651. }
  30652. };
  30653. return CombineAction;
  30654. }(BABYLON.Action));
  30655. BABYLON.CombineAction = CombineAction;
  30656. var ExecuteCodeAction = (function (_super) {
  30657. __extends(ExecuteCodeAction, _super);
  30658. function ExecuteCodeAction(triggerOptions, func, condition) {
  30659. _super.call(this, triggerOptions, condition);
  30660. this.func = func;
  30661. }
  30662. ExecuteCodeAction.prototype.execute = function (evt) {
  30663. this.func(evt);
  30664. };
  30665. return ExecuteCodeAction;
  30666. }(BABYLON.Action));
  30667. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  30668. var SetParentAction = (function (_super) {
  30669. __extends(SetParentAction, _super);
  30670. function SetParentAction(triggerOptions, target, parent, condition) {
  30671. _super.call(this, triggerOptions, condition);
  30672. this._target = target;
  30673. this._parent = parent;
  30674. }
  30675. SetParentAction.prototype._prepare = function () {
  30676. };
  30677. SetParentAction.prototype.execute = function () {
  30678. if (this._target.parent === this._parent) {
  30679. return;
  30680. }
  30681. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  30682. invertParentWorldMatrix.invert();
  30683. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  30684. this._target.parent = this._parent;
  30685. };
  30686. return SetParentAction;
  30687. }(BABYLON.Action));
  30688. BABYLON.SetParentAction = SetParentAction;
  30689. var PlaySoundAction = (function (_super) {
  30690. __extends(PlaySoundAction, _super);
  30691. function PlaySoundAction(triggerOptions, sound, condition) {
  30692. _super.call(this, triggerOptions, condition);
  30693. this._sound = sound;
  30694. }
  30695. PlaySoundAction.prototype._prepare = function () {
  30696. };
  30697. PlaySoundAction.prototype.execute = function () {
  30698. if (this._sound !== undefined)
  30699. this._sound.play();
  30700. };
  30701. return PlaySoundAction;
  30702. }(BABYLON.Action));
  30703. BABYLON.PlaySoundAction = PlaySoundAction;
  30704. var StopSoundAction = (function (_super) {
  30705. __extends(StopSoundAction, _super);
  30706. function StopSoundAction(triggerOptions, sound, condition) {
  30707. _super.call(this, triggerOptions, condition);
  30708. this._sound = sound;
  30709. }
  30710. StopSoundAction.prototype._prepare = function () {
  30711. };
  30712. StopSoundAction.prototype.execute = function () {
  30713. if (this._sound !== undefined)
  30714. this._sound.stop();
  30715. };
  30716. return StopSoundAction;
  30717. }(BABYLON.Action));
  30718. BABYLON.StopSoundAction = StopSoundAction;
  30719. })(BABYLON || (BABYLON = {}));
  30720. var BABYLON;
  30721. (function (BABYLON) {
  30722. var Geometry = (function () {
  30723. function Geometry(id, scene, vertexData, updatable, mesh) {
  30724. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30725. this._totalVertices = 0;
  30726. this._isDisposed = false;
  30727. this.id = id;
  30728. this._engine = scene.getEngine();
  30729. this._meshes = [];
  30730. this._scene = scene;
  30731. //Init vertex buffer cache
  30732. this._vertexBuffers = {};
  30733. this._indices = [];
  30734. // vertexData
  30735. if (vertexData) {
  30736. this.setAllVerticesData(vertexData, updatable);
  30737. }
  30738. else {
  30739. this._totalVertices = 0;
  30740. this._indices = [];
  30741. }
  30742. // applyToMesh
  30743. if (mesh) {
  30744. if (mesh instanceof BABYLON.LinesMesh) {
  30745. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30746. this.updateExtend();
  30747. }
  30748. this.applyToMesh(mesh);
  30749. mesh.computeWorldMatrix(true);
  30750. }
  30751. }
  30752. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30753. /**
  30754. * 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
  30755. * @returns The Bias Vector
  30756. */
  30757. get: function () {
  30758. return this._boundingBias;
  30759. },
  30760. set: function (value) {
  30761. if (this._boundingBias && this._boundingBias.equals(value)) {
  30762. return;
  30763. }
  30764. this._boundingBias = value.clone();
  30765. this.updateExtend();
  30766. },
  30767. enumerable: true,
  30768. configurable: true
  30769. });
  30770. Object.defineProperty(Geometry.prototype, "extend", {
  30771. get: function () {
  30772. return this._extend;
  30773. },
  30774. enumerable: true,
  30775. configurable: true
  30776. });
  30777. Geometry.prototype.getScene = function () {
  30778. return this._scene;
  30779. };
  30780. Geometry.prototype.getEngine = function () {
  30781. return this._engine;
  30782. };
  30783. Geometry.prototype.isReady = function () {
  30784. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30785. };
  30786. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30787. vertexData.applyToGeometry(this, updatable);
  30788. this.notifyUpdate();
  30789. };
  30790. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30791. if (this._vertexBuffers[kind]) {
  30792. this._vertexBuffers[kind].dispose();
  30793. }
  30794. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30795. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30796. stride = this._vertexBuffers[kind].getStrideSize();
  30797. this._totalVertices = data.length / stride;
  30798. this.updateExtend(data);
  30799. var meshes = this._meshes;
  30800. var numOfMeshes = meshes.length;
  30801. for (var index = 0; index < numOfMeshes; index++) {
  30802. var mesh = meshes[index];
  30803. mesh._resetPointsArrayCache();
  30804. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30805. mesh._createGlobalSubMesh();
  30806. mesh.computeWorldMatrix(true);
  30807. }
  30808. }
  30809. this.notifyUpdate(kind);
  30810. };
  30811. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30812. var vertexBuffer = this.getVertexBuffer(kind);
  30813. if (!vertexBuffer) {
  30814. return;
  30815. }
  30816. vertexBuffer.updateDirectly(data, offset);
  30817. this.notifyUpdate(kind);
  30818. };
  30819. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30820. var vertexBuffer = this.getVertexBuffer(kind);
  30821. if (!vertexBuffer) {
  30822. return;
  30823. }
  30824. vertexBuffer.update(data);
  30825. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30826. var stride = vertexBuffer.getStrideSize();
  30827. this._totalVertices = data.length / stride;
  30828. if (updateExtends) {
  30829. this.updateExtend(data);
  30830. }
  30831. var meshes = this._meshes;
  30832. var numOfMeshes = meshes.length;
  30833. for (var index = 0; index < numOfMeshes; index++) {
  30834. var mesh = meshes[index];
  30835. mesh._resetPointsArrayCache();
  30836. if (updateExtends) {
  30837. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30838. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30839. var subMesh = mesh.subMeshes[subIndex];
  30840. subMesh.refreshBoundingInfo();
  30841. }
  30842. }
  30843. }
  30844. }
  30845. this.notifyUpdate(kind);
  30846. };
  30847. Geometry.prototype.getTotalVertices = function () {
  30848. if (!this.isReady()) {
  30849. return 0;
  30850. }
  30851. return this._totalVertices;
  30852. };
  30853. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  30854. var vertexBuffer = this.getVertexBuffer(kind);
  30855. if (!vertexBuffer) {
  30856. return null;
  30857. }
  30858. var orig = vertexBuffer.getData();
  30859. if (!copyWhenShared || this._meshes.length === 1) {
  30860. return orig;
  30861. }
  30862. else {
  30863. var len = orig.length;
  30864. var copy = [];
  30865. for (var i = 0; i < len; i++) {
  30866. copy.push(orig[i]);
  30867. }
  30868. return copy;
  30869. }
  30870. };
  30871. Geometry.prototype.getVertexBuffer = function (kind) {
  30872. if (!this.isReady()) {
  30873. return null;
  30874. }
  30875. return this._vertexBuffers[kind];
  30876. };
  30877. Geometry.prototype.getVertexBuffers = function () {
  30878. if (!this.isReady()) {
  30879. return null;
  30880. }
  30881. return this._vertexBuffers;
  30882. };
  30883. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30884. if (!this._vertexBuffers) {
  30885. if (this._delayInfo) {
  30886. return this._delayInfo.indexOf(kind) !== -1;
  30887. }
  30888. return false;
  30889. }
  30890. return this._vertexBuffers[kind] !== undefined;
  30891. };
  30892. Geometry.prototype.getVerticesDataKinds = function () {
  30893. var result = [];
  30894. var kind;
  30895. if (!this._vertexBuffers && this._delayInfo) {
  30896. for (kind in this._delayInfo) {
  30897. result.push(kind);
  30898. }
  30899. }
  30900. else {
  30901. for (kind in this._vertexBuffers) {
  30902. result.push(kind);
  30903. }
  30904. }
  30905. return result;
  30906. };
  30907. Geometry.prototype.setIndices = function (indices, totalVertices) {
  30908. if (this._indexBuffer) {
  30909. this._engine._releaseBuffer(this._indexBuffer);
  30910. }
  30911. this._indices = indices;
  30912. if (this._meshes.length !== 0 && this._indices) {
  30913. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30914. }
  30915. if (totalVertices !== undefined) {
  30916. this._totalVertices = totalVertices;
  30917. }
  30918. var meshes = this._meshes;
  30919. var numOfMeshes = meshes.length;
  30920. for (var index = 0; index < numOfMeshes; index++) {
  30921. meshes[index]._createGlobalSubMesh();
  30922. }
  30923. this.notifyUpdate();
  30924. };
  30925. Geometry.prototype.getTotalIndices = function () {
  30926. if (!this.isReady()) {
  30927. return 0;
  30928. }
  30929. return this._indices.length;
  30930. };
  30931. Geometry.prototype.getIndices = function (copyWhenShared) {
  30932. if (!this.isReady()) {
  30933. return null;
  30934. }
  30935. var orig = this._indices;
  30936. if (!copyWhenShared || this._meshes.length === 1) {
  30937. return orig;
  30938. }
  30939. else {
  30940. var len = orig.length;
  30941. var copy = [];
  30942. for (var i = 0; i < len; i++) {
  30943. copy.push(orig[i]);
  30944. }
  30945. return copy;
  30946. }
  30947. };
  30948. Geometry.prototype.getIndexBuffer = function () {
  30949. if (!this.isReady()) {
  30950. return null;
  30951. }
  30952. return this._indexBuffer;
  30953. };
  30954. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30955. var meshes = this._meshes;
  30956. var index = meshes.indexOf(mesh);
  30957. if (index === -1) {
  30958. return;
  30959. }
  30960. for (var kind in this._vertexBuffers) {
  30961. this._vertexBuffers[kind].dispose();
  30962. }
  30963. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  30964. this._indexBuffer = null;
  30965. }
  30966. meshes.splice(index, 1);
  30967. mesh._geometry = null;
  30968. if (meshes.length === 0 && shouldDispose) {
  30969. this.dispose();
  30970. }
  30971. };
  30972. Geometry.prototype.applyToMesh = function (mesh) {
  30973. if (mesh._geometry === this) {
  30974. return;
  30975. }
  30976. var previousGeometry = mesh._geometry;
  30977. if (previousGeometry) {
  30978. previousGeometry.releaseForMesh(mesh);
  30979. }
  30980. var meshes = this._meshes;
  30981. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30982. mesh._geometry = this;
  30983. this._scene.pushGeometry(this);
  30984. meshes.push(mesh);
  30985. if (this.isReady()) {
  30986. this._applyToMesh(mesh);
  30987. }
  30988. else {
  30989. mesh._boundingInfo = this._boundingInfo;
  30990. }
  30991. };
  30992. Geometry.prototype.updateExtend = function (data) {
  30993. if (data === void 0) { data = null; }
  30994. if (!data) {
  30995. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30996. }
  30997. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  30998. };
  30999. Geometry.prototype._applyToMesh = function (mesh) {
  31000. var numOfMeshes = this._meshes.length;
  31001. // vertexBuffers
  31002. for (var kind in this._vertexBuffers) {
  31003. if (numOfMeshes === 1) {
  31004. this._vertexBuffers[kind].create();
  31005. }
  31006. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31007. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31008. mesh._resetPointsArrayCache();
  31009. if (!this._extend) {
  31010. this.updateExtend(this._vertexBuffers[kind].getData());
  31011. }
  31012. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31013. mesh._createGlobalSubMesh();
  31014. //bounding info was just created again, world matrix should be applied again.
  31015. mesh._updateBoundingInfo();
  31016. }
  31017. }
  31018. // indexBuffer
  31019. if (numOfMeshes === 1 && this._indices) {
  31020. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31021. }
  31022. if (this._indexBuffer) {
  31023. this._indexBuffer.references = numOfMeshes;
  31024. }
  31025. };
  31026. Geometry.prototype.notifyUpdate = function (kind) {
  31027. if (this.onGeometryUpdated) {
  31028. this.onGeometryUpdated(this, kind);
  31029. }
  31030. };
  31031. Geometry.prototype.load = function (scene, onLoaded) {
  31032. var _this = this;
  31033. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31034. return;
  31035. }
  31036. if (this.isReady()) {
  31037. if (onLoaded) {
  31038. onLoaded();
  31039. }
  31040. return;
  31041. }
  31042. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31043. scene._addPendingData(this);
  31044. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31045. _this._delayLoadingFunction(JSON.parse(data), _this);
  31046. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31047. _this._delayInfo = [];
  31048. scene._removePendingData(_this);
  31049. var meshes = _this._meshes;
  31050. var numOfMeshes = meshes.length;
  31051. for (var index = 0; index < numOfMeshes; index++) {
  31052. _this._applyToMesh(meshes[index]);
  31053. }
  31054. if (onLoaded) {
  31055. onLoaded();
  31056. }
  31057. }, function () { }, scene.database);
  31058. };
  31059. Geometry.prototype.isDisposed = function () {
  31060. return this._isDisposed;
  31061. };
  31062. Geometry.prototype.dispose = function () {
  31063. var meshes = this._meshes;
  31064. var numOfMeshes = meshes.length;
  31065. var index;
  31066. for (index = 0; index < numOfMeshes; index++) {
  31067. this.releaseForMesh(meshes[index]);
  31068. }
  31069. this._meshes = [];
  31070. for (var kind in this._vertexBuffers) {
  31071. this._vertexBuffers[kind].dispose();
  31072. }
  31073. this._vertexBuffers = [];
  31074. this._totalVertices = 0;
  31075. if (this._indexBuffer) {
  31076. this._engine._releaseBuffer(this._indexBuffer);
  31077. }
  31078. this._indexBuffer = null;
  31079. this._indices = [];
  31080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31081. this.delayLoadingFile = null;
  31082. this._delayLoadingFunction = null;
  31083. this._delayInfo = [];
  31084. this._boundingInfo = null;
  31085. this._scene.removeGeometry(this);
  31086. this._isDisposed = true;
  31087. };
  31088. Geometry.prototype.copy = function (id) {
  31089. var vertexData = new BABYLON.VertexData();
  31090. vertexData.indices = [];
  31091. var indices = this.getIndices();
  31092. for (var index = 0; index < indices.length; index++) {
  31093. vertexData.indices.push(indices[index]);
  31094. }
  31095. var updatable = false;
  31096. var stopChecking = false;
  31097. var kind;
  31098. for (kind in this._vertexBuffers) {
  31099. // using slice() to make a copy of the array and not just reference it
  31100. var data = this.getVerticesData(kind);
  31101. if (data instanceof Float32Array) {
  31102. vertexData.set(new Float32Array(data), kind);
  31103. }
  31104. else {
  31105. vertexData.set(data.slice(0), kind);
  31106. }
  31107. if (!stopChecking) {
  31108. updatable = this.getVertexBuffer(kind).isUpdatable();
  31109. stopChecking = !updatable;
  31110. }
  31111. }
  31112. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31113. geometry.delayLoadState = this.delayLoadState;
  31114. geometry.delayLoadingFile = this.delayLoadingFile;
  31115. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31116. for (kind in this._delayInfo) {
  31117. geometry._delayInfo = geometry._delayInfo || [];
  31118. geometry._delayInfo.push(kind);
  31119. }
  31120. // Bounding info
  31121. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31122. return geometry;
  31123. };
  31124. Geometry.prototype.serialize = function () {
  31125. var serializationObject = {};
  31126. serializationObject.id = this.id;
  31127. if (BABYLON.Tags.HasTags(this)) {
  31128. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31129. }
  31130. return serializationObject;
  31131. };
  31132. Geometry.prototype.serializeVerticeData = function () {
  31133. var serializationObject = this.serialize();
  31134. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31135. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31136. }
  31137. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31138. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31139. }
  31140. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31141. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31142. }
  31143. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31144. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31145. }
  31146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31147. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31148. }
  31149. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31150. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31151. }
  31152. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31153. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31154. }
  31155. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31156. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31157. }
  31158. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31159. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31160. }
  31161. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31162. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31163. serializationObject.matricesIndices._isExpanded = true;
  31164. }
  31165. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31166. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31167. }
  31168. serializationObject.indices = this.getIndices();
  31169. return serializationObject;
  31170. };
  31171. // Statics
  31172. Geometry.ExtractFromMesh = function (mesh, id) {
  31173. var geometry = mesh._geometry;
  31174. if (!geometry) {
  31175. return null;
  31176. }
  31177. return geometry.copy(id);
  31178. };
  31179. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31180. // be aware Math.random() could cause collisions
  31181. Geometry.RandomId = function () {
  31182. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31183. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31184. return v.toString(16);
  31185. });
  31186. };
  31187. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31188. var scene = mesh.getScene();
  31189. // Geometry
  31190. var geometryId = parsedGeometry.geometryId;
  31191. if (geometryId) {
  31192. var geometry = scene.getGeometryByID(geometryId);
  31193. if (geometry) {
  31194. geometry.applyToMesh(mesh);
  31195. }
  31196. }
  31197. else if (parsedGeometry instanceof ArrayBuffer) {
  31198. var binaryInfo = mesh._binaryInfo;
  31199. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31200. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31201. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31202. }
  31203. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31204. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31205. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31206. }
  31207. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31208. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31209. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31210. }
  31211. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31212. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31213. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31214. }
  31215. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31216. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31217. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31218. }
  31219. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31220. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31221. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31222. }
  31223. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31224. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31225. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31226. }
  31227. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31228. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31229. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31230. }
  31231. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31232. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31233. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31234. }
  31235. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31236. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31237. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31238. }
  31239. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31240. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31241. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31242. }
  31243. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31244. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31245. mesh.setIndices(indicesData);
  31246. }
  31247. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31248. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31249. mesh.subMeshes = [];
  31250. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31251. var materialIndex = subMeshesData[(i * 5) + 0];
  31252. var verticesStart = subMeshesData[(i * 5) + 1];
  31253. var verticesCount = subMeshesData[(i * 5) + 2];
  31254. var indexStart = subMeshesData[(i * 5) + 3];
  31255. var indexCount = subMeshesData[(i * 5) + 4];
  31256. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31257. }
  31258. }
  31259. }
  31260. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31261. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31262. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31263. if (parsedGeometry.uvs) {
  31264. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31265. }
  31266. if (parsedGeometry.uvs2) {
  31267. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31268. }
  31269. if (parsedGeometry.uvs3) {
  31270. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31271. }
  31272. if (parsedGeometry.uvs4) {
  31273. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31274. }
  31275. if (parsedGeometry.uvs5) {
  31276. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31277. }
  31278. if (parsedGeometry.uvs6) {
  31279. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31280. }
  31281. if (parsedGeometry.colors) {
  31282. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31283. }
  31284. if (parsedGeometry.matricesIndices) {
  31285. if (!parsedGeometry.matricesIndices._isExpanded) {
  31286. var floatIndices = [];
  31287. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31288. var matricesIndex = parsedGeometry.matricesIndices[i];
  31289. floatIndices.push(matricesIndex & 0x000000FF);
  31290. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31291. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31292. floatIndices.push(matricesIndex >> 24);
  31293. }
  31294. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31295. }
  31296. else {
  31297. delete parsedGeometry.matricesIndices._isExpanded;
  31298. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31299. }
  31300. }
  31301. if (parsedGeometry.matricesIndicesExtra) {
  31302. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31303. var floatIndices = [];
  31304. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31305. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31306. floatIndices.push(matricesIndex & 0x000000FF);
  31307. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31308. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31309. floatIndices.push(matricesIndex >> 24);
  31310. }
  31311. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  31312. }
  31313. else {
  31314. delete parsedGeometry.matricesIndices._isExpanded;
  31315. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  31316. }
  31317. }
  31318. if (parsedGeometry.matricesWeights) {
  31319. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  31320. }
  31321. if (parsedGeometry.matricesWeightsExtra) {
  31322. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  31323. }
  31324. mesh.setIndices(parsedGeometry.indices);
  31325. }
  31326. // SubMeshes
  31327. if (parsedGeometry.subMeshes) {
  31328. mesh.subMeshes = [];
  31329. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31330. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31331. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31332. }
  31333. }
  31334. // Flat shading
  31335. if (mesh._shouldGenerateFlatShading) {
  31336. mesh.convertToFlatShadedMesh();
  31337. delete mesh._shouldGenerateFlatShading;
  31338. }
  31339. // Update
  31340. mesh.computeWorldMatrix(true);
  31341. // Octree
  31342. if (scene['_selectionOctree']) {
  31343. scene['_selectionOctree'].addMesh(mesh);
  31344. }
  31345. };
  31346. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31347. if (scene.getGeometryByID(parsedVertexData.id)) {
  31348. return null; // null since geometry could be something else than a box...
  31349. }
  31350. var geometry = new Geometry(parsedVertexData.id, scene);
  31351. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31352. if (parsedVertexData.delayLoadingFile) {
  31353. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31354. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31355. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31356. geometry._delayInfo = [];
  31357. if (parsedVertexData.hasUVs) {
  31358. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31359. }
  31360. if (parsedVertexData.hasUVs2) {
  31361. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31362. }
  31363. if (parsedVertexData.hasUVs3) {
  31364. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31365. }
  31366. if (parsedVertexData.hasUVs4) {
  31367. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31368. }
  31369. if (parsedVertexData.hasUVs5) {
  31370. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31371. }
  31372. if (parsedVertexData.hasUVs6) {
  31373. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31374. }
  31375. if (parsedVertexData.hasColors) {
  31376. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31377. }
  31378. if (parsedVertexData.hasMatricesIndices) {
  31379. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31380. }
  31381. if (parsedVertexData.hasMatricesWeights) {
  31382. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31383. }
  31384. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31385. }
  31386. else {
  31387. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31388. }
  31389. scene.pushGeometry(geometry, true);
  31390. return geometry;
  31391. };
  31392. return Geometry;
  31393. }());
  31394. BABYLON.Geometry = Geometry;
  31395. /////// Primitives //////////////////////////////////////////////
  31396. var Geometry;
  31397. (function (Geometry) {
  31398. var Primitives;
  31399. (function (Primitives) {
  31400. /// Abstract class
  31401. var _Primitive = (function (_super) {
  31402. __extends(_Primitive, _super);
  31403. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31404. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  31405. this._canBeRegenerated = _canBeRegenerated;
  31406. this._beingRegenerated = true;
  31407. this.regenerate();
  31408. this._beingRegenerated = false;
  31409. }
  31410. _Primitive.prototype.canBeRegenerated = function () {
  31411. return this._canBeRegenerated;
  31412. };
  31413. _Primitive.prototype.regenerate = function () {
  31414. if (!this._canBeRegenerated) {
  31415. return;
  31416. }
  31417. this._beingRegenerated = true;
  31418. this.setAllVerticesData(this._regenerateVertexData(), false);
  31419. this._beingRegenerated = false;
  31420. };
  31421. _Primitive.prototype.asNewGeometry = function (id) {
  31422. return _super.prototype.copy.call(this, id);
  31423. };
  31424. // overrides
  31425. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31426. if (!this._beingRegenerated) {
  31427. return;
  31428. }
  31429. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31430. };
  31431. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31432. if (!this._beingRegenerated) {
  31433. return;
  31434. }
  31435. _super.prototype.setVerticesData.call(this, kind, data, false);
  31436. };
  31437. // to override
  31438. // protected
  31439. _Primitive.prototype._regenerateVertexData = function () {
  31440. throw new Error("Abstract method");
  31441. };
  31442. _Primitive.prototype.copy = function (id) {
  31443. throw new Error("Must be overriden in sub-classes.");
  31444. };
  31445. _Primitive.prototype.serialize = function () {
  31446. var serializationObject = _super.prototype.serialize.call(this);
  31447. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31448. return serializationObject;
  31449. };
  31450. return _Primitive;
  31451. }(Geometry));
  31452. Primitives._Primitive = _Primitive;
  31453. var Ribbon = (function (_super) {
  31454. __extends(Ribbon, _super);
  31455. // Members
  31456. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31458. _super.call(this, id, scene, canBeRegenerated, mesh);
  31459. this.pathArray = pathArray;
  31460. this.closeArray = closeArray;
  31461. this.closePath = closePath;
  31462. this.offset = offset;
  31463. this.side = side;
  31464. }
  31465. Ribbon.prototype._regenerateVertexData = function () {
  31466. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31467. };
  31468. Ribbon.prototype.copy = function (id) {
  31469. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  31470. };
  31471. return Ribbon;
  31472. }(_Primitive));
  31473. Primitives.Ribbon = Ribbon;
  31474. var Box = (function (_super) {
  31475. __extends(Box, _super);
  31476. // Members
  31477. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31478. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31479. _super.call(this, id, scene, canBeRegenerated, mesh);
  31480. this.size = size;
  31481. this.side = side;
  31482. }
  31483. Box.prototype._regenerateVertexData = function () {
  31484. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31485. };
  31486. Box.prototype.copy = function (id) {
  31487. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31488. };
  31489. Box.prototype.serialize = function () {
  31490. var serializationObject = _super.prototype.serialize.call(this);
  31491. serializationObject.size = this.size;
  31492. return serializationObject;
  31493. };
  31494. Box.Parse = function (parsedBox, scene) {
  31495. if (scene.getGeometryByID(parsedBox.id)) {
  31496. return null; // null since geometry could be something else than a box...
  31497. }
  31498. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31499. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31500. scene.pushGeometry(box, true);
  31501. return box;
  31502. };
  31503. return Box;
  31504. }(_Primitive));
  31505. Primitives.Box = Box;
  31506. var Sphere = (function (_super) {
  31507. __extends(Sphere, _super);
  31508. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31509. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31510. _super.call(this, id, scene, canBeRegenerated, mesh);
  31511. this.segments = segments;
  31512. this.diameter = diameter;
  31513. this.side = side;
  31514. }
  31515. Sphere.prototype._regenerateVertexData = function () {
  31516. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31517. };
  31518. Sphere.prototype.copy = function (id) {
  31519. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31520. };
  31521. Sphere.prototype.serialize = function () {
  31522. var serializationObject = _super.prototype.serialize.call(this);
  31523. serializationObject.segments = this.segments;
  31524. serializationObject.diameter = this.diameter;
  31525. return serializationObject;
  31526. };
  31527. Sphere.Parse = function (parsedSphere, scene) {
  31528. if (scene.getGeometryByID(parsedSphere.id)) {
  31529. return null; // null since geometry could be something else than a sphere...
  31530. }
  31531. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31532. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31533. scene.pushGeometry(sphere, true);
  31534. return sphere;
  31535. };
  31536. return Sphere;
  31537. }(_Primitive));
  31538. Primitives.Sphere = Sphere;
  31539. var Disc = (function (_super) {
  31540. __extends(Disc, _super);
  31541. // Members
  31542. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31543. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31544. _super.call(this, id, scene, canBeRegenerated, mesh);
  31545. this.radius = radius;
  31546. this.tessellation = tessellation;
  31547. this.side = side;
  31548. }
  31549. Disc.prototype._regenerateVertexData = function () {
  31550. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31551. };
  31552. Disc.prototype.copy = function (id) {
  31553. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31554. };
  31555. return Disc;
  31556. }(_Primitive));
  31557. Primitives.Disc = Disc;
  31558. var Cylinder = (function (_super) {
  31559. __extends(Cylinder, _super);
  31560. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31561. if (subdivisions === void 0) { subdivisions = 1; }
  31562. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31563. _super.call(this, id, scene, canBeRegenerated, mesh);
  31564. this.height = height;
  31565. this.diameterTop = diameterTop;
  31566. this.diameterBottom = diameterBottom;
  31567. this.tessellation = tessellation;
  31568. this.subdivisions = subdivisions;
  31569. this.side = side;
  31570. }
  31571. Cylinder.prototype._regenerateVertexData = function () {
  31572. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31573. };
  31574. Cylinder.prototype.copy = function (id) {
  31575. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31576. };
  31577. Cylinder.prototype.serialize = function () {
  31578. var serializationObject = _super.prototype.serialize.call(this);
  31579. serializationObject.height = this.height;
  31580. serializationObject.diameterTop = this.diameterTop;
  31581. serializationObject.diameterBottom = this.diameterBottom;
  31582. serializationObject.tessellation = this.tessellation;
  31583. return serializationObject;
  31584. };
  31585. Cylinder.Parse = function (parsedCylinder, scene) {
  31586. if (scene.getGeometryByID(parsedCylinder.id)) {
  31587. return null; // null since geometry could be something else than a cylinder...
  31588. }
  31589. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31590. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31591. scene.pushGeometry(cylinder, true);
  31592. return cylinder;
  31593. };
  31594. return Cylinder;
  31595. }(_Primitive));
  31596. Primitives.Cylinder = Cylinder;
  31597. var Torus = (function (_super) {
  31598. __extends(Torus, _super);
  31599. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31600. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31601. _super.call(this, id, scene, canBeRegenerated, mesh);
  31602. this.diameter = diameter;
  31603. this.thickness = thickness;
  31604. this.tessellation = tessellation;
  31605. this.side = side;
  31606. }
  31607. Torus.prototype._regenerateVertexData = function () {
  31608. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31609. };
  31610. Torus.prototype.copy = function (id) {
  31611. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31612. };
  31613. Torus.prototype.serialize = function () {
  31614. var serializationObject = _super.prototype.serialize.call(this);
  31615. serializationObject.diameter = this.diameter;
  31616. serializationObject.thickness = this.thickness;
  31617. serializationObject.tessellation = this.tessellation;
  31618. return serializationObject;
  31619. };
  31620. Torus.Parse = function (parsedTorus, scene) {
  31621. if (scene.getGeometryByID(parsedTorus.id)) {
  31622. return null; // null since geometry could be something else than a torus...
  31623. }
  31624. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31625. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31626. scene.pushGeometry(torus, true);
  31627. return torus;
  31628. };
  31629. return Torus;
  31630. }(_Primitive));
  31631. Primitives.Torus = Torus;
  31632. var Ground = (function (_super) {
  31633. __extends(Ground, _super);
  31634. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31635. _super.call(this, id, scene, canBeRegenerated, mesh);
  31636. this.width = width;
  31637. this.height = height;
  31638. this.subdivisions = subdivisions;
  31639. }
  31640. Ground.prototype._regenerateVertexData = function () {
  31641. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31642. };
  31643. Ground.prototype.copy = function (id) {
  31644. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31645. };
  31646. Ground.prototype.serialize = function () {
  31647. var serializationObject = _super.prototype.serialize.call(this);
  31648. serializationObject.width = this.width;
  31649. serializationObject.height = this.height;
  31650. serializationObject.subdivisions = this.subdivisions;
  31651. return serializationObject;
  31652. };
  31653. Ground.Parse = function (parsedGround, scene) {
  31654. if (scene.getGeometryByID(parsedGround.id)) {
  31655. return null; // null since geometry could be something else than a ground...
  31656. }
  31657. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31658. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31659. scene.pushGeometry(ground, true);
  31660. return ground;
  31661. };
  31662. return Ground;
  31663. }(_Primitive));
  31664. Primitives.Ground = Ground;
  31665. var TiledGround = (function (_super) {
  31666. __extends(TiledGround, _super);
  31667. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31668. _super.call(this, id, scene, canBeRegenerated, mesh);
  31669. this.xmin = xmin;
  31670. this.zmin = zmin;
  31671. this.xmax = xmax;
  31672. this.zmax = zmax;
  31673. this.subdivisions = subdivisions;
  31674. this.precision = precision;
  31675. }
  31676. TiledGround.prototype._regenerateVertexData = function () {
  31677. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31678. };
  31679. TiledGround.prototype.copy = function (id) {
  31680. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31681. };
  31682. return TiledGround;
  31683. }(_Primitive));
  31684. Primitives.TiledGround = TiledGround;
  31685. var Plane = (function (_super) {
  31686. __extends(Plane, _super);
  31687. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31688. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31689. _super.call(this, id, scene, canBeRegenerated, mesh);
  31690. this.size = size;
  31691. this.side = side;
  31692. }
  31693. Plane.prototype._regenerateVertexData = function () {
  31694. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31695. };
  31696. Plane.prototype.copy = function (id) {
  31697. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31698. };
  31699. Plane.prototype.serialize = function () {
  31700. var serializationObject = _super.prototype.serialize.call(this);
  31701. serializationObject.size = this.size;
  31702. return serializationObject;
  31703. };
  31704. Plane.Parse = function (parsedPlane, scene) {
  31705. if (scene.getGeometryByID(parsedPlane.id)) {
  31706. return null; // null since geometry could be something else than a ground...
  31707. }
  31708. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31709. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31710. scene.pushGeometry(plane, true);
  31711. return plane;
  31712. };
  31713. return Plane;
  31714. }(_Primitive));
  31715. Primitives.Plane = Plane;
  31716. var TorusKnot = (function (_super) {
  31717. __extends(TorusKnot, _super);
  31718. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31719. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31720. _super.call(this, id, scene, canBeRegenerated, mesh);
  31721. this.radius = radius;
  31722. this.tube = tube;
  31723. this.radialSegments = radialSegments;
  31724. this.tubularSegments = tubularSegments;
  31725. this.p = p;
  31726. this.q = q;
  31727. this.side = side;
  31728. }
  31729. TorusKnot.prototype._regenerateVertexData = function () {
  31730. 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 });
  31731. };
  31732. TorusKnot.prototype.copy = function (id) {
  31733. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31734. };
  31735. TorusKnot.prototype.serialize = function () {
  31736. var serializationObject = _super.prototype.serialize.call(this);
  31737. serializationObject.radius = this.radius;
  31738. serializationObject.tube = this.tube;
  31739. serializationObject.radialSegments = this.radialSegments;
  31740. serializationObject.tubularSegments = this.tubularSegments;
  31741. serializationObject.p = this.p;
  31742. serializationObject.q = this.q;
  31743. return serializationObject;
  31744. };
  31745. ;
  31746. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31747. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31748. return null; // null since geometry could be something else than a ground...
  31749. }
  31750. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31751. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31752. scene.pushGeometry(torusKnot, true);
  31753. return torusKnot;
  31754. };
  31755. return TorusKnot;
  31756. }(_Primitive));
  31757. Primitives.TorusKnot = TorusKnot;
  31758. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31759. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31760. })(BABYLON || (BABYLON = {}));
  31761. var BABYLON;
  31762. (function (BABYLON) {
  31763. var GroundMesh = (function (_super) {
  31764. __extends(GroundMesh, _super);
  31765. function GroundMesh(name, scene) {
  31766. _super.call(this, name, scene);
  31767. this.generateOctree = false;
  31768. this._worldInverse = new BABYLON.Matrix();
  31769. }
  31770. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  31771. get: function () {
  31772. return this._subdivisions;
  31773. },
  31774. enumerable: true,
  31775. configurable: true
  31776. });
  31777. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  31778. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  31779. this._subdivisions = chunksCount;
  31780. this.subdivide(this._subdivisions);
  31781. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  31782. };
  31783. /**
  31784. * Returns a height (y) value in the Worl system :
  31785. * the ground altitude at the coordinates (x, z) expressed in the World system.
  31786. * Returns the ground y position if (x, z) are outside the ground surface.
  31787. * Not pertinent if the ground is rotated.
  31788. */
  31789. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  31790. // express x and y in the ground local system
  31791. x -= this.position.x;
  31792. z -= this.position.z;
  31793. x /= this.scaling.x;
  31794. z /= this.scaling.z;
  31795. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31796. return this.position.y;
  31797. }
  31798. if (!this._heightQuads || this._heightQuads.length == 0) {
  31799. this._initHeightQuads();
  31800. this._computeHeightQuads();
  31801. }
  31802. var facet = this._getFacetAt(x, z);
  31803. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  31804. // return y in the World system
  31805. return y * this.scaling.y + this.position.y;
  31806. };
  31807. /**
  31808. * Returns a normalized vector (Vector3) orthogonal to the ground
  31809. * at the ground coordinates (x, z) expressed in the World system.
  31810. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  31811. * Not pertinent if the ground is rotated.
  31812. */
  31813. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  31814. var normal = new BABYLON.Vector3(0, 1, 0);
  31815. this.getNormalAtCoordinatesToRef(x, z, normal);
  31816. return normal;
  31817. };
  31818. /**
  31819. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  31820. * at the ground coordinates (x, z) expressed in the World system.
  31821. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  31822. * Not pertinent if the ground is rotated.
  31823. */
  31824. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  31825. // express x and y in the ground local system
  31826. x -= this.position.x;
  31827. z -= this.position.z;
  31828. x /= this.scaling.x;
  31829. z /= this.scaling.z;
  31830. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31831. return;
  31832. }
  31833. if (!this._heightQuads || this._heightQuads.length == 0) {
  31834. this._initHeightQuads();
  31835. this._computeHeightQuads();
  31836. }
  31837. var facet = this._getFacetAt(x, z);
  31838. ref.x = facet.x;
  31839. ref.y = facet.y;
  31840. ref.z = facet.z;
  31841. };
  31842. /**
  31843. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  31844. * if the ground has been updated.
  31845. * This can be used in the render loop
  31846. */
  31847. GroundMesh.prototype.updateCoordinateHeights = function () {
  31848. if (!this._heightQuads || this._heightQuads.length == 0) {
  31849. this._initHeightQuads();
  31850. }
  31851. this._computeHeightQuads();
  31852. };
  31853. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  31854. GroundMesh.prototype._getFacetAt = function (x, z) {
  31855. // retrieve col and row from x, z coordinates in the ground local system
  31856. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  31857. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  31858. var quad = this._heightQuads[row * this._subdivisions + col];
  31859. var facet;
  31860. if (z < quad.slope.x * x + quad.slope.y) {
  31861. facet = quad.facet1;
  31862. }
  31863. else {
  31864. facet = quad.facet2;
  31865. }
  31866. return facet;
  31867. };
  31868. // Creates and populates the heightMap array with "facet" elements :
  31869. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  31870. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31871. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31872. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31873. GroundMesh.prototype._initHeightQuads = function () {
  31874. this._heightQuads = new Array();
  31875. for (var row = 0; row < this._subdivisions; row++) {
  31876. for (var col = 0; col < this._subdivisions; col++) {
  31877. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  31878. this._heightQuads[row * this._subdivisions + col] = quad;
  31879. }
  31880. }
  31881. };
  31882. // Compute each quad element values and update the the heightMap array :
  31883. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31884. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31885. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31886. GroundMesh.prototype._computeHeightQuads = function () {
  31887. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31888. var v1 = BABYLON.Tmp.Vector3[0];
  31889. var v2 = BABYLON.Tmp.Vector3[1];
  31890. var v3 = BABYLON.Tmp.Vector3[2];
  31891. var v4 = BABYLON.Tmp.Vector3[3];
  31892. var v1v2 = BABYLON.Tmp.Vector3[4];
  31893. var v1v3 = BABYLON.Tmp.Vector3[5];
  31894. var v1v4 = BABYLON.Tmp.Vector3[6];
  31895. var norm1 = BABYLON.Tmp.Vector3[7];
  31896. var norm2 = BABYLON.Tmp.Vector3[8];
  31897. var i = 0;
  31898. var j = 0;
  31899. var k = 0;
  31900. var cd = 0; // 2D slope coefficient : z = cd * x + h
  31901. var h = 0;
  31902. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  31903. var d2 = 0;
  31904. for (var row = 0; row < this._subdivisions; row++) {
  31905. for (var col = 0; col < this._subdivisions; col++) {
  31906. i = col * 3;
  31907. j = row * (this._subdivisions + 1) * 3;
  31908. k = (row + 1) * (this._subdivisions + 1) * 3;
  31909. v1.x = positions[j + i];
  31910. v1.y = positions[j + i + 1];
  31911. v1.z = positions[j + i + 2];
  31912. v2.x = positions[j + i + 3];
  31913. v2.y = positions[j + i + 4];
  31914. v2.z = positions[j + i + 5];
  31915. v3.x = positions[k + i];
  31916. v3.y = positions[k + i + 1];
  31917. v3.z = positions[k + i + 2];
  31918. v4.x = positions[k + i + 3];
  31919. v4.y = positions[k + i + 4];
  31920. v4.z = positions[k + i + 5];
  31921. // 2D slope V1V4
  31922. cd = (v4.z - v1.z) / (v4.x - v1.x);
  31923. h = v1.z - cd * v1.x; // v1 belongs to the slope
  31924. // facet equations :
  31925. // we compute each facet normal vector
  31926. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  31927. // we compute the value d by applying the equation to v1 which belongs to the plane
  31928. // then we store the facet equation in a Vector4
  31929. v2.subtractToRef(v1, v1v2);
  31930. v3.subtractToRef(v1, v1v3);
  31931. v4.subtractToRef(v1, v1v4);
  31932. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  31933. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  31934. norm1.normalize();
  31935. norm2.normalize();
  31936. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  31937. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  31938. var quad = this._heightQuads[row * this._subdivisions + col];
  31939. quad.slope.copyFromFloats(cd, h);
  31940. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  31941. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  31942. }
  31943. }
  31944. };
  31945. return GroundMesh;
  31946. }(BABYLON.Mesh));
  31947. BABYLON.GroundMesh = GroundMesh;
  31948. })(BABYLON || (BABYLON = {}));
  31949. var BABYLON;
  31950. (function (BABYLON) {
  31951. var LinesMesh = (function (_super) {
  31952. __extends(LinesMesh, _super);
  31953. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  31954. if (parent === void 0) { parent = null; }
  31955. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  31956. this.color = new BABYLON.Color3(1, 1, 1);
  31957. this.alpha = 1;
  31958. this._intersectionThreshold = 0.1;
  31959. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  31960. attributes: ["position"],
  31961. uniforms: ["worldViewProjection", "color"],
  31962. needAlphaBlending: true
  31963. });
  31964. }
  31965. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  31966. /**
  31967. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  31968. * This margin is expressed in world space coordinates, so its value may vary.
  31969. * Default value is 0.1
  31970. * @returns the intersection Threshold value.
  31971. */
  31972. get: function () {
  31973. return this._intersectionThreshold;
  31974. },
  31975. /**
  31976. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  31977. * This margin is expressed in world space coordinates, so its value may vary.
  31978. * @param value the new threshold to apply
  31979. */
  31980. set: function (value) {
  31981. if (this._intersectionThreshold === value) {
  31982. return;
  31983. }
  31984. this._intersectionThreshold = value;
  31985. if (this.geometry) {
  31986. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  31987. }
  31988. },
  31989. enumerable: true,
  31990. configurable: true
  31991. });
  31992. Object.defineProperty(LinesMesh.prototype, "material", {
  31993. get: function () {
  31994. return this._colorShader;
  31995. },
  31996. enumerable: true,
  31997. configurable: true
  31998. });
  31999. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  32000. get: function () {
  32001. return true;
  32002. },
  32003. enumerable: true,
  32004. configurable: true
  32005. });
  32006. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32007. get: function () {
  32008. return false;
  32009. },
  32010. enumerable: true,
  32011. configurable: true
  32012. });
  32013. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32014. var engine = this.getScene().getEngine();
  32015. var indexToBind = this._geometry.getIndexBuffer();
  32016. // VBOs
  32017. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32018. // Color
  32019. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32020. };
  32021. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32022. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32023. return;
  32024. }
  32025. var engine = this.getScene().getEngine();
  32026. // Draw order
  32027. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32028. };
  32029. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32030. this._colorShader.dispose();
  32031. _super.prototype.dispose.call(this, doNotRecurse);
  32032. };
  32033. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32034. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32035. };
  32036. return LinesMesh;
  32037. }(BABYLON.Mesh));
  32038. BABYLON.LinesMesh = LinesMesh;
  32039. })(BABYLON || (BABYLON = {}));
  32040. var BABYLON;
  32041. (function (BABYLON) {
  32042. var DebugLayer = (function () {
  32043. function DebugLayer(scene) {
  32044. var _this = this;
  32045. this._transformationMatrix = BABYLON.Matrix.Identity();
  32046. this._enabled = false;
  32047. this._labelsEnabled = false;
  32048. this._displayStatistics = true;
  32049. this._displayTree = false;
  32050. this._displayLogs = false;
  32051. this._skeletonViewers = new Array();
  32052. this._identityMatrix = BABYLON.Matrix.Identity();
  32053. this.axisRatio = 0.02;
  32054. this.accentColor = "orange";
  32055. this._scene = scene;
  32056. this._syncPositions = function () {
  32057. var engine = _this._scene.getEngine();
  32058. var canvasRect = engine.getRenderingCanvasClientRect();
  32059. if (_this._showUI) {
  32060. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32061. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32062. _this._statsDiv.style.width = "400px";
  32063. _this._statsDiv.style.height = "auto";
  32064. _this._statsSubsetDiv.style.maxHeight = "240px";
  32065. _this._optionsDiv.style.left = "0px";
  32066. _this._optionsDiv.style.top = "10px";
  32067. _this._optionsDiv.style.width = "200px";
  32068. _this._optionsDiv.style.height = "auto";
  32069. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32070. _this._logDiv.style.left = "0px";
  32071. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32072. _this._logDiv.style.width = "600px";
  32073. _this._logDiv.style.height = "160px";
  32074. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32075. _this._treeDiv.style.top = "10px";
  32076. _this._treeDiv.style.width = "300px";
  32077. _this._treeDiv.style.height = "auto";
  32078. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32079. }
  32080. _this._globalDiv.style.left = canvasRect.left + "px";
  32081. _this._globalDiv.style.top = canvasRect.top + "px";
  32082. _this._drawingCanvas.style.left = "0px";
  32083. _this._drawingCanvas.style.top = "0px";
  32084. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32085. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32086. var devicePixelRatio = window.devicePixelRatio || 1;
  32087. var context = _this._drawingContext;
  32088. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32089. context.mozBackingStorePixelRatio ||
  32090. context.msBackingStorePixelRatio ||
  32091. context.oBackingStorePixelRatio ||
  32092. context.backingStorePixelRatio || 1;
  32093. _this._ratio = devicePixelRatio / backingStoreRatio;
  32094. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32095. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32096. };
  32097. this._onCanvasClick = function (evt) {
  32098. _this._clickPosition = {
  32099. x: evt.clientX * _this._ratio,
  32100. y: evt.clientY * _this._ratio
  32101. };
  32102. };
  32103. this._syncUI = function () {
  32104. if (_this._showUI) {
  32105. if (_this._displayStatistics) {
  32106. _this._displayStats();
  32107. _this._statsDiv.style.display = "";
  32108. }
  32109. else {
  32110. _this._statsDiv.style.display = "none";
  32111. }
  32112. if (_this._displayLogs) {
  32113. _this._logDiv.style.display = "";
  32114. }
  32115. else {
  32116. _this._logDiv.style.display = "none";
  32117. }
  32118. if (_this._displayTree) {
  32119. _this._treeDiv.style.display = "";
  32120. if (_this._needToRefreshMeshesTree) {
  32121. _this._needToRefreshMeshesTree = false;
  32122. _this._refreshMeshesTreeContent();
  32123. }
  32124. }
  32125. else {
  32126. _this._treeDiv.style.display = "none";
  32127. }
  32128. }
  32129. };
  32130. this._syncData = function () {
  32131. if (_this._labelsEnabled || !_this._showUI) {
  32132. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32133. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32134. var engine = _this._scene.getEngine();
  32135. var viewport = _this._camera.viewport;
  32136. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32137. // Meshes
  32138. var meshes = _this._camera.getActiveMeshes();
  32139. var index;
  32140. var projectedPosition;
  32141. for (index = 0; index < meshes.length; index++) {
  32142. var mesh = meshes.data[index];
  32143. var position = mesh.getBoundingInfo().boundingSphere.center;
  32144. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32145. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32146. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32147. }
  32148. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32149. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32150. }
  32151. }
  32152. // Cameras
  32153. var cameras = _this._scene.cameras;
  32154. for (index = 0; index < cameras.length; index++) {
  32155. var camera = cameras[index];
  32156. if (camera === _this._camera) {
  32157. continue;
  32158. }
  32159. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32160. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32161. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32162. _this._camera.detachControl(engine.getRenderingCanvas());
  32163. _this._camera = camera;
  32164. _this._camera.attachControl(engine.getRenderingCanvas());
  32165. }, function () { return "purple"; });
  32166. }
  32167. }
  32168. // Lights
  32169. var lights = _this._scene.lights;
  32170. for (index = 0; index < lights.length; index++) {
  32171. var light = lights[index];
  32172. if (light.position) {
  32173. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32174. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32175. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32176. light.setEnabled(!light.isEnabled());
  32177. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32178. }
  32179. }
  32180. }
  32181. }
  32182. _this._clickPosition = undefined;
  32183. };
  32184. }
  32185. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32186. while (this._treeSubsetDiv.hasChildNodes()) {
  32187. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32188. }
  32189. // Add meshes
  32190. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32191. sortedArray.sort(function (a, b) {
  32192. if (a.name === b.name) {
  32193. return 0;
  32194. }
  32195. return (a.name > b.name) ? 1 : -1;
  32196. });
  32197. for (var index = 0; index < sortedArray.length; index++) {
  32198. var mesh = sortedArray[index];
  32199. if (!mesh.isEnabled()) {
  32200. continue;
  32201. }
  32202. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32203. m.isVisible = element.checked;
  32204. }, mesh);
  32205. }
  32206. };
  32207. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32208. this._drawingContext.beginPath();
  32209. this._drawingContext.moveTo(zero.x, zero.y);
  32210. this._drawingContext.lineTo(unit.x, unit.y);
  32211. this._drawingContext.strokeStyle = color;
  32212. this._drawingContext.lineWidth = 4;
  32213. this._drawingContext.stroke();
  32214. this._drawingContext.font = "normal 14px Segoe UI";
  32215. this._drawingContext.fillStyle = color;
  32216. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32217. };
  32218. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32219. var position = mesh.getBoundingInfo().boundingSphere.center;
  32220. var worldMatrix = mesh.getWorldMatrix();
  32221. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32222. var unit = (unprojectedVector.subtract(position)).length();
  32223. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32224. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32225. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32226. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32227. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32228. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32229. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32230. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32231. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32232. };
  32233. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32234. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32235. this._drawingContext.font = "normal 12px Segoe UI";
  32236. var textMetrics = this._drawingContext.measureText(text);
  32237. var centerX = projectedPosition.x - textMetrics.width / 2;
  32238. var centerY = projectedPosition.y;
  32239. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32240. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32241. onClick();
  32242. }
  32243. this._drawingContext.beginPath();
  32244. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32245. this._drawingContext.fillStyle = getFillStyle();
  32246. this._drawingContext.globalAlpha = 0.5;
  32247. this._drawingContext.fill();
  32248. this._drawingContext.globalAlpha = 1.0;
  32249. this._drawingContext.strokeStyle = '#FFFFFF';
  32250. this._drawingContext.lineWidth = 1;
  32251. this._drawingContext.stroke();
  32252. this._drawingContext.fillStyle = "#FFFFFF";
  32253. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32254. this._drawingContext.beginPath();
  32255. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32256. this._drawingContext.fill();
  32257. }
  32258. };
  32259. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32260. if (!this._clickPosition) {
  32261. return false;
  32262. }
  32263. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32264. return false;
  32265. }
  32266. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32267. return false;
  32268. }
  32269. return true;
  32270. };
  32271. DebugLayer.prototype.isVisible = function () {
  32272. return this._enabled;
  32273. };
  32274. DebugLayer.prototype.hide = function () {
  32275. if (!this._enabled) {
  32276. return;
  32277. }
  32278. this._enabled = false;
  32279. var engine = this._scene.getEngine();
  32280. this._scene.unregisterBeforeRender(this._syncData);
  32281. this._scene.unregisterAfterRender(this._syncUI);
  32282. this._rootElement.removeChild(this._globalDiv);
  32283. this._scene.forceShowBoundingBoxes = false;
  32284. this._scene.forceWireframe = false;
  32285. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32286. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32287. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32288. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32289. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32290. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32291. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32292. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32293. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32294. this._scene.shadowsEnabled = true;
  32295. this._scene.particlesEnabled = true;
  32296. this._scene.postProcessesEnabled = true;
  32297. this._scene.collisionsEnabled = true;
  32298. this._scene.lightsEnabled = true;
  32299. this._scene.texturesEnabled = true;
  32300. this._scene.lensFlaresEnabled = true;
  32301. this._scene.proceduralTexturesEnabled = true;
  32302. this._scene.renderTargetsEnabled = true;
  32303. this._scene.probesEnabled = true;
  32304. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  32305. this._clearSkeletonViewers();
  32306. };
  32307. DebugLayer.prototype._clearSkeletonViewers = function () {
  32308. for (var index = 0; index < this._skeletonViewers.length; index++) {
  32309. this._skeletonViewers[index].dispose();
  32310. }
  32311. this._skeletonViewers = [];
  32312. };
  32313. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  32314. if (showUI === void 0) { showUI = true; }
  32315. if (camera === void 0) { camera = null; }
  32316. if (rootElement === void 0) { rootElement = null; }
  32317. if (this._enabled) {
  32318. return;
  32319. }
  32320. this._enabled = true;
  32321. if (camera) {
  32322. this._camera = camera;
  32323. }
  32324. else {
  32325. this._camera = this._scene.activeCamera;
  32326. }
  32327. this._showUI = showUI;
  32328. var engine = this._scene.getEngine();
  32329. this._globalDiv = document.createElement("div");
  32330. this._rootElement = rootElement || document.body;
  32331. this._rootElement.appendChild(this._globalDiv);
  32332. this._generateDOMelements();
  32333. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  32334. this._syncPositions();
  32335. this._scene.registerBeforeRender(this._syncData);
  32336. this._scene.registerAfterRender(this._syncUI);
  32337. };
  32338. DebugLayer.prototype._clearLabels = function () {
  32339. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  32340. for (var index = 0; index < this._scene.meshes.length; index++) {
  32341. var mesh = this._scene.meshes[index];
  32342. mesh.renderOverlay = false;
  32343. }
  32344. };
  32345. DebugLayer.prototype._generateheader = function (root, text) {
  32346. var header = document.createElement("div");
  32347. header.innerHTML = text + "&nbsp;";
  32348. header.style.textAlign = "right";
  32349. header.style.width = "100%";
  32350. header.style.color = "white";
  32351. header.style.backgroundColor = "Black";
  32352. header.style.padding = "5px 5px 4px 0px";
  32353. header.style.marginLeft = "-5px";
  32354. header.style.fontWeight = "bold";
  32355. root.appendChild(header);
  32356. };
  32357. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  32358. var label = document.createElement("label");
  32359. label.style.display = "inline";
  32360. label.innerHTML = title;
  32361. label.style.color = color;
  32362. root.appendChild(label);
  32363. root.appendChild(document.createElement("br"));
  32364. };
  32365. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  32366. if (tag === void 0) { tag = null; }
  32367. var label = document.createElement("label");
  32368. label.style.display = "inline";
  32369. var boundingBoxesCheckbox = document.createElement("input");
  32370. boundingBoxesCheckbox.type = "checkbox";
  32371. boundingBoxesCheckbox.checked = initialState;
  32372. boundingBoxesCheckbox.style.display = "inline";
  32373. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  32374. boundingBoxesCheckbox.style.verticalAlign = "sub";
  32375. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  32376. task(evt.target, tag);
  32377. });
  32378. label.appendChild(boundingBoxesCheckbox);
  32379. var container = document.createElement("span");
  32380. var leftPart = document.createElement("span");
  32381. var rightPart = document.createElement("span");
  32382. rightPart.style.cssFloat = "right";
  32383. leftPart.innerHTML = leftTitle;
  32384. rightPart.innerHTML = rightTitle;
  32385. rightPart.style.fontSize = "12px";
  32386. rightPart.style.maxWidth = "200px";
  32387. container.appendChild(leftPart);
  32388. container.appendChild(rightPart);
  32389. label.appendChild(container);
  32390. root.appendChild(label);
  32391. root.appendChild(document.createElement("br"));
  32392. };
  32393. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  32394. if (tag === void 0) { tag = null; }
  32395. var label = document.createElement("label");
  32396. label.style.display = "inline";
  32397. var checkBox = document.createElement("input");
  32398. checkBox.type = "checkbox";
  32399. checkBox.checked = initialState;
  32400. checkBox.style.display = "inline";
  32401. checkBox.style.margin = "0px 5px 0px 0px";
  32402. checkBox.style.verticalAlign = "sub";
  32403. checkBox.addEventListener("change", function (evt) {
  32404. task(evt.target, tag);
  32405. });
  32406. label.appendChild(checkBox);
  32407. label.appendChild(document.createTextNode(title));
  32408. root.appendChild(label);
  32409. root.appendChild(document.createElement("br"));
  32410. };
  32411. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  32412. if (tag === void 0) { tag = null; }
  32413. var button = document.createElement("button");
  32414. button.innerHTML = title;
  32415. button.style.height = "24px";
  32416. button.style.width = "150px";
  32417. button.style.marginBottom = "5px";
  32418. button.style.color = "#444444";
  32419. button.style.border = "1px solid white";
  32420. button.className = "debugLayerButton";
  32421. button.addEventListener("click", function (evt) {
  32422. task(evt.target, tag);
  32423. });
  32424. root.appendChild(button);
  32425. root.appendChild(document.createElement("br"));
  32426. };
  32427. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  32428. if (tag === void 0) { tag = null; }
  32429. var label = document.createElement("label");
  32430. label.style.display = "inline";
  32431. var boundingBoxesRadio = document.createElement("input");
  32432. boundingBoxesRadio.type = "radio";
  32433. boundingBoxesRadio.name = name;
  32434. boundingBoxesRadio.checked = initialState;
  32435. boundingBoxesRadio.style.display = "inline";
  32436. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  32437. boundingBoxesRadio.style.verticalAlign = "sub";
  32438. boundingBoxesRadio.addEventListener("change", function (evt) {
  32439. task(evt.target, tag);
  32440. });
  32441. label.appendChild(boundingBoxesRadio);
  32442. label.appendChild(document.createTextNode(title));
  32443. root.appendChild(label);
  32444. root.appendChild(document.createElement("br"));
  32445. };
  32446. DebugLayer.prototype._generateDOMelements = function () {
  32447. var _this = this;
  32448. this._globalDiv.id = "DebugLayer";
  32449. this._globalDiv.style.position = "absolute";
  32450. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  32451. this._globalDiv.style.fontSize = "14px";
  32452. this._globalDiv.style.color = "white";
  32453. // Drawing canvas
  32454. this._drawingCanvas = document.createElement("canvas");
  32455. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  32456. this._drawingCanvas.style.position = "absolute";
  32457. this._drawingCanvas.style.pointerEvents = "none";
  32458. this._drawingCanvas.style.backgroundColor = "transparent";
  32459. this._drawingContext = this._drawingCanvas.getContext("2d");
  32460. this._globalDiv.appendChild(this._drawingCanvas);
  32461. if (this._showUI) {
  32462. var background = "rgba(128, 128, 128, 0.4)";
  32463. var border = "rgb(180, 180, 180) solid 1px";
  32464. // Stats
  32465. this._statsDiv = document.createElement("div");
  32466. this._statsDiv.id = "DebugLayerStats";
  32467. this._statsDiv.style.border = border;
  32468. this._statsDiv.style.position = "absolute";
  32469. this._statsDiv.style.background = background;
  32470. this._statsDiv.style.padding = "0px 0px 0px 5px";
  32471. this._generateheader(this._statsDiv, "STATISTICS");
  32472. this._statsSubsetDiv = document.createElement("div");
  32473. this._statsSubsetDiv.style.paddingTop = "5px";
  32474. this._statsSubsetDiv.style.paddingBottom = "5px";
  32475. this._statsSubsetDiv.style.overflowY = "auto";
  32476. this._statsDiv.appendChild(this._statsSubsetDiv);
  32477. // Tree
  32478. this._treeDiv = document.createElement("div");
  32479. this._treeDiv.id = "DebugLayerTree";
  32480. this._treeDiv.style.border = border;
  32481. this._treeDiv.style.position = "absolute";
  32482. this._treeDiv.style.background = background;
  32483. this._treeDiv.style.padding = "0px 0px 0px 5px";
  32484. this._treeDiv.style.display = "none";
  32485. this._generateheader(this._treeDiv, "MESHES TREE");
  32486. this._treeSubsetDiv = document.createElement("div");
  32487. this._treeSubsetDiv.style.paddingTop = "5px";
  32488. this._treeSubsetDiv.style.paddingRight = "5px";
  32489. this._treeSubsetDiv.style.overflowY = "auto";
  32490. this._treeSubsetDiv.style.maxHeight = "300px";
  32491. this._treeDiv.appendChild(this._treeSubsetDiv);
  32492. this._needToRefreshMeshesTree = true;
  32493. // Logs
  32494. this._logDiv = document.createElement("div");
  32495. this._logDiv.style.border = border;
  32496. this._logDiv.id = "DebugLayerLogs";
  32497. this._logDiv.style.position = "absolute";
  32498. this._logDiv.style.background = background;
  32499. this._logDiv.style.padding = "0px 0px 0px 5px";
  32500. this._logDiv.style.display = "none";
  32501. this._generateheader(this._logDiv, "LOGS");
  32502. this._logSubsetDiv = document.createElement("div");
  32503. this._logSubsetDiv.style.height = "127px";
  32504. this._logSubsetDiv.style.paddingTop = "5px";
  32505. this._logSubsetDiv.style.overflowY = "auto";
  32506. this._logSubsetDiv.style.fontSize = "12px";
  32507. this._logSubsetDiv.style.fontFamily = "consolas";
  32508. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  32509. this._logDiv.appendChild(this._logSubsetDiv);
  32510. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  32511. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  32512. };
  32513. // Options
  32514. this._optionsDiv = document.createElement("div");
  32515. this._optionsDiv.id = "DebugLayerOptions";
  32516. this._optionsDiv.style.border = border;
  32517. this._optionsDiv.style.position = "absolute";
  32518. this._optionsDiv.style.background = background;
  32519. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  32520. this._optionsDiv.style.overflowY = "auto";
  32521. this._generateheader(this._optionsDiv, "OPTIONS");
  32522. this._optionsSubsetDiv = document.createElement("div");
  32523. this._optionsSubsetDiv.style.paddingTop = "5px";
  32524. this._optionsSubsetDiv.style.paddingBottom = "5px";
  32525. this._optionsSubsetDiv.style.overflowY = "auto";
  32526. this._optionsSubsetDiv.style.maxHeight = "200px";
  32527. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  32528. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  32529. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  32530. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  32531. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  32532. _this._displayTree = element.checked;
  32533. _this._needToRefreshMeshesTree = true;
  32534. });
  32535. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32536. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  32537. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  32538. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  32539. _this._labelsEnabled = element.checked;
  32540. if (!_this._labelsEnabled) {
  32541. _this._clearLabels();
  32542. }
  32543. });
  32544. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  32545. if (element.checked) {
  32546. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  32547. }
  32548. else {
  32549. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  32550. }
  32551. });
  32552. ;
  32553. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32554. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  32555. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  32556. if (element.checked) {
  32557. _this._scene.forceWireframe = false;
  32558. _this._scene.forcePointsCloud = false;
  32559. }
  32560. });
  32561. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  32562. if (element.checked) {
  32563. _this._scene.forceWireframe = true;
  32564. _this._scene.forcePointsCloud = false;
  32565. }
  32566. });
  32567. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  32568. if (element.checked) {
  32569. _this._scene.forceWireframe = false;
  32570. _this._scene.forcePointsCloud = true;
  32571. }
  32572. });
  32573. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32574. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  32575. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  32576. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  32577. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  32578. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  32579. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  32580. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  32581. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  32582. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  32583. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  32584. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  32585. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32586. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  32587. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  32588. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  32589. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  32590. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  32591. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  32592. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  32593. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  32594. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  32595. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  32596. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  32597. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  32598. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  32599. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  32600. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  32601. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  32602. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32603. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  32604. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  32605. if (element.checked) {
  32606. _this._scene.headphone = true;
  32607. }
  32608. });
  32609. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  32610. if (element.checked) {
  32611. _this._scene.headphone = false;
  32612. }
  32613. });
  32614. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  32615. _this._scene.audioEnabled = !element.checked;
  32616. });
  32617. }
  32618. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32619. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  32620. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  32621. if (!element.checked) {
  32622. _this._clearSkeletonViewers();
  32623. return;
  32624. }
  32625. for (var index = 0; index < _this._scene.meshes.length; index++) {
  32626. var mesh = _this._scene.meshes[index];
  32627. if (mesh.skeleton) {
  32628. var found = false;
  32629. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  32630. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  32631. found = true;
  32632. break;
  32633. }
  32634. }
  32635. if (found) {
  32636. continue;
  32637. }
  32638. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  32639. viewer.isEnabled = true;
  32640. _this._skeletonViewers.push(viewer);
  32641. }
  32642. }
  32643. });
  32644. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32645. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  32646. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  32647. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  32648. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  32649. if (_this._camera) {
  32650. console.log(_this._camera);
  32651. }
  32652. else {
  32653. console.warn("No camera defined, or debug layer created before camera creation!");
  32654. }
  32655. });
  32656. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32657. this._globalDiv.appendChild(this._statsDiv);
  32658. this._globalDiv.appendChild(this._logDiv);
  32659. this._globalDiv.appendChild(this._optionsDiv);
  32660. this._globalDiv.appendChild(this._treeDiv);
  32661. }
  32662. };
  32663. DebugLayer.prototype._displayStats = function () {
  32664. var scene = this._scene;
  32665. var engine = scene.getEngine();
  32666. var glInfo = engine.getGlInfo();
  32667. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  32668. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32669. + "<b>Count</b><br>"
  32670. + "Total meshes: " + scene.meshes.length + "<br>"
  32671. + "Total lights: " + scene.lights.length + "<br>"
  32672. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  32673. + "Total materials: " + scene.materials.length + "<br>"
  32674. + "Total textures: " + scene.textures.length + "<br>"
  32675. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  32676. + "Active indices: " + scene.getActiveIndices() + "<br>"
  32677. + "Active bones: " + scene.getActiveBones() + "<br>"
  32678. + "Active particles: " + scene.getActiveParticles() + "<br>"
  32679. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  32680. + "<b>Duration</b><br>"
  32681. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  32682. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  32683. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  32684. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  32685. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  32686. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  32687. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  32688. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  32689. + "</div>"
  32690. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32691. + "<b>Extensions</b><br>"
  32692. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  32693. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  32694. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  32695. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  32696. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  32697. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  32698. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  32699. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  32700. + "</div><br>"
  32701. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32702. + "<b>Caps.</b><br>"
  32703. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  32704. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  32705. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  32706. + "<b>Info</b><br>"
  32707. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  32708. + glInfo.version + "<br>"
  32709. + "</div><br>"
  32710. + glInfo.renderer + "<br>";
  32711. if (this.customStatsFunction) {
  32712. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  32713. }
  32714. };
  32715. return DebugLayer;
  32716. }());
  32717. BABYLON.DebugLayer = DebugLayer;
  32718. })(BABYLON || (BABYLON = {}));
  32719. var BABYLON;
  32720. (function (BABYLON) {
  32721. var DefaultLoadingScreen = (function () {
  32722. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  32723. var _this = this;
  32724. if (_loadingText === void 0) { _loadingText = ""; }
  32725. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  32726. this._renderingCanvas = _renderingCanvas;
  32727. this._loadingText = _loadingText;
  32728. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  32729. // Resize
  32730. this._resizeLoadingUI = function () {
  32731. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  32732. _this._loadingDiv.style.position = "absolute";
  32733. _this._loadingDiv.style.left = canvasRect.left + "px";
  32734. _this._loadingDiv.style.top = canvasRect.top + "px";
  32735. _this._loadingDiv.style.width = canvasRect.width + "px";
  32736. _this._loadingDiv.style.height = canvasRect.height + "px";
  32737. };
  32738. }
  32739. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  32740. var _this = this;
  32741. if (this._loadingDiv) {
  32742. // Do not add a loading screen if there is already one
  32743. return;
  32744. }
  32745. this._loadingDiv = document.createElement("div");
  32746. this._loadingDiv.id = "babylonjsLoadingDiv";
  32747. this._loadingDiv.style.opacity = "0";
  32748. this._loadingDiv.style.transition = "opacity 1.5s ease";
  32749. // Loading text
  32750. this._loadingTextDiv = document.createElement("div");
  32751. this._loadingTextDiv.style.position = "absolute";
  32752. this._loadingTextDiv.style.left = "0";
  32753. this._loadingTextDiv.style.top = "50%";
  32754. this._loadingTextDiv.style.marginTop = "80px";
  32755. this._loadingTextDiv.style.width = "100%";
  32756. this._loadingTextDiv.style.height = "20px";
  32757. this._loadingTextDiv.style.fontFamily = "Arial";
  32758. this._loadingTextDiv.style.fontSize = "14px";
  32759. this._loadingTextDiv.style.color = "white";
  32760. this._loadingTextDiv.style.textAlign = "center";
  32761. this._loadingTextDiv.innerHTML = "Loading";
  32762. this._loadingDiv.appendChild(this._loadingTextDiv);
  32763. //set the predefined text
  32764. this._loadingTextDiv.innerHTML = this._loadingText;
  32765. // Loading img
  32766. var imgBack = new Image();
  32767. 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==";
  32768. imgBack.style.position = "absolute";
  32769. imgBack.style.left = "50%";
  32770. imgBack.style.top = "50%";
  32771. imgBack.style.marginLeft = "-50px";
  32772. imgBack.style.marginTop = "-50px";
  32773. imgBack.style.transition = "transform 1.0s ease";
  32774. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  32775. var deg = 360;
  32776. var onTransitionEnd = function () {
  32777. deg += 360;
  32778. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  32779. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  32780. };
  32781. imgBack.addEventListener("transitionend", onTransitionEnd);
  32782. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  32783. this._loadingDiv.appendChild(imgBack);
  32784. // front image
  32785. var imgFront = new Image();
  32786. 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=";
  32787. imgFront.style.position = "absolute";
  32788. imgFront.style.left = "50%";
  32789. imgFront.style.top = "50%";
  32790. imgFront.style.marginLeft = "-50px";
  32791. imgFront.style.marginTop = "-50px";
  32792. this._loadingDiv.appendChild(imgFront);
  32793. this._resizeLoadingUI();
  32794. window.addEventListener("resize", this._resizeLoadingUI);
  32795. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32796. document.body.appendChild(this._loadingDiv);
  32797. setTimeout(function () {
  32798. _this._loadingDiv.style.opacity = "1";
  32799. imgBack.style.transform = "rotateZ(360deg)";
  32800. imgBack.style.webkitTransform = "rotateZ(360deg)";
  32801. }, 0);
  32802. };
  32803. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  32804. var _this = this;
  32805. if (!this._loadingDiv) {
  32806. return;
  32807. }
  32808. var onTransitionEnd = function () {
  32809. if (!_this._loadingDiv) {
  32810. return;
  32811. }
  32812. document.body.removeChild(_this._loadingDiv);
  32813. window.removeEventListener("resize", _this._resizeLoadingUI);
  32814. _this._loadingDiv = null;
  32815. };
  32816. this._loadingDiv.style.opacity = "0";
  32817. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  32818. };
  32819. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  32820. set: function (text) {
  32821. this._loadingText = text;
  32822. if (this._loadingTextDiv) {
  32823. this._loadingTextDiv.innerHTML = this._loadingText;
  32824. }
  32825. },
  32826. enumerable: true,
  32827. configurable: true
  32828. });
  32829. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  32830. get: function () {
  32831. return this._loadingDivBackgroundColor;
  32832. },
  32833. set: function (color) {
  32834. this._loadingDivBackgroundColor = color;
  32835. if (!this._loadingDiv) {
  32836. return;
  32837. }
  32838. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32839. },
  32840. enumerable: true,
  32841. configurable: true
  32842. });
  32843. return DefaultLoadingScreen;
  32844. }());
  32845. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  32846. })(BABYLON || (BABYLON = {}));
  32847. var BABYLON;
  32848. (function (BABYLON) {
  32849. var AudioEngine = (function () {
  32850. function AudioEngine() {
  32851. this._audioContext = null;
  32852. this._audioContextInitialized = false;
  32853. this.canUseWebAudio = false;
  32854. this.WarnedWebAudioUnsupported = false;
  32855. this.unlocked = false;
  32856. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  32857. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  32858. this.canUseWebAudio = true;
  32859. }
  32860. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  32861. this._unlockiOSaudio();
  32862. }
  32863. else {
  32864. this.unlocked = true;
  32865. }
  32866. }
  32867. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  32868. get: function () {
  32869. if (!this._audioContextInitialized) {
  32870. this._initializeAudioContext();
  32871. }
  32872. return this._audioContext;
  32873. },
  32874. enumerable: true,
  32875. configurable: true
  32876. });
  32877. AudioEngine.prototype._unlockiOSaudio = function () {
  32878. var _this = this;
  32879. var unlockaudio = function () {
  32880. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  32881. var source = _this.audioContext.createBufferSource();
  32882. source.buffer = buffer;
  32883. source.connect(_this.audioContext.destination);
  32884. source.start(0);
  32885. setTimeout(function () {
  32886. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  32887. _this.unlocked = true;
  32888. window.removeEventListener('touchend', unlockaudio, false);
  32889. if (_this.onAudioUnlocked) {
  32890. _this.onAudioUnlocked();
  32891. }
  32892. }
  32893. }, 0);
  32894. };
  32895. window.addEventListener('touchend', unlockaudio, false);
  32896. };
  32897. AudioEngine.prototype._initializeAudioContext = function () {
  32898. try {
  32899. if (this.canUseWebAudio) {
  32900. this._audioContext = new AudioContext();
  32901. // create a global volume gain node
  32902. this.masterGain = this._audioContext.createGain();
  32903. this.masterGain.gain.value = 1;
  32904. this.masterGain.connect(this._audioContext.destination);
  32905. this._audioContextInitialized = true;
  32906. }
  32907. }
  32908. catch (e) {
  32909. this.canUseWebAudio = false;
  32910. BABYLON.Tools.Error("Web Audio: " + e.message);
  32911. }
  32912. };
  32913. AudioEngine.prototype.dispose = function () {
  32914. if (this.canUseWebAudio && this._audioContextInitialized) {
  32915. if (this._connectedAnalyser) {
  32916. this._connectedAnalyser.stopDebugCanvas();
  32917. this._connectedAnalyser.dispose();
  32918. this.masterGain.disconnect();
  32919. this.masterGain.connect(this._audioContext.destination);
  32920. this._connectedAnalyser = null;
  32921. }
  32922. this.masterGain.gain.value = 1;
  32923. }
  32924. this.WarnedWebAudioUnsupported = false;
  32925. };
  32926. AudioEngine.prototype.getGlobalVolume = function () {
  32927. if (this.canUseWebAudio && this._audioContextInitialized) {
  32928. return this.masterGain.gain.value;
  32929. }
  32930. else {
  32931. return -1;
  32932. }
  32933. };
  32934. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  32935. if (this.canUseWebAudio && this._audioContextInitialized) {
  32936. this.masterGain.gain.value = newVolume;
  32937. }
  32938. };
  32939. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  32940. if (this._connectedAnalyser) {
  32941. this._connectedAnalyser.stopDebugCanvas();
  32942. }
  32943. if (this.canUseWebAudio && this._audioContextInitialized) {
  32944. this._connectedAnalyser = analyser;
  32945. this.masterGain.disconnect();
  32946. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  32947. }
  32948. };
  32949. return AudioEngine;
  32950. }());
  32951. BABYLON.AudioEngine = AudioEngine;
  32952. })(BABYLON || (BABYLON = {}));
  32953. var BABYLON;
  32954. (function (BABYLON) {
  32955. var Sound = (function () {
  32956. /**
  32957. * Create a sound and attach it to a scene
  32958. * @param name Name of your sound
  32959. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  32960. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  32961. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  32962. */
  32963. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  32964. var _this = this;
  32965. this.autoplay = false;
  32966. this.loop = false;
  32967. this.useCustomAttenuation = false;
  32968. this.spatialSound = false;
  32969. this.refDistance = 1;
  32970. this.rolloffFactor = 1;
  32971. this.maxDistance = 100;
  32972. this.distanceModel = "linear";
  32973. this._panningModel = "equalpower";
  32974. this._playbackRate = 1;
  32975. this._streaming = false;
  32976. this._startTime = 0;
  32977. this._startOffset = 0;
  32978. this._position = BABYLON.Vector3.Zero();
  32979. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  32980. this._volume = 1;
  32981. this._isLoaded = false;
  32982. this._isReadyToPlay = false;
  32983. this.isPlaying = false;
  32984. this.isPaused = false;
  32985. this._isDirectional = false;
  32986. // Used if you'd like to create a directional sound.
  32987. // If not set, the sound will be omnidirectional
  32988. this._coneInnerAngle = 360;
  32989. this._coneOuterAngle = 360;
  32990. this._coneOuterGain = 0;
  32991. this._isOutputConnected = false;
  32992. this.name = name;
  32993. this._scene = scene;
  32994. this._readyToPlayCallback = readyToPlayCallback;
  32995. // Default custom attenuation function is a linear attenuation
  32996. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  32997. if (currentDistance < maxDistance) {
  32998. return currentVolume * (1 - currentDistance / maxDistance);
  32999. }
  33000. else {
  33001. return 0;
  33002. }
  33003. };
  33004. if (options) {
  33005. this.autoplay = options.autoplay || false;
  33006. this.loop = options.loop || false;
  33007. // if volume === 0, we need another way to check this option
  33008. if (options.volume !== undefined) {
  33009. this._volume = options.volume;
  33010. }
  33011. this.spatialSound = options.spatialSound || false;
  33012. this.maxDistance = options.maxDistance || 100;
  33013. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33014. this.rolloffFactor = options.rolloffFactor || 1;
  33015. this.refDistance = options.refDistance || 1;
  33016. this.distanceModel = options.distanceModel || "linear";
  33017. this._playbackRate = options.playbackRate || 1;
  33018. this._streaming = options.streaming || false;
  33019. }
  33020. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33021. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33022. this._soundGain.gain.value = this._volume;
  33023. this._inputAudioNode = this._soundGain;
  33024. this._ouputAudioNode = this._soundGain;
  33025. if (this.spatialSound) {
  33026. this._createSpatialParameters();
  33027. }
  33028. this._scene.mainSoundTrack.AddSound(this);
  33029. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33030. if (urlOrArrayBuffer) {
  33031. // If it's an URL
  33032. if (typeof (urlOrArrayBuffer) === "string") {
  33033. // Loading sound using XHR2
  33034. if (!this._streaming) {
  33035. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33036. }
  33037. else {
  33038. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33039. this._htmlAudioElement.controls = false;
  33040. this._htmlAudioElement.loop = this.loop;
  33041. this._htmlAudioElement.crossOrigin = "anonymous";
  33042. this._htmlAudioElement.preload = "auto";
  33043. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33044. _this._isReadyToPlay = true;
  33045. if (_this.autoplay) {
  33046. _this.play();
  33047. }
  33048. if (_this._readyToPlayCallback) {
  33049. _this._readyToPlayCallback();
  33050. }
  33051. });
  33052. document.body.appendChild(this._htmlAudioElement);
  33053. }
  33054. }
  33055. else {
  33056. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33057. if (urlOrArrayBuffer.byteLength > 0) {
  33058. this._soundLoaded(urlOrArrayBuffer);
  33059. }
  33060. }
  33061. else {
  33062. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33063. }
  33064. }
  33065. }
  33066. }
  33067. else {
  33068. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33069. this._scene.mainSoundTrack.AddSound(this);
  33070. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33071. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33072. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33073. }
  33074. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33075. if (this._readyToPlayCallback) {
  33076. window.setTimeout(function () {
  33077. _this._readyToPlayCallback();
  33078. }, 1000);
  33079. }
  33080. }
  33081. }
  33082. Sound.prototype.dispose = function () {
  33083. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33084. if (this.isPlaying) {
  33085. this.stop();
  33086. }
  33087. this._isReadyToPlay = false;
  33088. if (this.soundTrackId === -1) {
  33089. this._scene.mainSoundTrack.RemoveSound(this);
  33090. }
  33091. else {
  33092. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33093. }
  33094. if (this._soundGain) {
  33095. this._soundGain.disconnect();
  33096. this._soundGain = null;
  33097. }
  33098. if (this._soundPanner) {
  33099. this._soundPanner.disconnect();
  33100. this._soundPanner = null;
  33101. }
  33102. if (this._soundSource) {
  33103. this._soundSource.disconnect();
  33104. this._soundSource = null;
  33105. }
  33106. this._audioBuffer = null;
  33107. if (this._htmlAudioElement) {
  33108. this._htmlAudioElement.pause();
  33109. this._htmlAudioElement.src = "";
  33110. document.body.removeChild(this._htmlAudioElement);
  33111. }
  33112. if (this._connectedMesh) {
  33113. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33114. this._connectedMesh = null;
  33115. }
  33116. }
  33117. };
  33118. Sound.prototype._soundLoaded = function (audioData) {
  33119. var _this = this;
  33120. this._isLoaded = true;
  33121. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33122. _this._audioBuffer = buffer;
  33123. _this._isReadyToPlay = true;
  33124. if (_this.autoplay) {
  33125. _this.play();
  33126. }
  33127. if (_this._readyToPlayCallback) {
  33128. _this._readyToPlayCallback();
  33129. }
  33130. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33131. };
  33132. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33133. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33134. this._audioBuffer = audioBuffer;
  33135. this._isReadyToPlay = true;
  33136. }
  33137. };
  33138. Sound.prototype.updateOptions = function (options) {
  33139. if (options) {
  33140. this.loop = options.loop || this.loop;
  33141. this.maxDistance = options.maxDistance || this.maxDistance;
  33142. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33143. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33144. this.refDistance = options.refDistance || this.refDistance;
  33145. this.distanceModel = options.distanceModel || this.distanceModel;
  33146. this._playbackRate = options.playbackRate || this._playbackRate;
  33147. this._updateSpatialParameters();
  33148. if (this.isPlaying) {
  33149. if (this._streaming) {
  33150. this._htmlAudioElement.playbackRate = this._playbackRate;
  33151. }
  33152. else {
  33153. this._soundSource.playbackRate.value = this._playbackRate;
  33154. }
  33155. }
  33156. }
  33157. };
  33158. Sound.prototype._createSpatialParameters = function () {
  33159. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33160. if (this._scene.headphone) {
  33161. this._panningModel = "HRTF";
  33162. }
  33163. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33164. this._updateSpatialParameters();
  33165. this._soundPanner.connect(this._ouputAudioNode);
  33166. this._inputAudioNode = this._soundPanner;
  33167. }
  33168. };
  33169. Sound.prototype._updateSpatialParameters = function () {
  33170. if (this.spatialSound) {
  33171. if (this.useCustomAttenuation) {
  33172. // Tricks to disable in a way embedded Web Audio attenuation
  33173. this._soundPanner.distanceModel = "linear";
  33174. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33175. this._soundPanner.refDistance = 1;
  33176. this._soundPanner.rolloffFactor = 1;
  33177. this._soundPanner.panningModel = this._panningModel;
  33178. }
  33179. else {
  33180. this._soundPanner.distanceModel = this.distanceModel;
  33181. this._soundPanner.maxDistance = this.maxDistance;
  33182. this._soundPanner.refDistance = this.refDistance;
  33183. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33184. this._soundPanner.panningModel = this._panningModel;
  33185. }
  33186. }
  33187. };
  33188. Sound.prototype.switchPanningModelToHRTF = function () {
  33189. this._panningModel = "HRTF";
  33190. this._switchPanningModel();
  33191. };
  33192. Sound.prototype.switchPanningModelToEqualPower = function () {
  33193. this._panningModel = "equalpower";
  33194. this._switchPanningModel();
  33195. };
  33196. Sound.prototype._switchPanningModel = function () {
  33197. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33198. this._soundPanner.panningModel = this._panningModel;
  33199. }
  33200. };
  33201. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33202. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33203. if (this._isOutputConnected) {
  33204. this._ouputAudioNode.disconnect();
  33205. }
  33206. this._ouputAudioNode.connect(soundTrackAudioNode);
  33207. this._isOutputConnected = true;
  33208. }
  33209. };
  33210. /**
  33211. * Transform this sound into a directional source
  33212. * @param coneInnerAngle Size of the inner cone in degree
  33213. * @param coneOuterAngle Size of the outer cone in degree
  33214. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33215. */
  33216. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33217. if (coneOuterAngle < coneInnerAngle) {
  33218. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33219. return;
  33220. }
  33221. this._coneInnerAngle = coneInnerAngle;
  33222. this._coneOuterAngle = coneOuterAngle;
  33223. this._coneOuterGain = coneOuterGain;
  33224. this._isDirectional = true;
  33225. if (this.isPlaying && this.loop) {
  33226. this.stop();
  33227. this.play();
  33228. }
  33229. };
  33230. Sound.prototype.setPosition = function (newPosition) {
  33231. this._position = newPosition;
  33232. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33233. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33234. }
  33235. };
  33236. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33237. this._localDirection = newLocalDirection;
  33238. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33239. this._updateDirection();
  33240. }
  33241. };
  33242. Sound.prototype._updateDirection = function () {
  33243. var mat = this._connectedMesh.getWorldMatrix();
  33244. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33245. direction.normalize();
  33246. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33247. };
  33248. Sound.prototype.updateDistanceFromListener = function () {
  33249. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33250. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33251. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33252. }
  33253. };
  33254. Sound.prototype.setAttenuationFunction = function (callback) {
  33255. this._customAttenuationFunction = callback;
  33256. };
  33257. /**
  33258. * Play the sound
  33259. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33260. */
  33261. Sound.prototype.play = function (time) {
  33262. var _this = this;
  33263. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33264. try {
  33265. if (this._startOffset < 0) {
  33266. time = -this._startOffset;
  33267. this._startOffset = 0;
  33268. }
  33269. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33270. if (!this._soundSource || !this._streamingSource) {
  33271. if (this.spatialSound) {
  33272. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33273. if (this._isDirectional) {
  33274. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33275. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33276. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33277. if (this._connectedMesh) {
  33278. this._updateDirection();
  33279. }
  33280. else {
  33281. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33282. }
  33283. }
  33284. }
  33285. }
  33286. if (this._streaming) {
  33287. if (!this._streamingSource) {
  33288. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33289. this._htmlAudioElement.onended = function () { _this._onended(); };
  33290. this._htmlAudioElement.playbackRate = this._playbackRate;
  33291. }
  33292. this._streamingSource.disconnect();
  33293. this._streamingSource.connect(this._inputAudioNode);
  33294. this._htmlAudioElement.play();
  33295. }
  33296. else {
  33297. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33298. this._soundSource.buffer = this._audioBuffer;
  33299. this._soundSource.connect(this._inputAudioNode);
  33300. this._soundSource.loop = this.loop;
  33301. this._soundSource.playbackRate.value = this._playbackRate;
  33302. this._soundSource.onended = function () { _this._onended(); };
  33303. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33304. }
  33305. this._startTime = startTime;
  33306. this.isPlaying = true;
  33307. this.isPaused = false;
  33308. }
  33309. catch (ex) {
  33310. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33311. }
  33312. }
  33313. };
  33314. Sound.prototype._onended = function () {
  33315. this.isPlaying = false;
  33316. if (this.onended) {
  33317. this.onended();
  33318. }
  33319. };
  33320. /**
  33321. * Stop the sound
  33322. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33323. */
  33324. Sound.prototype.stop = function (time) {
  33325. if (this.isPlaying) {
  33326. if (this._streaming) {
  33327. this._htmlAudioElement.pause();
  33328. // Test needed for Firefox or it will generate an Invalid State Error
  33329. if (this._htmlAudioElement.currentTime > 0) {
  33330. this._htmlAudioElement.currentTime = 0;
  33331. }
  33332. }
  33333. else {
  33334. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33335. this._soundSource.stop(stopTime);
  33336. if (!this.isPaused) {
  33337. this._startOffset = 0;
  33338. }
  33339. }
  33340. this.isPlaying = false;
  33341. }
  33342. };
  33343. Sound.prototype.pause = function () {
  33344. if (this.isPlaying) {
  33345. this.isPaused = true;
  33346. if (this._streaming) {
  33347. this._htmlAudioElement.pause();
  33348. }
  33349. else {
  33350. this.stop(0);
  33351. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33352. }
  33353. }
  33354. };
  33355. Sound.prototype.setVolume = function (newVolume, time) {
  33356. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33357. if (time) {
  33358. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33359. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33360. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33361. }
  33362. else {
  33363. this._soundGain.gain.value = newVolume;
  33364. }
  33365. }
  33366. this._volume = newVolume;
  33367. };
  33368. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33369. this._playbackRate = newPlaybackRate;
  33370. if (this.isPlaying) {
  33371. if (this._streaming) {
  33372. this._htmlAudioElement.playbackRate = this._playbackRate;
  33373. }
  33374. else {
  33375. this._soundSource.playbackRate.value = this._playbackRate;
  33376. }
  33377. }
  33378. };
  33379. Sound.prototype.getVolume = function () {
  33380. return this._volume;
  33381. };
  33382. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33383. var _this = this;
  33384. if (this._connectedMesh) {
  33385. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33386. this._registerFunc = null;
  33387. }
  33388. this._connectedMesh = meshToConnectTo;
  33389. if (!this.spatialSound) {
  33390. this.spatialSound = true;
  33391. this._createSpatialParameters();
  33392. if (this.isPlaying && this.loop) {
  33393. this.stop();
  33394. this.play();
  33395. }
  33396. }
  33397. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33398. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33399. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33400. };
  33401. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33402. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33403. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33404. this._updateDirection();
  33405. }
  33406. };
  33407. Sound.prototype.clone = function () {
  33408. var _this = this;
  33409. if (!this._streaming) {
  33410. var setBufferAndRun = function () {
  33411. if (_this._isReadyToPlay) {
  33412. clonedSound._audioBuffer = _this.getAudioBuffer();
  33413. clonedSound._isReadyToPlay = true;
  33414. if (clonedSound.autoplay) {
  33415. clonedSound.play();
  33416. }
  33417. }
  33418. else {
  33419. window.setTimeout(setBufferAndRun, 300);
  33420. }
  33421. };
  33422. var currentOptions = {
  33423. autoplay: this.autoplay, loop: this.loop,
  33424. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  33425. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  33426. refDistance: this.refDistance, distanceModel: this.distanceModel
  33427. };
  33428. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  33429. if (this.useCustomAttenuation) {
  33430. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  33431. }
  33432. clonedSound.setPosition(this._position);
  33433. clonedSound.setPlaybackRate(this._playbackRate);
  33434. setBufferAndRun();
  33435. return clonedSound;
  33436. }
  33437. else {
  33438. return null;
  33439. }
  33440. };
  33441. Sound.prototype.getAudioBuffer = function () {
  33442. return this._audioBuffer;
  33443. };
  33444. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  33445. var soundName = parsedSound.name;
  33446. var soundUrl;
  33447. if (parsedSound.url) {
  33448. soundUrl = rootUrl + parsedSound.url;
  33449. }
  33450. else {
  33451. soundUrl = rootUrl + soundName;
  33452. }
  33453. var options = {
  33454. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33455. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33456. rolloffFactor: parsedSound.rolloffFactor,
  33457. refDistance: parsedSound.refDistance,
  33458. distanceModel: parsedSound.distanceModel,
  33459. playbackRate: parsedSound.playbackRate
  33460. };
  33461. var newSound;
  33462. if (!sourceSound) {
  33463. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33464. scene._addPendingData(newSound);
  33465. }
  33466. else {
  33467. var setBufferAndRun = function () {
  33468. if (sourceSound._isReadyToPlay) {
  33469. newSound._audioBuffer = sourceSound.getAudioBuffer();
  33470. newSound._isReadyToPlay = true;
  33471. if (newSound.autoplay) {
  33472. newSound.play();
  33473. }
  33474. }
  33475. else {
  33476. window.setTimeout(setBufferAndRun, 300);
  33477. }
  33478. };
  33479. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  33480. setBufferAndRun();
  33481. }
  33482. if (parsedSound.position) {
  33483. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33484. newSound.setPosition(soundPosition);
  33485. }
  33486. if (parsedSound.isDirectional) {
  33487. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33488. if (parsedSound.localDirectionToMesh) {
  33489. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33490. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33491. }
  33492. }
  33493. if (parsedSound.connectedMeshId) {
  33494. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33495. if (connectedMesh) {
  33496. newSound.attachToMesh(connectedMesh);
  33497. }
  33498. }
  33499. return newSound;
  33500. };
  33501. return Sound;
  33502. }());
  33503. BABYLON.Sound = Sound;
  33504. })(BABYLON || (BABYLON = {}));
  33505. var BABYLON;
  33506. (function (BABYLON) {
  33507. var SoundTrack = (function () {
  33508. function SoundTrack(scene, options) {
  33509. this.id = -1;
  33510. this._isMainTrack = false;
  33511. this._isInitialized = false;
  33512. this._scene = scene;
  33513. this.soundCollection = new Array();
  33514. this._options = options;
  33515. if (!this._isMainTrack) {
  33516. this._scene.soundTracks.push(this);
  33517. this.id = this._scene.soundTracks.length - 1;
  33518. }
  33519. }
  33520. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33521. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33522. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33523. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33524. if (this._options) {
  33525. if (this._options.volume) {
  33526. this._outputAudioNode.gain.value = this._options.volume;
  33527. }
  33528. if (this._options.mainTrack) {
  33529. this._isMainTrack = this._options.mainTrack;
  33530. }
  33531. }
  33532. this._isInitialized = true;
  33533. }
  33534. };
  33535. SoundTrack.prototype.dispose = function () {
  33536. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33537. if (this._connectedAnalyser) {
  33538. this._connectedAnalyser.stopDebugCanvas();
  33539. }
  33540. while (this.soundCollection.length) {
  33541. this.soundCollection[0].dispose();
  33542. }
  33543. if (this._outputAudioNode) {
  33544. this._outputAudioNode.disconnect();
  33545. }
  33546. this._outputAudioNode = null;
  33547. }
  33548. };
  33549. SoundTrack.prototype.AddSound = function (sound) {
  33550. if (!this._isInitialized) {
  33551. this._initializeSoundTrackAudioGraph();
  33552. }
  33553. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33554. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33555. }
  33556. if (sound.soundTrackId) {
  33557. if (sound.soundTrackId === -1) {
  33558. this._scene.mainSoundTrack.RemoveSound(sound);
  33559. }
  33560. else {
  33561. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33562. }
  33563. }
  33564. this.soundCollection.push(sound);
  33565. sound.soundTrackId = this.id;
  33566. };
  33567. SoundTrack.prototype.RemoveSound = function (sound) {
  33568. var index = this.soundCollection.indexOf(sound);
  33569. if (index !== -1) {
  33570. this.soundCollection.splice(index, 1);
  33571. }
  33572. };
  33573. SoundTrack.prototype.setVolume = function (newVolume) {
  33574. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33575. this._outputAudioNode.gain.value = newVolume;
  33576. }
  33577. };
  33578. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33579. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33580. for (var i = 0; i < this.soundCollection.length; i++) {
  33581. this.soundCollection[i].switchPanningModelToHRTF();
  33582. }
  33583. }
  33584. };
  33585. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33586. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33587. for (var i = 0; i < this.soundCollection.length; i++) {
  33588. this.soundCollection[i].switchPanningModelToEqualPower();
  33589. }
  33590. }
  33591. };
  33592. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33593. if (this._connectedAnalyser) {
  33594. this._connectedAnalyser.stopDebugCanvas();
  33595. }
  33596. this._connectedAnalyser = analyser;
  33597. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33598. this._outputAudioNode.disconnect();
  33599. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33600. }
  33601. };
  33602. return SoundTrack;
  33603. }());
  33604. BABYLON.SoundTrack = SoundTrack;
  33605. })(BABYLON || (BABYLON = {}));
  33606. var BABYLON;
  33607. (function (BABYLON) {
  33608. var SIMDVector3 = (function () {
  33609. function SIMDVector3() {
  33610. }
  33611. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  33612. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  33613. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33614. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33615. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33616. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33617. 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));
  33618. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33619. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33620. };
  33621. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  33622. var v0 = SIMD.float32x4.splat(x);
  33623. var v1 = SIMD.float32x4.splat(y);
  33624. var v2 = SIMD.float32x4.splat(z);
  33625. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33626. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33627. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33628. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33629. 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));
  33630. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33631. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33632. };
  33633. return SIMDVector3;
  33634. }());
  33635. BABYLON.SIMDVector3 = SIMDVector3;
  33636. var SIMDMatrix = (function () {
  33637. function SIMDMatrix() {
  33638. }
  33639. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  33640. if (offset === void 0) { offset = 0; }
  33641. var tm = this.m;
  33642. var om = other.m;
  33643. var om0 = SIMD.float32x4.load(om, 0);
  33644. var om1 = SIMD.float32x4.load(om, 4);
  33645. var om2 = SIMD.float32x4.load(om, 8);
  33646. var om3 = SIMD.float32x4.load(om, 12);
  33647. var tm0 = SIMD.float32x4.load(tm, 0);
  33648. 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)))));
  33649. var tm1 = SIMD.float32x4.load(tm, 4);
  33650. 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)))));
  33651. var tm2 = SIMD.float32x4.load(tm, 8);
  33652. 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)))));
  33653. var tm3 = SIMD.float32x4.load(tm, 12);
  33654. 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)))));
  33655. };
  33656. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  33657. var src = this.m;
  33658. var dest = other.m;
  33659. var row0, row1, row2, row3;
  33660. var tmp1;
  33661. var minor0, minor1, minor2, minor3;
  33662. var det;
  33663. // Load the 4 rows
  33664. var src0 = SIMD.float32x4.load(src, 0);
  33665. var src1 = SIMD.float32x4.load(src, 4);
  33666. var src2 = SIMD.float32x4.load(src, 8);
  33667. var src3 = SIMD.float32x4.load(src, 12);
  33668. // Transpose the source matrix. Sort of. Not a true transpose operation
  33669. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33670. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33671. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  33672. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  33673. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33674. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33675. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  33676. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  33677. // This is a true transposition, but it will lead to an incorrect result
  33678. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33679. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33680. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33681. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33682. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33683. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33684. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33685. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33686. // ----
  33687. tmp1 = SIMD.float32x4.mul(row2, row3);
  33688. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33689. minor0 = SIMD.float32x4.mul(row1, tmp1);
  33690. minor1 = SIMD.float32x4.mul(row0, tmp1);
  33691. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33692. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  33693. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  33694. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  33695. // ----
  33696. tmp1 = SIMD.float32x4.mul(row1, row2);
  33697. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33698. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  33699. minor3 = SIMD.float32x4.mul(row0, tmp1);
  33700. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33701. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  33702. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  33703. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  33704. // ----
  33705. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  33706. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33707. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  33708. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  33709. minor2 = SIMD.float32x4.mul(row0, tmp1);
  33710. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33711. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  33712. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  33713. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  33714. // ----
  33715. tmp1 = SIMD.float32x4.mul(row0, row1);
  33716. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33717. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  33718. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  33719. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33720. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  33721. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  33722. // ----
  33723. tmp1 = SIMD.float32x4.mul(row0, row3);
  33724. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33725. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  33726. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  33727. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33728. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  33729. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  33730. // ----
  33731. tmp1 = SIMD.float32x4.mul(row0, row2);
  33732. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33733. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  33734. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  33735. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33736. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  33737. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  33738. // Compute determinant
  33739. det = SIMD.float32x4.mul(row0, minor0);
  33740. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  33741. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  33742. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  33743. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  33744. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  33745. // These shuffles aren't necessary if the faulty transposition is done
  33746. // up at the top of this function.
  33747. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  33748. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  33749. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  33750. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  33751. // Compute final values by multiplying with 1/det
  33752. minor0 = SIMD.float32x4.mul(det, minor0);
  33753. minor1 = SIMD.float32x4.mul(det, minor1);
  33754. minor2 = SIMD.float32x4.mul(det, minor2);
  33755. minor3 = SIMD.float32x4.mul(det, minor3);
  33756. SIMD.float32x4.store(dest, 0, minor0);
  33757. SIMD.float32x4.store(dest, 4, minor1);
  33758. SIMD.float32x4.store(dest, 8, minor2);
  33759. SIMD.float32x4.store(dest, 12, minor3);
  33760. return this;
  33761. };
  33762. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  33763. var out = result.m;
  33764. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  33765. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  33766. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  33767. // cc.kmVec3Subtract(f, pCenter, pEye);
  33768. var f = SIMD.float32x4.sub(center, eye);
  33769. // cc.kmVec3Normalize(f, f);
  33770. var tmp = SIMD.float32x4.mul(f, f);
  33771. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33772. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33773. // cc.kmVec3Assign(up, pUp);
  33774. // cc.kmVec3Normalize(up, up);
  33775. tmp = SIMD.float32x4.mul(up, up);
  33776. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33777. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33778. // cc.kmVec3Cross(s, f, up);
  33779. 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)));
  33780. // cc.kmVec3Normalize(s, s);
  33781. tmp = SIMD.float32x4.mul(s, s);
  33782. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33783. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33784. // cc.kmVec3Cross(u, s, f);
  33785. 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)));
  33786. // cc.kmVec3Normalize(s, s);
  33787. tmp = SIMD.float32x4.mul(s, s);
  33788. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33789. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33790. var zero = SIMD.float32x4.splat(0.0);
  33791. s = SIMD.float32x4.neg(s);
  33792. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  33793. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  33794. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33795. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  33796. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  33797. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  33798. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33799. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  33800. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  33801. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  33802. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  33803. var b3 = SIMD.float32x4.neg(eye);
  33804. b3 = SIMD.float32x4.withW(b3, 1.0);
  33805. 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)))));
  33806. 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)))));
  33807. 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)))));
  33808. 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)))));
  33809. };
  33810. return SIMDMatrix;
  33811. }());
  33812. BABYLON.SIMDMatrix = SIMDMatrix;
  33813. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  33814. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  33815. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  33816. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  33817. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  33818. var SIMDHelper = (function () {
  33819. function SIMDHelper() {
  33820. }
  33821. Object.defineProperty(SIMDHelper, "IsEnabled", {
  33822. get: function () {
  33823. return SIMDHelper._isEnabled;
  33824. },
  33825. enumerable: true,
  33826. configurable: true
  33827. });
  33828. SIMDHelper.DisableSIMD = function () {
  33829. // Replace functions
  33830. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  33831. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  33832. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  33833. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  33834. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  33835. SIMDHelper._isEnabled = false;
  33836. };
  33837. SIMDHelper.EnableSIMD = function () {
  33838. if (window.SIMD === undefined) {
  33839. return;
  33840. }
  33841. // Replace functions
  33842. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  33843. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  33844. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  33845. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  33846. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  33847. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  33848. get: function () { return this._data[0]; },
  33849. set: function (value) {
  33850. if (!this._data) {
  33851. this._data = new Float32Array(3);
  33852. }
  33853. this._data[0] = value;
  33854. }
  33855. });
  33856. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  33857. get: function () { return this._data[1]; },
  33858. set: function (value) {
  33859. this._data[1] = value;
  33860. }
  33861. });
  33862. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  33863. get: function () { return this._data[2]; },
  33864. set: function (value) {
  33865. this._data[2] = value;
  33866. }
  33867. });
  33868. SIMDHelper._isEnabled = true;
  33869. };
  33870. SIMDHelper._isEnabled = false;
  33871. return SIMDHelper;
  33872. }());
  33873. BABYLON.SIMDHelper = SIMDHelper;
  33874. })(BABYLON || (BABYLON = {}));
  33875. var BABYLON;
  33876. (function (BABYLON) {
  33877. var ShaderMaterial = (function (_super) {
  33878. __extends(ShaderMaterial, _super);
  33879. function ShaderMaterial(name, scene, shaderPath, options) {
  33880. _super.call(this, name, scene);
  33881. this._textures = {};
  33882. this._floats = {};
  33883. this._floatsArrays = {};
  33884. this._colors3 = {};
  33885. this._colors4 = {};
  33886. this._vectors2 = {};
  33887. this._vectors3 = {};
  33888. this._vectors4 = {};
  33889. this._matrices = {};
  33890. this._matrices3x3 = {};
  33891. this._matrices2x2 = {};
  33892. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  33893. this._shaderPath = shaderPath;
  33894. options.needAlphaBlending = options.needAlphaBlending || false;
  33895. options.needAlphaTesting = options.needAlphaTesting || false;
  33896. options.attributes = options.attributes || ["position", "normal", "uv"];
  33897. options.uniforms = options.uniforms || ["worldViewProjection"];
  33898. options.samplers = options.samplers || [];
  33899. options.defines = options.defines || [];
  33900. this._options = options;
  33901. }
  33902. ShaderMaterial.prototype.needAlphaBlending = function () {
  33903. return this._options.needAlphaBlending;
  33904. };
  33905. ShaderMaterial.prototype.needAlphaTesting = function () {
  33906. return this._options.needAlphaTesting;
  33907. };
  33908. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  33909. if (this._options.uniforms.indexOf(uniformName) === -1) {
  33910. this._options.uniforms.push(uniformName);
  33911. }
  33912. };
  33913. ShaderMaterial.prototype.setTexture = function (name, texture) {
  33914. if (this._options.samplers.indexOf(name) === -1) {
  33915. this._options.samplers.push(name);
  33916. }
  33917. this._textures[name] = texture;
  33918. return this;
  33919. };
  33920. ShaderMaterial.prototype.setFloat = function (name, value) {
  33921. this._checkUniform(name);
  33922. this._floats[name] = value;
  33923. return this;
  33924. };
  33925. ShaderMaterial.prototype.setFloats = function (name, value) {
  33926. this._checkUniform(name);
  33927. this._floatsArrays[name] = value;
  33928. return this;
  33929. };
  33930. ShaderMaterial.prototype.setColor3 = function (name, value) {
  33931. this._checkUniform(name);
  33932. this._colors3[name] = value;
  33933. return this;
  33934. };
  33935. ShaderMaterial.prototype.setColor4 = function (name, value) {
  33936. this._checkUniform(name);
  33937. this._colors4[name] = value;
  33938. return this;
  33939. };
  33940. ShaderMaterial.prototype.setVector2 = function (name, value) {
  33941. this._checkUniform(name);
  33942. this._vectors2[name] = value;
  33943. return this;
  33944. };
  33945. ShaderMaterial.prototype.setVector3 = function (name, value) {
  33946. this._checkUniform(name);
  33947. this._vectors3[name] = value;
  33948. return this;
  33949. };
  33950. ShaderMaterial.prototype.setVector4 = function (name, value) {
  33951. this._checkUniform(name);
  33952. this._vectors4[name] = value;
  33953. return this;
  33954. };
  33955. ShaderMaterial.prototype.setMatrix = function (name, value) {
  33956. this._checkUniform(name);
  33957. this._matrices[name] = value;
  33958. return this;
  33959. };
  33960. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  33961. this._checkUniform(name);
  33962. this._matrices3x3[name] = value;
  33963. return this;
  33964. };
  33965. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  33966. this._checkUniform(name);
  33967. this._matrices2x2[name] = value;
  33968. return this;
  33969. };
  33970. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  33971. var scene = this.getScene();
  33972. var engine = scene.getEngine();
  33973. if (!this.checkReadyOnEveryCall) {
  33974. if (this._renderId === scene.getRenderId()) {
  33975. return true;
  33976. }
  33977. }
  33978. // Instances
  33979. var defines = [];
  33980. var fallbacks = new BABYLON.EffectFallbacks();
  33981. if (useInstances) {
  33982. defines.push("#define INSTANCES");
  33983. }
  33984. for (var index = 0; index < this._options.defines.length; index++) {
  33985. defines.push(this._options.defines[index]);
  33986. }
  33987. // Bones
  33988. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  33989. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33990. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33991. fallbacks.addCPUSkinningFallback(0, mesh);
  33992. }
  33993. // Alpha test
  33994. if (engine.getAlphaTesting()) {
  33995. defines.push("#define ALPHATEST");
  33996. }
  33997. var previousEffect = this._effect;
  33998. var join = defines.join("\n");
  33999. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  34000. if (!this._effect.isReady()) {
  34001. return false;
  34002. }
  34003. if (previousEffect !== this._effect) {
  34004. scene.resetCachedMaterial();
  34005. }
  34006. this._renderId = scene.getRenderId();
  34007. return true;
  34008. };
  34009. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34010. var scene = this.getScene();
  34011. if (this._options.uniforms.indexOf("world") !== -1) {
  34012. this._effect.setMatrix("world", world);
  34013. }
  34014. if (this._options.uniforms.indexOf("worldView") !== -1) {
  34015. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  34016. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  34017. }
  34018. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  34019. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  34020. }
  34021. };
  34022. ShaderMaterial.prototype.bind = function (world, mesh) {
  34023. // Std values
  34024. this.bindOnlyWorldMatrix(world);
  34025. if (this.getScene().getCachedMaterial() !== this) {
  34026. if (this._options.uniforms.indexOf("view") !== -1) {
  34027. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  34028. }
  34029. if (this._options.uniforms.indexOf("projection") !== -1) {
  34030. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  34031. }
  34032. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  34033. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34034. }
  34035. // Bones
  34036. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34037. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34038. }
  34039. // Texture
  34040. for (var name in this._textures) {
  34041. this._effect.setTexture(name, this._textures[name]);
  34042. }
  34043. // Float
  34044. for (name in this._floats) {
  34045. this._effect.setFloat(name, this._floats[name]);
  34046. }
  34047. // Float s
  34048. for (name in this._floatsArrays) {
  34049. this._effect.setArray(name, this._floatsArrays[name]);
  34050. }
  34051. // Color3
  34052. for (name in this._colors3) {
  34053. this._effect.setColor3(name, this._colors3[name]);
  34054. }
  34055. // Color4
  34056. for (name in this._colors4) {
  34057. var color = this._colors4[name];
  34058. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  34059. }
  34060. // Vector2
  34061. for (name in this._vectors2) {
  34062. this._effect.setVector2(name, this._vectors2[name]);
  34063. }
  34064. // Vector3
  34065. for (name in this._vectors3) {
  34066. this._effect.setVector3(name, this._vectors3[name]);
  34067. }
  34068. // Vector4
  34069. for (name in this._vectors4) {
  34070. this._effect.setVector4(name, this._vectors4[name]);
  34071. }
  34072. // Matrix
  34073. for (name in this._matrices) {
  34074. this._effect.setMatrix(name, this._matrices[name]);
  34075. }
  34076. // Matrix 3x3
  34077. for (name in this._matrices3x3) {
  34078. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  34079. }
  34080. // Matrix 2x2
  34081. for (name in this._matrices2x2) {
  34082. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  34083. }
  34084. }
  34085. _super.prototype.bind.call(this, world, mesh);
  34086. };
  34087. ShaderMaterial.prototype.clone = function (name) {
  34088. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  34089. return newShaderMaterial;
  34090. };
  34091. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  34092. for (var name in this._textures) {
  34093. this._textures[name].dispose();
  34094. }
  34095. this._textures = {};
  34096. _super.prototype.dispose.call(this, forceDisposeEffect);
  34097. };
  34098. ShaderMaterial.prototype.serialize = function () {
  34099. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34100. serializationObject.customType = "BABYLON.ShaderMaterial";
  34101. serializationObject.options = this._options;
  34102. serializationObject.shaderPath = this._shaderPath;
  34103. // Texture
  34104. serializationObject.textures = {};
  34105. for (var name in this._textures) {
  34106. serializationObject.textures[name] = this._textures[name].serialize();
  34107. }
  34108. // Float
  34109. serializationObject.floats = {};
  34110. for (name in this._floats) {
  34111. serializationObject.floats[name] = this._floats[name];
  34112. }
  34113. // Float s
  34114. serializationObject.floatArrays = {};
  34115. for (name in this._floatsArrays) {
  34116. serializationObject.floatArrays[name] = this._floatsArrays[name];
  34117. }
  34118. // Color3
  34119. serializationObject.colors3 = {};
  34120. for (name in this._colors3) {
  34121. serializationObject.colors3[name] = this._colors3[name].asArray();
  34122. }
  34123. // Color4
  34124. serializationObject.colors4 = {};
  34125. for (name in this._colors4) {
  34126. serializationObject.colors4[name] = this._colors4[name].asArray();
  34127. }
  34128. // Vector2
  34129. serializationObject.vectors2 = {};
  34130. for (name in this._vectors2) {
  34131. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  34132. }
  34133. // Vector3
  34134. serializationObject.vectors3 = {};
  34135. for (name in this._vectors3) {
  34136. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  34137. }
  34138. // Vector4
  34139. serializationObject.vectors4 = {};
  34140. for (name in this._vectors4) {
  34141. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  34142. }
  34143. // Matrix
  34144. serializationObject.matrices = {};
  34145. for (name in this._matrices) {
  34146. serializationObject.matrices[name] = this._matrices[name].asArray();
  34147. }
  34148. // Matrix 3x3
  34149. serializationObject.matrices3x3 = {};
  34150. for (name in this._matrices3x3) {
  34151. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  34152. }
  34153. // Matrix 2x2
  34154. serializationObject.matrices2x2 = {};
  34155. for (name in this._matrices2x2) {
  34156. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  34157. }
  34158. return serializationObject;
  34159. };
  34160. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  34161. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  34162. // Texture
  34163. for (var name in source.textures) {
  34164. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  34165. }
  34166. // Float
  34167. for (name in source.floats) {
  34168. material.setFloat(name, source.floats[name]);
  34169. }
  34170. // Float s
  34171. for (name in source.floatsArrays) {
  34172. material.setFloats(name, source.floatsArrays[name]);
  34173. }
  34174. // Color3
  34175. for (name in source.colors3) {
  34176. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  34177. }
  34178. // Color4
  34179. for (name in source.colors4) {
  34180. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  34181. }
  34182. // Vector2
  34183. for (name in source.vectors2) {
  34184. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  34185. }
  34186. // Vector3
  34187. for (name in source.vectors3) {
  34188. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  34189. }
  34190. // Vector4
  34191. for (name in source.vectors4) {
  34192. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  34193. }
  34194. // Matrix
  34195. for (name in source.matrices) {
  34196. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  34197. }
  34198. // Matrix 3x3
  34199. for (name in source.matrices3x3) {
  34200. material.setMatrix3x3(name, source.matrices3x3[name]);
  34201. }
  34202. // Matrix 2x2
  34203. for (name in source.matrices2x2) {
  34204. material.setMatrix2x2(name, source.matrices2x2[name]);
  34205. }
  34206. return material;
  34207. };
  34208. return ShaderMaterial;
  34209. }(BABYLON.Material));
  34210. BABYLON.ShaderMaterial = ShaderMaterial;
  34211. })(BABYLON || (BABYLON = {}));
  34212. var BABYLON;
  34213. (function (BABYLON) {
  34214. var Internals;
  34215. (function (Internals) {
  34216. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34217. // All values and structures referenced from:
  34218. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34219. var DDS_MAGIC = 0x20534444;
  34220. 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;
  34221. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34222. 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;
  34223. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34224. function FourCCToInt32(value) {
  34225. return value.charCodeAt(0) +
  34226. (value.charCodeAt(1) << 8) +
  34227. (value.charCodeAt(2) << 16) +
  34228. (value.charCodeAt(3) << 24);
  34229. }
  34230. function Int32ToFourCC(value) {
  34231. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34232. }
  34233. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34234. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34235. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34236. var headerLengthInt = 31; // The header length in 32 bit ints
  34237. // Offsets into the header array
  34238. var off_magic = 0;
  34239. var off_size = 1;
  34240. var off_flags = 2;
  34241. var off_height = 3;
  34242. var off_width = 4;
  34243. var off_mipmapCount = 7;
  34244. var off_pfFlags = 20;
  34245. var off_pfFourCC = 21;
  34246. var off_RGBbpp = 22;
  34247. var off_RMask = 23;
  34248. var off_GMask = 24;
  34249. var off_BMask = 25;
  34250. var off_AMask = 26;
  34251. var off_caps1 = 27;
  34252. var off_caps2 = 28;
  34253. ;
  34254. var DDSTools = (function () {
  34255. function DDSTools() {
  34256. }
  34257. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34258. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34259. var mipmapCount = 1;
  34260. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34261. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34262. }
  34263. return {
  34264. width: header[off_width],
  34265. height: header[off_height],
  34266. mipmapCount: mipmapCount,
  34267. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34268. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34269. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34270. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  34271. };
  34272. };
  34273. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34274. var byteArray = new Uint8Array(dataLength);
  34275. var srcData = new Uint8Array(arrayBuffer);
  34276. var index = 0;
  34277. for (var y = height - 1; y >= 0; y--) {
  34278. for (var x = 0; x < width; x++) {
  34279. var srcPos = dataOffset + (x + y * width) * 4;
  34280. byteArray[index + 2] = srcData[srcPos];
  34281. byteArray[index + 1] = srcData[srcPos + 1];
  34282. byteArray[index] = srcData[srcPos + 2];
  34283. byteArray[index + 3] = srcData[srcPos + 3];
  34284. index += 4;
  34285. }
  34286. }
  34287. return byteArray;
  34288. };
  34289. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34290. var byteArray = new Uint8Array(dataLength);
  34291. var srcData = new Uint8Array(arrayBuffer);
  34292. var index = 0;
  34293. for (var y = height - 1; y >= 0; y--) {
  34294. for (var x = 0; x < width; x++) {
  34295. var srcPos = dataOffset + (x + y * width) * 3;
  34296. byteArray[index + 2] = srcData[srcPos];
  34297. byteArray[index + 1] = srcData[srcPos + 1];
  34298. byteArray[index] = srcData[srcPos + 2];
  34299. index += 3;
  34300. }
  34301. }
  34302. return byteArray;
  34303. };
  34304. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34305. var byteArray = new Uint8Array(dataLength);
  34306. var srcData = new Uint8Array(arrayBuffer);
  34307. var index = 0;
  34308. for (var y = height - 1; y >= 0; y--) {
  34309. for (var x = 0; x < width; x++) {
  34310. var srcPos = dataOffset + (x + y * width);
  34311. byteArray[index] = srcData[srcPos];
  34312. index++;
  34313. }
  34314. }
  34315. return byteArray;
  34316. };
  34317. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  34318. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  34319. if (header[off_magic] != DDS_MAGIC) {
  34320. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34321. return;
  34322. }
  34323. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34324. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34325. return;
  34326. }
  34327. if (info.isFourCC) {
  34328. fourCC = header[off_pfFourCC];
  34329. switch (fourCC) {
  34330. case FOURCC_DXT1:
  34331. blockBytes = 8;
  34332. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34333. break;
  34334. case FOURCC_DXT3:
  34335. blockBytes = 16;
  34336. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34337. break;
  34338. case FOURCC_DXT5:
  34339. blockBytes = 16;
  34340. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34341. break;
  34342. default:
  34343. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34344. return;
  34345. }
  34346. }
  34347. mipmapCount = 1;
  34348. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34349. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34350. }
  34351. var bpp = header[off_RGBbpp];
  34352. for (var face = 0; face < faces; face++) {
  34353. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34354. width = header[off_width];
  34355. height = header[off_height];
  34356. dataOffset = header[off_size] + 4;
  34357. for (i = 0; i < mipmapCount; ++i) {
  34358. if (info.isRGB) {
  34359. if (bpp === 24) {
  34360. dataLength = width * height * 3;
  34361. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34362. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34363. }
  34364. else {
  34365. dataLength = width * height * 4;
  34366. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34367. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34368. }
  34369. }
  34370. else if (info.isLuminance) {
  34371. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34372. var unpaddedRowSize = width;
  34373. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34374. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34375. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34376. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34377. }
  34378. else {
  34379. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34380. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34381. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  34382. }
  34383. dataOffset += dataLength;
  34384. width *= 0.5;
  34385. height *= 0.5;
  34386. width = Math.max(1.0, width);
  34387. height = Math.max(1.0, height);
  34388. }
  34389. }
  34390. };
  34391. return DDSTools;
  34392. }());
  34393. Internals.DDSTools = DDSTools;
  34394. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34395. })(BABYLON || (BABYLON = {}));
  34396. var BABYLON;
  34397. (function (BABYLON) {
  34398. var CannonJSPlugin = (function () {
  34399. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  34400. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  34401. if (iterations === void 0) { iterations = 10; }
  34402. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  34403. this.name = "CannonJSPlugin";
  34404. this._physicsMaterials = [];
  34405. this._fixedTimeStep = 1 / 60;
  34406. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34407. this._currentCollisionGroup = 2;
  34408. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  34409. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  34410. this._tmpPosition = BABYLON.Vector3.Zero();
  34411. this._tmpQuaternion = new BABYLON.Quaternion();
  34412. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  34413. this._tmpDeltaRotation = new BABYLON.Quaternion();
  34414. this._tmpUnityRotation = new BABYLON.Quaternion();
  34415. if (!this.isSupported()) {
  34416. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  34417. return;
  34418. }
  34419. this.world = new CANNON.World();
  34420. this.world.broadphase = new CANNON.NaiveBroadphase();
  34421. this.world.solver.iterations = iterations;
  34422. }
  34423. CannonJSPlugin.prototype.setGravity = function (gravity) {
  34424. this.world.gravity.copy(gravity);
  34425. };
  34426. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  34427. this._fixedTimeStep = timeStep;
  34428. };
  34429. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  34430. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  34431. };
  34432. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34433. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34434. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34435. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34436. };
  34437. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34438. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34439. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34440. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34441. };
  34442. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34443. //parent-child relationship. Does this impostor has a parent impostor?
  34444. if (impostor.parent) {
  34445. if (impostor.physicsBody) {
  34446. this.removePhysicsBody(impostor);
  34447. //TODO is that needed?
  34448. impostor.forceUpdate();
  34449. }
  34450. return;
  34451. }
  34452. //should a new body be created for this impostor?
  34453. if (impostor.isBodyInitRequired()) {
  34454. var shape = this._createShape(impostor);
  34455. //unregister events, if body is being changed
  34456. var oldBody = impostor.physicsBody;
  34457. if (oldBody) {
  34458. this.removePhysicsBody(impostor);
  34459. }
  34460. //create the body and material
  34461. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  34462. var bodyCreationObject = {
  34463. mass: impostor.getParam("mass"),
  34464. material: material
  34465. };
  34466. // A simple extend, in case native options were used.
  34467. var nativeOptions = impostor.getParam("nativeOptions");
  34468. for (var key in nativeOptions) {
  34469. if (nativeOptions.hasOwnProperty(key)) {
  34470. bodyCreationObject[key] = nativeOptions[key];
  34471. }
  34472. }
  34473. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  34474. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  34475. this.world.addEventListener("preStep", impostor.beforeStep);
  34476. this.world.addEventListener("postStep", impostor.afterStep);
  34477. impostor.physicsBody.addShape(shape);
  34478. this.world.add(impostor.physicsBody);
  34479. //try to keep the body moving in the right direction by taking old properties.
  34480. //Should be tested!
  34481. if (oldBody) {
  34482. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  34483. impostor.physicsBody[param].copy(oldBody[param]);
  34484. });
  34485. }
  34486. this._processChildMeshes(impostor);
  34487. }
  34488. //now update the body's transformation
  34489. this._updatePhysicsBodyTransformation(impostor);
  34490. };
  34491. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  34492. var _this = this;
  34493. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  34494. if (meshChildren.length) {
  34495. var processMesh = function (localPosition, mesh) {
  34496. var childImpostor = mesh.getPhysicsImpostor();
  34497. if (childImpostor) {
  34498. var parent = childImpostor.parent;
  34499. if (parent !== mainImpostor) {
  34500. var localPosition = mesh.position;
  34501. if (childImpostor.physicsBody) {
  34502. _this.removePhysicsBody(childImpostor);
  34503. childImpostor.physicsBody = null;
  34504. }
  34505. childImpostor.parent = mainImpostor;
  34506. childImpostor.resetUpdateFlags();
  34507. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  34508. //Add the mass of the children.
  34509. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  34510. }
  34511. }
  34512. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  34513. };
  34514. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  34515. }
  34516. };
  34517. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34518. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  34519. this.world.removeEventListener("preStep", impostor.beforeStep);
  34520. this.world.removeEventListener("postStep", impostor.afterStep);
  34521. this.world.remove(impostor.physicsBody);
  34522. };
  34523. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  34524. var mainBody = impostorJoint.mainImpostor.physicsBody;
  34525. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  34526. if (!mainBody || !connectedBody) {
  34527. return;
  34528. }
  34529. var constraint;
  34530. var jointData = impostorJoint.joint.jointData;
  34531. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34532. var constraintData = {
  34533. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  34534. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  34535. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  34536. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  34537. maxForce: jointData.nativeParams.maxForce,
  34538. collideConnected: !!jointData.collision
  34539. };
  34540. //Not needed, Cannon has a collideConnected flag
  34541. /*if (!jointData.collision) {
  34542. //add 1st body to a collision group of its own, if it is not in 1
  34543. if (mainBody.collisionFilterGroup === 1) {
  34544. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  34545. this._currentCollisionGroup <<= 1;
  34546. }
  34547. if (connectedBody.collisionFilterGroup === 1) {
  34548. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  34549. this._currentCollisionGroup <<= 1;
  34550. }
  34551. //add their mask to the collisionFilterMask of each other:
  34552. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  34553. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  34554. }*/
  34555. switch (impostorJoint.joint.type) {
  34556. case BABYLON.PhysicsJoint.HingeJoint:
  34557. case BABYLON.PhysicsJoint.Hinge2Joint:
  34558. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  34559. break;
  34560. case BABYLON.PhysicsJoint.DistanceJoint:
  34561. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  34562. break;
  34563. case BABYLON.PhysicsJoint.SpringJoint:
  34564. var springData = jointData;
  34565. constraint = new CANNON.Spring(mainBody, connectedBody, {
  34566. restLength: springData.length,
  34567. stiffness: springData.stiffness,
  34568. damping: springData.damping,
  34569. localAnchorA: constraintData.pivotA,
  34570. localAnchorB: constraintData.pivotB
  34571. });
  34572. break;
  34573. case BABYLON.PhysicsJoint.PointToPointJoint:
  34574. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  34575. default:
  34576. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  34577. break;
  34578. }
  34579. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  34580. constraint.collideConnected = !!jointData.collision;
  34581. impostorJoint.joint.physicsJoint = constraint;
  34582. //don't add spring as constraint, as it is not one.
  34583. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  34584. this.world.addConstraint(constraint);
  34585. }
  34586. else {
  34587. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  34588. constraint.applyForce();
  34589. });
  34590. }
  34591. };
  34592. CannonJSPlugin.prototype.removeJoint = function (joint) {
  34593. //TODO
  34594. };
  34595. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  34596. var index;
  34597. var mat;
  34598. for (index = 0; index < this._physicsMaterials.length; index++) {
  34599. mat = this._physicsMaterials[index];
  34600. if (mat.friction === friction && mat.restitution === restitution) {
  34601. return mat;
  34602. }
  34603. }
  34604. var currentMat = new CANNON.Material("mat");
  34605. currentMat.friction = friction;
  34606. currentMat.restitution = restitution;
  34607. this._physicsMaterials.push(currentMat);
  34608. return currentMat;
  34609. };
  34610. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  34611. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  34612. };
  34613. CannonJSPlugin.prototype._createShape = function (impostor) {
  34614. var object = impostor.object;
  34615. var returnValue;
  34616. var extendSize = impostor.getObjectExtendSize();
  34617. switch (impostor.type) {
  34618. case BABYLON.PhysicsEngine.SphereImpostor:
  34619. var radiusX = extendSize.x;
  34620. var radiusY = extendSize.y;
  34621. var radiusZ = extendSize.z;
  34622. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  34623. break;
  34624. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  34625. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34626. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  34627. break;
  34628. case BABYLON.PhysicsImpostor.BoxImpostor:
  34629. var box = extendSize.scale(0.5);
  34630. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  34631. break;
  34632. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34633. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  34634. returnValue = new CANNON.Plane();
  34635. break;
  34636. case BABYLON.PhysicsImpostor.MeshImpostor:
  34637. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  34638. var rawFaces = object.getIndices ? object.getIndices() : [];
  34639. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  34640. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  34641. break;
  34642. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  34643. returnValue = this._createHeightmap(object);
  34644. break;
  34645. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34646. returnValue = new CANNON.Particle();
  34647. break;
  34648. }
  34649. return returnValue;
  34650. };
  34651. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  34652. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34653. var matrix = [];
  34654. //For now pointDepth will not be used and will be automatically calculated.
  34655. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  34656. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  34657. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  34658. var elementSize = dim * 2 / arraySize;
  34659. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  34660. for (var i = 0; i < pos.length; i = i + 3) {
  34661. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  34662. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  34663. var y = pos[i + 1] + minY;
  34664. if (!matrix[x]) {
  34665. matrix[x] = [];
  34666. }
  34667. if (!matrix[x][z]) {
  34668. matrix[x][z] = y;
  34669. }
  34670. matrix[x][z] = Math.max(y, matrix[x][z]);
  34671. }
  34672. for (var x = 0; x <= arraySize; ++x) {
  34673. if (!matrix[x]) {
  34674. var loc = 1;
  34675. while (!matrix[(x + loc) % arraySize]) {
  34676. loc++;
  34677. }
  34678. matrix[x] = matrix[(x + loc) % arraySize].slice();
  34679. }
  34680. for (var z = 0; z <= arraySize; ++z) {
  34681. if (!matrix[x][z]) {
  34682. var loc = 1;
  34683. var newValue;
  34684. while (newValue === undefined) {
  34685. newValue = matrix[x][(z + loc++) % arraySize];
  34686. }
  34687. matrix[x][z] = newValue;
  34688. }
  34689. }
  34690. }
  34691. var shape = new CANNON.Heightfield(matrix, {
  34692. elementSize: elementSize
  34693. });
  34694. //For future reference, needed for body transformation
  34695. shape.minY = minY;
  34696. return shape;
  34697. };
  34698. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  34699. var object = impostor.object;
  34700. //make sure it is updated...
  34701. object.computeWorldMatrix && object.computeWorldMatrix(true);
  34702. // The delta between the mesh position and the mesh bounding box center
  34703. var center = impostor.getObjectCenter();
  34704. var extendSize = impostor.getObjectExtendSize();
  34705. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  34706. this._tmpPosition.copyFrom(center);
  34707. var quaternion = object.rotationQuaternion;
  34708. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  34709. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  34710. //-90 DEG in X, precalculated
  34711. quaternion = quaternion.multiply(this._minus90X);
  34712. //Invert! (Precalculated, 90 deg in X)
  34713. //No need to clone. this will never change.
  34714. impostor.setDeltaRotation(this._plus90X);
  34715. }
  34716. //If it is a heightfield, if should be centered.
  34717. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  34718. var mesh = object;
  34719. //calculate the correct body position:
  34720. var rotationQuaternion = mesh.rotationQuaternion;
  34721. mesh.rotationQuaternion = this._tmpUnityRotation;
  34722. mesh.computeWorldMatrix(true);
  34723. //get original center with no rotation
  34724. var c = center.clone();
  34725. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  34726. //rotation is back
  34727. mesh.rotationQuaternion = rotationQuaternion;
  34728. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  34729. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  34730. mesh.setPivotMatrix(p);
  34731. mesh.computeWorldMatrix(true);
  34732. //calculate the translation
  34733. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  34734. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  34735. //add it inverted to the delta
  34736. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  34737. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  34738. mesh.setPivotMatrix(oldPivot);
  34739. mesh.computeWorldMatrix(true);
  34740. }
  34741. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  34742. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  34743. this._tmpPosition.copyFrom(object.position);
  34744. }
  34745. impostor.setDeltaPosition(this._tmpDeltaPosition);
  34746. //Now update the impostor object
  34747. impostor.physicsBody.position.copy(this._tmpPosition);
  34748. impostor.physicsBody.quaternion.copy(quaternion);
  34749. };
  34750. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  34751. impostor.object.position.copyFrom(impostor.physicsBody.position);
  34752. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  34753. };
  34754. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  34755. impostor.physicsBody.position.copy(newPosition);
  34756. impostor.physicsBody.quaternion.copy(newRotation);
  34757. };
  34758. CannonJSPlugin.prototype.isSupported = function () {
  34759. return window.CANNON !== undefined;
  34760. };
  34761. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  34762. impostor.physicsBody.velocity.copy(velocity);
  34763. };
  34764. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  34765. impostor.physicsBody.angularVelocity.copy(velocity);
  34766. };
  34767. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  34768. var v = impostor.physicsBody.velocity;
  34769. if (!v)
  34770. return null;
  34771. return new BABYLON.Vector3(v.x, v.y, v.z);
  34772. };
  34773. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  34774. var v = impostor.physicsBody.angularVelocity;
  34775. if (!v)
  34776. return null;
  34777. return new BABYLON.Vector3(v.x, v.y, v.z);
  34778. };
  34779. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  34780. impostor.physicsBody.mass = mass;
  34781. impostor.physicsBody.updateMassProperties();
  34782. };
  34783. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  34784. impostor.physicsBody.sleep();
  34785. };
  34786. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  34787. impostor.physicsBody.wakeUp();
  34788. };
  34789. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  34790. joint.physicsJoint.distance = maxDistance;
  34791. };
  34792. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  34793. if (!motorIndex) {
  34794. joint.physicsJoint.enableMotor();
  34795. }
  34796. };
  34797. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  34798. if (!motorIndex) {
  34799. joint.physicsJoint.disableMotor();
  34800. }
  34801. };
  34802. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  34803. if (!motorIndex) {
  34804. joint.physicsJoint.enableMotor();
  34805. joint.physicsJoint.setMotorSpeed(speed);
  34806. if (maxForce) {
  34807. this.setLimit(joint, maxForce);
  34808. }
  34809. }
  34810. };
  34811. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  34812. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  34813. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  34814. };
  34815. CannonJSPlugin.prototype.dispose = function () {
  34816. //nothing to do, actually.
  34817. };
  34818. return CannonJSPlugin;
  34819. }());
  34820. BABYLON.CannonJSPlugin = CannonJSPlugin;
  34821. })(BABYLON || (BABYLON = {}));
  34822. var BABYLON;
  34823. (function (BABYLON) {
  34824. var OimoJSPlugin = (function () {
  34825. function OimoJSPlugin(iterations) {
  34826. this.name = "OimoJSPlugin";
  34827. this._tmpImpostorsArray = [];
  34828. this._tmpPositionVector = BABYLON.Vector3.Zero();
  34829. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  34830. this.world.clear();
  34831. //making sure no stats are calculated
  34832. this.world.isNoStat = true;
  34833. }
  34834. OimoJSPlugin.prototype.setGravity = function (gravity) {
  34835. this.world.gravity.copy(gravity);
  34836. };
  34837. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  34838. this.world.timeStep = timeStep;
  34839. };
  34840. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  34841. var _this = this;
  34842. impostors.forEach(function (impostor) {
  34843. impostor.beforeStep();
  34844. });
  34845. this.world.step();
  34846. impostors.forEach(function (impostor) {
  34847. impostor.afterStep();
  34848. //update the ordered impostors array
  34849. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  34850. });
  34851. //check for collisions
  34852. var contact = this.world.contacts;
  34853. while (contact !== null) {
  34854. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  34855. contact = contact.next;
  34856. continue;
  34857. }
  34858. //is this body colliding with any other? get the impostor
  34859. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  34860. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  34861. if (!mainImpostor || !collidingImpostor) {
  34862. contact = contact.next;
  34863. continue;
  34864. }
  34865. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  34866. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  34867. contact = contact.next;
  34868. }
  34869. };
  34870. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34871. var mass = impostor.physicsBody.massInfo.mass;
  34872. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  34873. };
  34874. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34875. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  34876. this.applyImpulse(impostor, force, contactPoint);
  34877. };
  34878. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34879. var _this = this;
  34880. //parent-child relationship. Does this impostor has a parent impostor?
  34881. if (impostor.parent) {
  34882. if (impostor.physicsBody) {
  34883. this.removePhysicsBody(impostor);
  34884. //TODO is that needed?
  34885. impostor.forceUpdate();
  34886. }
  34887. return;
  34888. }
  34889. if (impostor.isBodyInitRequired()) {
  34890. var bodyConfig = {
  34891. name: impostor.uniqueId,
  34892. //Oimo must have mass, also for static objects.
  34893. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  34894. size: [],
  34895. type: [],
  34896. pos: [],
  34897. rot: [],
  34898. move: impostor.getParam("mass") !== 0,
  34899. //Supporting older versions of Oimo
  34900. world: this.world
  34901. };
  34902. var impostors = [impostor];
  34903. function addToArray(parent) {
  34904. if (!parent.getChildMeshes)
  34905. return;
  34906. parent.getChildMeshes().forEach(function (m) {
  34907. if (m.physicsImpostor) {
  34908. impostors.push(m.physicsImpostor);
  34909. m.physicsImpostor._init();
  34910. }
  34911. });
  34912. }
  34913. addToArray(impostor.object);
  34914. function checkWithEpsilon(value) {
  34915. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  34916. }
  34917. impostors.forEach(function (i) {
  34918. //get the correct bounding box
  34919. var oldQuaternion = i.object.rotationQuaternion;
  34920. var rot = new OIMO.Euler().setFromQuaternion({
  34921. x: impostor.object.rotationQuaternion.x,
  34922. y: impostor.object.rotationQuaternion.y,
  34923. z: impostor.object.rotationQuaternion.z,
  34924. s: impostor.object.rotationQuaternion.w });
  34925. var extendSize = i.getObjectExtendSize();
  34926. if (i === impostor) {
  34927. var center = impostor.getObjectCenter();
  34928. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  34929. //Can also use Array.prototype.push.apply
  34930. bodyConfig.pos.push(center.x);
  34931. bodyConfig.pos.push(center.y);
  34932. bodyConfig.pos.push(center.z);
  34933. //tmp solution
  34934. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  34935. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  34936. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  34937. }
  34938. else {
  34939. bodyConfig.pos.push(i.object.position.x);
  34940. bodyConfig.pos.push(i.object.position.y);
  34941. bodyConfig.pos.push(i.object.position.z);
  34942. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  34943. bodyConfig.rot.push(0);
  34944. bodyConfig.rot.push(0);
  34945. bodyConfig.rot.push(0);
  34946. }
  34947. // register mesh
  34948. switch (i.type) {
  34949. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34950. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  34951. case BABYLON.PhysicsImpostor.SphereImpostor:
  34952. var radiusX = extendSize.x;
  34953. var radiusY = extendSize.y;
  34954. var radiusZ = extendSize.z;
  34955. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  34956. bodyConfig.type.push('sphere');
  34957. //due to the way oimo works with compounds, add 3 times
  34958. bodyConfig.size.push(size);
  34959. bodyConfig.size.push(size);
  34960. bodyConfig.size.push(size);
  34961. break;
  34962. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34963. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  34964. var sizeY = checkWithEpsilon(extendSize.y);
  34965. bodyConfig.type.push('cylinder');
  34966. bodyConfig.size.push(sizeX);
  34967. bodyConfig.size.push(sizeY);
  34968. //due to the way oimo works with compounds, add one more value.
  34969. bodyConfig.size.push(sizeY);
  34970. break;
  34971. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34972. case BABYLON.PhysicsImpostor.BoxImpostor:
  34973. default:
  34974. var sizeX = checkWithEpsilon(extendSize.x);
  34975. var sizeY = checkWithEpsilon(extendSize.y);
  34976. var sizeZ = checkWithEpsilon(extendSize.z);
  34977. bodyConfig.type.push('box');
  34978. bodyConfig.size.push(sizeX);
  34979. bodyConfig.size.push(sizeY);
  34980. bodyConfig.size.push(sizeZ);
  34981. break;
  34982. }
  34983. //actually not needed, but hey...
  34984. i.object.rotationQuaternion = oldQuaternion;
  34985. });
  34986. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  34987. }
  34988. else {
  34989. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  34990. }
  34991. impostor.setDeltaPosition(this._tmpPositionVector);
  34992. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  34993. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  34994. };
  34995. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34996. //impostor.physicsBody.dispose();
  34997. //Same as : (older oimo versions)
  34998. this.world.removeRigidBody(impostor.physicsBody);
  34999. };
  35000. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35001. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35002. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35003. if (!mainBody || !connectedBody) {
  35004. return;
  35005. }
  35006. var jointData = impostorJoint.joint.jointData;
  35007. var options = jointData.nativeParams || {};
  35008. var type;
  35009. var nativeJointData = {
  35010. body1: mainBody,
  35011. body2: connectedBody,
  35012. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  35013. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  35014. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  35015. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  35016. min: options.min,
  35017. max: options.max,
  35018. collision: options.collision || jointData.collision,
  35019. spring: options.spring,
  35020. //supporting older version of Oimo
  35021. world: this.world
  35022. };
  35023. switch (impostorJoint.joint.type) {
  35024. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35025. type = "jointBall";
  35026. break;
  35027. case BABYLON.PhysicsJoint.SpringJoint:
  35028. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  35029. var springData = jointData;
  35030. nativeJointData.min = springData.length || nativeJointData.min;
  35031. //Max should also be set, just make sure it is at least min
  35032. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  35033. case BABYLON.PhysicsJoint.DistanceJoint:
  35034. type = "jointDistance";
  35035. nativeJointData.max = jointData.maxDistance;
  35036. break;
  35037. case BABYLON.PhysicsJoint.PrismaticJoint:
  35038. type = "jointPrisme";
  35039. break;
  35040. case BABYLON.PhysicsJoint.SliderJoint:
  35041. type = "jointSlide";
  35042. break;
  35043. case BABYLON.PhysicsJoint.WheelJoint:
  35044. type = "jointWheel";
  35045. break;
  35046. case BABYLON.PhysicsJoint.HingeJoint:
  35047. default:
  35048. type = "jointHinge";
  35049. break;
  35050. }
  35051. nativeJointData.type = type;
  35052. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  35053. };
  35054. OimoJSPlugin.prototype.removeJoint = function (joint) {
  35055. joint.joint.physicsJoint.dispose();
  35056. };
  35057. OimoJSPlugin.prototype.isSupported = function () {
  35058. return OIMO !== undefined;
  35059. };
  35060. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35061. if (!impostor.physicsBody.sleeping) {
  35062. //TODO check that
  35063. if (impostor.physicsBody.shapes.next) {
  35064. var parentShape = this._getLastShape(impostor.physicsBody);
  35065. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  35066. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  35067. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  35068. }
  35069. else {
  35070. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  35071. }
  35072. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  35073. }
  35074. };
  35075. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35076. var body = impostor.physicsBody;
  35077. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  35078. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  35079. body.syncShapes();
  35080. body.awake();
  35081. };
  35082. OimoJSPlugin.prototype._getLastShape = function (body) {
  35083. var lastShape = body.shapes;
  35084. while (lastShape.next) {
  35085. lastShape = lastShape.next;
  35086. }
  35087. return lastShape;
  35088. };
  35089. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35090. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  35091. };
  35092. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35093. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  35094. };
  35095. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35096. var v = impostor.physicsBody.linearVelocity;
  35097. if (!v)
  35098. return null;
  35099. return new BABYLON.Vector3(v.x, v.y, v.z);
  35100. };
  35101. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35102. var v = impostor.physicsBody.angularVelocity;
  35103. if (!v)
  35104. return null;
  35105. return new BABYLON.Vector3(v.x, v.y, v.z);
  35106. };
  35107. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35108. var staticBody = mass === 0;
  35109. //this will actually set the body's density and not its mass.
  35110. //But this is how oimo treats the mass variable.
  35111. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  35112. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  35113. };
  35114. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  35115. impostor.physicsBody.sleep();
  35116. };
  35117. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  35118. impostor.physicsBody.awake();
  35119. };
  35120. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35121. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  35122. if (minDistance !== void 0) {
  35123. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  35124. }
  35125. };
  35126. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35127. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35128. if (motor) {
  35129. motor.setMotor(speed, maxForce);
  35130. }
  35131. };
  35132. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  35133. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35134. if (motor) {
  35135. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  35136. }
  35137. };
  35138. OimoJSPlugin.prototype.dispose = function () {
  35139. this.world.clear();
  35140. };
  35141. return OimoJSPlugin;
  35142. }());
  35143. BABYLON.OimoJSPlugin = OimoJSPlugin;
  35144. })(BABYLON || (BABYLON = {}));
  35145. var BABYLON;
  35146. (function (BABYLON) {
  35147. var DisplayPassPostProcess = (function (_super) {
  35148. __extends(DisplayPassPostProcess, _super);
  35149. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35150. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  35151. }
  35152. return DisplayPassPostProcess;
  35153. }(BABYLON.PostProcess));
  35154. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  35155. })(BABYLON || (BABYLON = {}));
  35156. var BABYLON;
  35157. (function (BABYLON) {
  35158. var SimplificationSettings = (function () {
  35159. function SimplificationSettings(quality, distance, optimizeMesh) {
  35160. this.quality = quality;
  35161. this.distance = distance;
  35162. this.optimizeMesh = optimizeMesh;
  35163. }
  35164. return SimplificationSettings;
  35165. }());
  35166. BABYLON.SimplificationSettings = SimplificationSettings;
  35167. var SimplificationQueue = (function () {
  35168. function SimplificationQueue() {
  35169. this.running = false;
  35170. this._simplificationArray = [];
  35171. }
  35172. SimplificationQueue.prototype.addTask = function (task) {
  35173. this._simplificationArray.push(task);
  35174. };
  35175. SimplificationQueue.prototype.executeNext = function () {
  35176. var task = this._simplificationArray.pop();
  35177. if (task) {
  35178. this.running = true;
  35179. this.runSimplification(task);
  35180. }
  35181. else {
  35182. this.running = false;
  35183. }
  35184. };
  35185. SimplificationQueue.prototype.runSimplification = function (task) {
  35186. var _this = this;
  35187. if (task.parallelProcessing) {
  35188. //parallel simplifier
  35189. task.settings.forEach(function (setting) {
  35190. var simplifier = _this.getSimplifier(task);
  35191. simplifier.simplify(setting, function (newMesh) {
  35192. task.mesh.addLODLevel(setting.distance, newMesh);
  35193. newMesh.isVisible = true;
  35194. //check if it is the last
  35195. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  35196. //all done, run the success callback.
  35197. task.successCallback();
  35198. }
  35199. _this.executeNext();
  35200. });
  35201. });
  35202. }
  35203. else {
  35204. //single simplifier.
  35205. var simplifier = this.getSimplifier(task);
  35206. var runDecimation = function (setting, callback) {
  35207. simplifier.simplify(setting, function (newMesh) {
  35208. task.mesh.addLODLevel(setting.distance, newMesh);
  35209. newMesh.isVisible = true;
  35210. //run the next quality level
  35211. callback();
  35212. });
  35213. };
  35214. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  35215. runDecimation(task.settings[loop.index], function () {
  35216. loop.executeNext();
  35217. });
  35218. }, function () {
  35219. //execution ended, run the success callback.
  35220. if (task.successCallback) {
  35221. task.successCallback();
  35222. }
  35223. _this.executeNext();
  35224. });
  35225. }
  35226. };
  35227. SimplificationQueue.prototype.getSimplifier = function (task) {
  35228. switch (task.simplificationType) {
  35229. case SimplificationType.QUADRATIC:
  35230. default:
  35231. return new QuadraticErrorSimplification(task.mesh);
  35232. }
  35233. };
  35234. return SimplificationQueue;
  35235. }());
  35236. BABYLON.SimplificationQueue = SimplificationQueue;
  35237. /**
  35238. * The implemented types of simplification.
  35239. * At the moment only Quadratic Error Decimation is implemented.
  35240. */
  35241. (function (SimplificationType) {
  35242. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  35243. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  35244. var SimplificationType = BABYLON.SimplificationType;
  35245. var DecimationTriangle = (function () {
  35246. function DecimationTriangle(vertices) {
  35247. this.vertices = vertices;
  35248. this.error = new Array(4);
  35249. this.deleted = false;
  35250. this.isDirty = false;
  35251. this.deletePending = false;
  35252. this.borderFactor = 0;
  35253. }
  35254. return DecimationTriangle;
  35255. }());
  35256. BABYLON.DecimationTriangle = DecimationTriangle;
  35257. var DecimationVertex = (function () {
  35258. function DecimationVertex(position, id) {
  35259. this.position = position;
  35260. this.id = id;
  35261. this.isBorder = true;
  35262. this.q = new QuadraticMatrix();
  35263. this.triangleCount = 0;
  35264. this.triangleStart = 0;
  35265. this.originalOffsets = [];
  35266. }
  35267. DecimationVertex.prototype.updatePosition = function (newPosition) {
  35268. this.position.copyFrom(newPosition);
  35269. };
  35270. return DecimationVertex;
  35271. }());
  35272. BABYLON.DecimationVertex = DecimationVertex;
  35273. var QuadraticMatrix = (function () {
  35274. function QuadraticMatrix(data) {
  35275. this.data = new Array(10);
  35276. for (var i = 0; i < 10; ++i) {
  35277. if (data && data[i]) {
  35278. this.data[i] = data[i];
  35279. }
  35280. else {
  35281. this.data[i] = 0;
  35282. }
  35283. }
  35284. }
  35285. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  35286. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  35287. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  35288. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  35289. return det;
  35290. };
  35291. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  35292. for (var i = 0; i < 10; ++i) {
  35293. this.data[i] += matrix.data[i];
  35294. }
  35295. };
  35296. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  35297. for (var i = 0; i < 10; ++i) {
  35298. this.data[i] += data[i];
  35299. }
  35300. };
  35301. QuadraticMatrix.prototype.add = function (matrix) {
  35302. var m = new QuadraticMatrix();
  35303. for (var i = 0; i < 10; ++i) {
  35304. m.data[i] = this.data[i] + matrix.data[i];
  35305. }
  35306. return m;
  35307. };
  35308. QuadraticMatrix.FromData = function (a, b, c, d) {
  35309. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  35310. };
  35311. //returning an array to avoid garbage collection
  35312. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  35313. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  35314. };
  35315. return QuadraticMatrix;
  35316. }());
  35317. BABYLON.QuadraticMatrix = QuadraticMatrix;
  35318. var Reference = (function () {
  35319. function Reference(vertexId, triangleId) {
  35320. this.vertexId = vertexId;
  35321. this.triangleId = triangleId;
  35322. }
  35323. return Reference;
  35324. }());
  35325. BABYLON.Reference = Reference;
  35326. /**
  35327. * An implementation of the Quadratic Error simplification algorithm.
  35328. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  35329. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  35330. * @author RaananW
  35331. */
  35332. var QuadraticErrorSimplification = (function () {
  35333. function QuadraticErrorSimplification(_mesh) {
  35334. this._mesh = _mesh;
  35335. this.initialized = false;
  35336. this.syncIterations = 5000;
  35337. this.aggressiveness = 7;
  35338. this.decimationIterations = 100;
  35339. this.boundingBoxEpsilon = BABYLON.Epsilon;
  35340. }
  35341. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  35342. var _this = this;
  35343. this.initDecimatedMesh();
  35344. //iterating through the submeshes array, one after the other.
  35345. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  35346. _this.initWithMesh(loop.index, function () {
  35347. _this.runDecimation(settings, loop.index, function () {
  35348. loop.executeNext();
  35349. });
  35350. }, settings.optimizeMesh);
  35351. }, function () {
  35352. setTimeout(function () {
  35353. successCallback(_this._reconstructedMesh);
  35354. }, 0);
  35355. });
  35356. };
  35357. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  35358. var _this = this;
  35359. var gCount = 0;
  35360. triangle.vertices.forEach(function (vertex) {
  35361. var count = 0;
  35362. var vPos = vertex.position;
  35363. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  35364. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  35365. ++count;
  35366. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  35367. ++count;
  35368. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  35369. ++count;
  35370. if (count > 1) {
  35371. ++gCount;
  35372. }
  35373. ;
  35374. });
  35375. if (gCount > 1) {
  35376. console.log(triangle, gCount);
  35377. }
  35378. return gCount > 1;
  35379. };
  35380. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  35381. var _this = this;
  35382. var targetCount = ~~(this.triangles.length * settings.quality);
  35383. var deletedTriangles = 0;
  35384. var triangleCount = this.triangles.length;
  35385. var iterationFunction = function (iteration, callback) {
  35386. setTimeout(function () {
  35387. if (iteration % 5 === 0) {
  35388. _this.updateMesh(iteration === 0);
  35389. }
  35390. for (var i = 0; i < _this.triangles.length; ++i) {
  35391. _this.triangles[i].isDirty = false;
  35392. }
  35393. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  35394. var trianglesIterator = function (i) {
  35395. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  35396. var t = _this.triangles[tIdx];
  35397. if (!t)
  35398. return;
  35399. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  35400. return;
  35401. }
  35402. for (var j = 0; j < 3; ++j) {
  35403. if (t.error[j] < threshold) {
  35404. var deleted0 = [];
  35405. var deleted1 = [];
  35406. var v0 = t.vertices[j];
  35407. var v1 = t.vertices[(j + 1) % 3];
  35408. if (v0.isBorder !== v1.isBorder)
  35409. continue;
  35410. var p = BABYLON.Vector3.Zero();
  35411. var n = BABYLON.Vector3.Zero();
  35412. var uv = BABYLON.Vector2.Zero();
  35413. var color = new BABYLON.Color4(0, 0, 0, 1);
  35414. _this.calculateError(v0, v1, p, n, uv, color);
  35415. var delTr = [];
  35416. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  35417. continue;
  35418. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  35419. continue;
  35420. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  35421. continue;
  35422. var uniqueArray = [];
  35423. delTr.forEach(function (deletedT) {
  35424. if (uniqueArray.indexOf(deletedT) === -1) {
  35425. deletedT.deletePending = true;
  35426. uniqueArray.push(deletedT);
  35427. }
  35428. });
  35429. if (uniqueArray.length % 2 !== 0) {
  35430. continue;
  35431. }
  35432. v0.q = v1.q.add(v0.q);
  35433. v0.updatePosition(p);
  35434. var tStart = _this.references.length;
  35435. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  35436. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  35437. var tCount = _this.references.length - tStart;
  35438. if (tCount <= v0.triangleCount) {
  35439. if (tCount) {
  35440. for (var c = 0; c < tCount; c++) {
  35441. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  35442. }
  35443. }
  35444. }
  35445. else {
  35446. v0.triangleStart = tStart;
  35447. }
  35448. v0.triangleCount = tCount;
  35449. break;
  35450. }
  35451. }
  35452. };
  35453. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  35454. }, 0);
  35455. };
  35456. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  35457. if (triangleCount - deletedTriangles <= targetCount)
  35458. loop.breakLoop();
  35459. else {
  35460. iterationFunction(loop.index, function () {
  35461. loop.executeNext();
  35462. });
  35463. }
  35464. }, function () {
  35465. setTimeout(function () {
  35466. //reconstruct this part of the mesh
  35467. _this.reconstructMesh(submeshIndex);
  35468. successCallback();
  35469. }, 0);
  35470. });
  35471. };
  35472. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  35473. var _this = this;
  35474. this.vertices = [];
  35475. this.triangles = [];
  35476. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35477. var indices = this._mesh.getIndices();
  35478. var submesh = this._mesh.subMeshes[submeshIndex];
  35479. var findInVertices = function (positionToSearch) {
  35480. if (optimizeMesh) {
  35481. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  35482. if (_this.vertices[ii].position.equals(positionToSearch)) {
  35483. return _this.vertices[ii];
  35484. }
  35485. }
  35486. }
  35487. return null;
  35488. };
  35489. var vertexReferences = [];
  35490. var vertexInit = function (i) {
  35491. var offset = i + submesh.verticesStart;
  35492. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  35493. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  35494. vertex.originalOffsets.push(offset);
  35495. if (vertex.id === _this.vertices.length) {
  35496. _this.vertices.push(vertex);
  35497. }
  35498. vertexReferences.push(vertex.id);
  35499. };
  35500. //var totalVertices = mesh.getTotalVertices();
  35501. var totalVertices = submesh.verticesCount;
  35502. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  35503. var indicesInit = function (i) {
  35504. var offset = (submesh.indexStart / 3) + i;
  35505. var pos = (offset * 3);
  35506. var i0 = indices[pos + 0];
  35507. var i1 = indices[pos + 1];
  35508. var i2 = indices[pos + 2];
  35509. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  35510. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  35511. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  35512. var triangle = new DecimationTriangle([v0, v1, v2]);
  35513. triangle.originalOffset = pos;
  35514. _this.triangles.push(triangle);
  35515. };
  35516. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  35517. _this.init(callback);
  35518. });
  35519. });
  35520. };
  35521. QuadraticErrorSimplification.prototype.init = function (callback) {
  35522. var _this = this;
  35523. var triangleInit1 = function (i) {
  35524. var t = _this.triangles[i];
  35525. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  35526. for (var j = 0; j < 3; j++) {
  35527. 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))));
  35528. }
  35529. };
  35530. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  35531. var triangleInit2 = function (i) {
  35532. var t = _this.triangles[i];
  35533. for (var j = 0; j < 3; ++j) {
  35534. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  35535. }
  35536. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35537. };
  35538. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  35539. _this.initialized = true;
  35540. callback();
  35541. });
  35542. });
  35543. };
  35544. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  35545. var newTriangles = [];
  35546. var i;
  35547. for (i = 0; i < this.vertices.length; ++i) {
  35548. this.vertices[i].triangleCount = 0;
  35549. }
  35550. var t;
  35551. var j;
  35552. for (i = 0; i < this.triangles.length; ++i) {
  35553. if (!this.triangles[i].deleted) {
  35554. t = this.triangles[i];
  35555. for (j = 0; j < 3; ++j) {
  35556. t.vertices[j].triangleCount = 1;
  35557. }
  35558. newTriangles.push(t);
  35559. }
  35560. }
  35561. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  35562. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  35563. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  35564. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  35565. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35566. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35567. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35568. var vertexCount = 0;
  35569. for (i = 0; i < this.vertices.length; ++i) {
  35570. var vertex = this.vertices[i];
  35571. vertex.id = vertexCount;
  35572. if (vertex.triangleCount) {
  35573. vertex.originalOffsets.forEach(function (originalOffset) {
  35574. newPositionData.push(vertex.position.x);
  35575. newPositionData.push(vertex.position.y);
  35576. newPositionData.push(vertex.position.z);
  35577. newNormalData.push(normalData[originalOffset * 3]);
  35578. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  35579. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  35580. if (uvs && uvs.length) {
  35581. newUVsData.push(uvs[(originalOffset * 2)]);
  35582. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  35583. }
  35584. else if (colorsData && colorsData.length) {
  35585. newColorsData.push(colorsData[(originalOffset * 4)]);
  35586. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  35587. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  35588. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  35589. }
  35590. ++vertexCount;
  35591. });
  35592. }
  35593. }
  35594. var startingIndex = this._reconstructedMesh.getTotalIndices();
  35595. var startingVertex = this._reconstructedMesh.getTotalVertices();
  35596. var submeshesArray = this._reconstructedMesh.subMeshes;
  35597. this._reconstructedMesh.subMeshes = [];
  35598. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  35599. var originalIndices = this._mesh.getIndices();
  35600. for (i = 0; i < newTriangles.length; ++i) {
  35601. t = newTriangles[i]; //now get the new referencing point for each vertex
  35602. [0, 1, 2].forEach(function (idx) {
  35603. var id = originalIndices[t.originalOffset + idx];
  35604. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  35605. if (offset < 0)
  35606. offset = 0;
  35607. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  35608. });
  35609. }
  35610. //overwriting the old vertex buffers and indices.
  35611. this._reconstructedMesh.setIndices(newIndicesArray);
  35612. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  35613. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  35614. if (newUVsData.length > 0)
  35615. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  35616. if (newColorsData.length > 0)
  35617. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  35618. //create submesh
  35619. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  35620. if (submeshIndex > 0) {
  35621. this._reconstructedMesh.subMeshes = [];
  35622. submeshesArray.forEach(function (submesh) {
  35623. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  35624. });
  35625. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  35626. }
  35627. };
  35628. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  35629. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  35630. this._reconstructedMesh.material = this._mesh.material;
  35631. this._reconstructedMesh.parent = this._mesh.parent;
  35632. this._reconstructedMesh.isVisible = false;
  35633. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  35634. };
  35635. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  35636. for (var i = 0; i < vertex1.triangleCount; ++i) {
  35637. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  35638. if (t.deleted)
  35639. continue;
  35640. var s = this.references[vertex1.triangleStart + i].vertexId;
  35641. var v1 = t.vertices[(s + 1) % 3];
  35642. var v2 = t.vertices[(s + 2) % 3];
  35643. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  35644. deletedArray[i] = true;
  35645. delTr.push(t);
  35646. continue;
  35647. }
  35648. var d1 = v1.position.subtract(point);
  35649. d1 = d1.normalize();
  35650. var d2 = v2.position.subtract(point);
  35651. d2 = d2.normalize();
  35652. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  35653. return true;
  35654. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  35655. deletedArray[i] = false;
  35656. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  35657. return true;
  35658. }
  35659. return false;
  35660. };
  35661. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  35662. var newDeleted = deletedTriangles;
  35663. for (var i = 0; i < vertex.triangleCount; ++i) {
  35664. var ref = this.references[vertex.triangleStart + i];
  35665. var t = this.triangles[ref.triangleId];
  35666. if (t.deleted)
  35667. continue;
  35668. if (deletedArray[i] && t.deletePending) {
  35669. t.deleted = true;
  35670. newDeleted++;
  35671. continue;
  35672. }
  35673. t.vertices[ref.vertexId] = origVertex;
  35674. t.isDirty = true;
  35675. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  35676. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  35677. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  35678. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35679. this.references.push(ref);
  35680. }
  35681. return newDeleted;
  35682. };
  35683. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  35684. for (var i = 0; i < this.vertices.length; ++i) {
  35685. var vCount = [];
  35686. var vId = [];
  35687. var v = this.vertices[i];
  35688. var j;
  35689. for (j = 0; j < v.triangleCount; ++j) {
  35690. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  35691. for (var ii = 0; ii < 3; ii++) {
  35692. var ofs = 0;
  35693. var vv = triangle.vertices[ii];
  35694. while (ofs < vCount.length) {
  35695. if (vId[ofs] === vv.id)
  35696. break;
  35697. ++ofs;
  35698. }
  35699. if (ofs === vCount.length) {
  35700. vCount.push(1);
  35701. vId.push(vv.id);
  35702. }
  35703. else {
  35704. vCount[ofs]++;
  35705. }
  35706. }
  35707. }
  35708. for (j = 0; j < vCount.length; ++j) {
  35709. if (vCount[j] === 1) {
  35710. this.vertices[vId[j]].isBorder = true;
  35711. }
  35712. else {
  35713. this.vertices[vId[j]].isBorder = false;
  35714. }
  35715. }
  35716. }
  35717. };
  35718. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  35719. if (identifyBorders === void 0) { identifyBorders = false; }
  35720. var i;
  35721. if (!identifyBorders) {
  35722. var newTrianglesVector = [];
  35723. for (i = 0; i < this.triangles.length; ++i) {
  35724. if (!this.triangles[i].deleted) {
  35725. newTrianglesVector.push(this.triangles[i]);
  35726. }
  35727. }
  35728. this.triangles = newTrianglesVector;
  35729. }
  35730. for (i = 0; i < this.vertices.length; ++i) {
  35731. this.vertices[i].triangleCount = 0;
  35732. this.vertices[i].triangleStart = 0;
  35733. }
  35734. var t;
  35735. var j;
  35736. var v;
  35737. for (i = 0; i < this.triangles.length; ++i) {
  35738. t = this.triangles[i];
  35739. for (j = 0; j < 3; ++j) {
  35740. v = t.vertices[j];
  35741. v.triangleCount++;
  35742. }
  35743. }
  35744. var tStart = 0;
  35745. for (i = 0; i < this.vertices.length; ++i) {
  35746. this.vertices[i].triangleStart = tStart;
  35747. tStart += this.vertices[i].triangleCount;
  35748. this.vertices[i].triangleCount = 0;
  35749. }
  35750. var newReferences = new Array(this.triangles.length * 3);
  35751. for (i = 0; i < this.triangles.length; ++i) {
  35752. t = this.triangles[i];
  35753. for (j = 0; j < 3; ++j) {
  35754. v = t.vertices[j];
  35755. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  35756. v.triangleCount++;
  35757. }
  35758. }
  35759. this.references = newReferences;
  35760. if (identifyBorders) {
  35761. this.identifyBorder();
  35762. }
  35763. };
  35764. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  35765. var x = point.x;
  35766. var y = point.y;
  35767. var z = point.z;
  35768. 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
  35769. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  35770. };
  35771. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  35772. var q = vertex1.q.add(vertex2.q);
  35773. var border = vertex1.isBorder && vertex2.isBorder;
  35774. var error = 0;
  35775. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  35776. if (qDet !== 0 && !border) {
  35777. if (!pointResult) {
  35778. pointResult = BABYLON.Vector3.Zero();
  35779. }
  35780. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  35781. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  35782. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  35783. error = this.vertexError(q, pointResult);
  35784. }
  35785. else {
  35786. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  35787. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  35788. var error1 = this.vertexError(q, vertex1.position);
  35789. var error2 = this.vertexError(q, vertex2.position);
  35790. var error3 = this.vertexError(q, p3);
  35791. error = Math.min(error1, error2, error3);
  35792. if (error === error1) {
  35793. if (pointResult) {
  35794. pointResult.copyFrom(vertex1.position);
  35795. }
  35796. }
  35797. else if (error === error2) {
  35798. if (pointResult) {
  35799. pointResult.copyFrom(vertex2.position);
  35800. }
  35801. }
  35802. else {
  35803. if (pointResult) {
  35804. pointResult.copyFrom(p3);
  35805. }
  35806. }
  35807. }
  35808. return error;
  35809. };
  35810. return QuadraticErrorSimplification;
  35811. }());
  35812. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  35813. })(BABYLON || (BABYLON = {}));
  35814. var BABYLON;
  35815. (function (BABYLON) {
  35816. var serializedGeometries = [];
  35817. var serializeGeometry = function (geometry, serializationGeometries) {
  35818. if (serializedGeometries[geometry.id]) {
  35819. return;
  35820. }
  35821. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  35822. serializationGeometries.boxes.push(geometry.serialize());
  35823. }
  35824. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  35825. serializationGeometries.spheres.push(geometry.serialize());
  35826. }
  35827. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  35828. serializationGeometries.cylinders.push(geometry.serialize());
  35829. }
  35830. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  35831. serializationGeometries.toruses.push(geometry.serialize());
  35832. }
  35833. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  35834. serializationGeometries.grounds.push(geometry.serialize());
  35835. }
  35836. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  35837. serializationGeometries.planes.push(geometry.serialize());
  35838. }
  35839. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  35840. serializationGeometries.torusKnots.push(geometry.serialize());
  35841. }
  35842. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  35843. throw new Error("Unknown primitive type");
  35844. }
  35845. else {
  35846. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  35847. }
  35848. serializedGeometries[geometry.id] = true;
  35849. };
  35850. var serializeMesh = function (mesh, serializationScene) {
  35851. var serializationObject = {};
  35852. serializationObject.name = mesh.name;
  35853. serializationObject.id = mesh.id;
  35854. if (BABYLON.Tags.HasTags(mesh)) {
  35855. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  35856. }
  35857. serializationObject.position = mesh.position.asArray();
  35858. if (mesh.rotationQuaternion) {
  35859. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  35860. }
  35861. else if (mesh.rotation) {
  35862. serializationObject.rotation = mesh.rotation.asArray();
  35863. }
  35864. serializationObject.scaling = mesh.scaling.asArray();
  35865. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  35866. serializationObject.isEnabled = mesh.isEnabled();
  35867. serializationObject.isVisible = mesh.isVisible;
  35868. serializationObject.infiniteDistance = mesh.infiniteDistance;
  35869. serializationObject.pickable = mesh.isPickable;
  35870. serializationObject.receiveShadows = mesh.receiveShadows;
  35871. serializationObject.billboardMode = mesh.billboardMode;
  35872. serializationObject.visibility = mesh.visibility;
  35873. serializationObject.checkCollisions = mesh.checkCollisions;
  35874. // Parent
  35875. if (mesh.parent) {
  35876. serializationObject.parentId = mesh.parent.id;
  35877. }
  35878. // Geometry
  35879. var geometry = mesh._geometry;
  35880. if (geometry) {
  35881. var geometryId = geometry.id;
  35882. serializationObject.geometryId = geometryId;
  35883. if (!mesh.getScene().getGeometryByID(geometryId)) {
  35884. // 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
  35885. serializeGeometry(geometry, serializationScene.geometries);
  35886. }
  35887. // SubMeshes
  35888. serializationObject.subMeshes = [];
  35889. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35890. var subMesh = mesh.subMeshes[subIndex];
  35891. serializationObject.subMeshes.push({
  35892. materialIndex: subMesh.materialIndex,
  35893. verticesStart: subMesh.verticesStart,
  35894. verticesCount: subMesh.verticesCount,
  35895. indexStart: subMesh.indexStart,
  35896. indexCount: subMesh.indexCount
  35897. });
  35898. }
  35899. }
  35900. // Material
  35901. if (mesh.material) {
  35902. serializationObject.materialId = mesh.material.id;
  35903. }
  35904. else {
  35905. mesh.material = null;
  35906. }
  35907. // Skeleton
  35908. if (mesh.skeleton) {
  35909. serializationObject.skeletonId = mesh.skeleton.id;
  35910. }
  35911. // Physics
  35912. //TODO implement correct serialization for physics impostors.
  35913. if (mesh.getPhysicsImpostor()) {
  35914. serializationObject.physicsMass = mesh.getPhysicsMass();
  35915. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  35916. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  35917. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  35918. }
  35919. // Instances
  35920. serializationObject.instances = [];
  35921. for (var index = 0; index < mesh.instances.length; index++) {
  35922. var instance = mesh.instances[index];
  35923. var serializationInstance = {
  35924. name: instance.name,
  35925. position: instance.position.asArray(),
  35926. scaling: instance.scaling.asArray()
  35927. };
  35928. if (instance.rotationQuaternion) {
  35929. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  35930. }
  35931. else if (instance.rotation) {
  35932. serializationInstance.rotation = instance.rotation.asArray();
  35933. }
  35934. serializationObject.instances.push(serializationInstance);
  35935. // Animations
  35936. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  35937. serializationInstance.ranges = instance.serializeAnimationRanges();
  35938. }
  35939. // Animations
  35940. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  35941. serializationObject.ranges = mesh.serializeAnimationRanges();
  35942. // Layer mask
  35943. serializationObject.layerMask = mesh.layerMask;
  35944. return serializationObject;
  35945. };
  35946. var finalizeSingleMesh = function (mesh, serializationObject) {
  35947. //only works if the mesh is already loaded
  35948. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  35949. //serialize material
  35950. if (mesh.material) {
  35951. if (mesh.material instanceof BABYLON.StandardMaterial) {
  35952. serializationObject.materials = serializationObject.materials || [];
  35953. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  35954. serializationObject.materials.push(mesh.material.serialize());
  35955. }
  35956. }
  35957. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  35958. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  35959. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  35960. serializationObject.multiMaterials.push(mesh.material.serialize());
  35961. }
  35962. }
  35963. }
  35964. //serialize geometry
  35965. var geometry = mesh._geometry;
  35966. if (geometry) {
  35967. if (!serializationObject.geometries) {
  35968. serializationObject.geometries = {};
  35969. serializationObject.geometries.boxes = [];
  35970. serializationObject.geometries.spheres = [];
  35971. serializationObject.geometries.cylinders = [];
  35972. serializationObject.geometries.toruses = [];
  35973. serializationObject.geometries.grounds = [];
  35974. serializationObject.geometries.planes = [];
  35975. serializationObject.geometries.torusKnots = [];
  35976. serializationObject.geometries.vertexData = [];
  35977. }
  35978. serializeGeometry(geometry, serializationObject.geometries);
  35979. }
  35980. // Skeletons
  35981. if (mesh.skeleton) {
  35982. serializationObject.skeletons = serializationObject.skeletons || [];
  35983. serializationObject.skeletons.push(mesh.skeleton.serialize());
  35984. }
  35985. //serialize the actual mesh
  35986. serializationObject.meshes = serializationObject.meshes || [];
  35987. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  35988. }
  35989. };
  35990. var SceneSerializer = (function () {
  35991. function SceneSerializer() {
  35992. }
  35993. SceneSerializer.ClearCache = function () {
  35994. serializedGeometries = [];
  35995. };
  35996. SceneSerializer.Serialize = function (scene) {
  35997. var serializationObject = {};
  35998. // Scene
  35999. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  36000. serializationObject.autoClear = scene.autoClear;
  36001. serializationObject.clearColor = scene.clearColor.asArray();
  36002. serializationObject.ambientColor = scene.ambientColor.asArray();
  36003. serializationObject.gravity = scene.gravity.asArray();
  36004. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  36005. serializationObject.workerCollisions = scene.workerCollisions;
  36006. // Fog
  36007. if (scene.fogMode && scene.fogMode !== 0) {
  36008. serializationObject.fogMode = scene.fogMode;
  36009. serializationObject.fogColor = scene.fogColor.asArray();
  36010. serializationObject.fogStart = scene.fogStart;
  36011. serializationObject.fogEnd = scene.fogEnd;
  36012. serializationObject.fogDensity = scene.fogDensity;
  36013. }
  36014. //Physics
  36015. if (scene.isPhysicsEnabled()) {
  36016. serializationObject.physicsEnabled = true;
  36017. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  36018. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  36019. }
  36020. // Lights
  36021. serializationObject.lights = [];
  36022. var index;
  36023. var light;
  36024. for (index = 0; index < scene.lights.length; index++) {
  36025. light = scene.lights[index];
  36026. serializationObject.lights.push(light.serialize());
  36027. }
  36028. // Cameras
  36029. serializationObject.cameras = [];
  36030. for (index = 0; index < scene.cameras.length; index++) {
  36031. var camera = scene.cameras[index];
  36032. serializationObject.cameras.push(camera.serialize());
  36033. }
  36034. if (scene.activeCamera) {
  36035. serializationObject.activeCameraID = scene.activeCamera.id;
  36036. }
  36037. // Animations
  36038. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  36039. // Materials
  36040. serializationObject.materials = [];
  36041. serializationObject.multiMaterials = [];
  36042. var material;
  36043. for (index = 0; index < scene.materials.length; index++) {
  36044. material = scene.materials[index];
  36045. serializationObject.materials.push(material.serialize());
  36046. }
  36047. // MultiMaterials
  36048. serializationObject.multiMaterials = [];
  36049. for (index = 0; index < scene.multiMaterials.length; index++) {
  36050. var multiMaterial = scene.multiMaterials[index];
  36051. serializationObject.multiMaterials.push(multiMaterial.serialize());
  36052. }
  36053. // Skeletons
  36054. serializationObject.skeletons = [];
  36055. for (index = 0; index < scene.skeletons.length; index++) {
  36056. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  36057. }
  36058. // Geometries
  36059. serializationObject.geometries = {};
  36060. serializationObject.geometries.boxes = [];
  36061. serializationObject.geometries.spheres = [];
  36062. serializationObject.geometries.cylinders = [];
  36063. serializationObject.geometries.toruses = [];
  36064. serializationObject.geometries.grounds = [];
  36065. serializationObject.geometries.planes = [];
  36066. serializationObject.geometries.torusKnots = [];
  36067. serializationObject.geometries.vertexData = [];
  36068. serializedGeometries = [];
  36069. var geometries = scene.getGeometries();
  36070. for (index = 0; index < geometries.length; index++) {
  36071. var geometry = geometries[index];
  36072. if (geometry.isReady()) {
  36073. serializeGeometry(geometry, serializationObject.geometries);
  36074. }
  36075. }
  36076. // Meshes
  36077. serializationObject.meshes = [];
  36078. for (index = 0; index < scene.meshes.length; index++) {
  36079. var abstractMesh = scene.meshes[index];
  36080. if (abstractMesh instanceof BABYLON.Mesh) {
  36081. var mesh = abstractMesh;
  36082. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36083. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36084. }
  36085. }
  36086. }
  36087. // Particles Systems
  36088. serializationObject.particleSystems = [];
  36089. for (index = 0; index < scene.particleSystems.length; index++) {
  36090. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  36091. }
  36092. // Lens flares
  36093. serializationObject.lensFlareSystems = [];
  36094. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  36095. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  36096. }
  36097. // Shadows
  36098. serializationObject.shadowGenerators = [];
  36099. for (index = 0; index < scene.lights.length; index++) {
  36100. light = scene.lights[index];
  36101. if (light.getShadowGenerator()) {
  36102. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  36103. }
  36104. }
  36105. return serializationObject;
  36106. };
  36107. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  36108. if (withParents === void 0) { withParents = false; }
  36109. if (withChildren === void 0) { withChildren = false; }
  36110. var serializationObject = {};
  36111. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  36112. if (withParents || withChildren) {
  36113. //deliberate for loop! not for each, appended should be processed as well.
  36114. for (var i = 0; i < toSerialize.length; ++i) {
  36115. if (withChildren) {
  36116. toSerialize[i].getDescendants().forEach(function (node) {
  36117. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  36118. toSerialize.push(node);
  36119. }
  36120. });
  36121. }
  36122. //make sure the array doesn't contain the object already
  36123. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  36124. toSerialize.push(toSerialize[i].parent);
  36125. }
  36126. }
  36127. }
  36128. toSerialize.forEach(function (mesh) {
  36129. finalizeSingleMesh(mesh, serializationObject);
  36130. });
  36131. return serializationObject;
  36132. };
  36133. return SceneSerializer;
  36134. }());
  36135. BABYLON.SceneSerializer = SceneSerializer;
  36136. })(BABYLON || (BABYLON = {}));
  36137. var BABYLON;
  36138. (function (BABYLON) {
  36139. // Unique ID when we import meshes from Babylon to CSG
  36140. var currentCSGMeshId = 0;
  36141. // # class Vertex
  36142. // Represents a vertex of a polygon. Use your own vertex class instead of this
  36143. // one to provide additional features like texture coordinates and vertex
  36144. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  36145. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  36146. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  36147. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  36148. // is not used anywhere else.
  36149. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  36150. var Vertex = (function () {
  36151. function Vertex(pos, normal, uv) {
  36152. this.pos = pos;
  36153. this.normal = normal;
  36154. this.uv = uv;
  36155. }
  36156. Vertex.prototype.clone = function () {
  36157. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  36158. };
  36159. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  36160. // orientation of a polygon is flipped.
  36161. Vertex.prototype.flip = function () {
  36162. this.normal = this.normal.scale(-1);
  36163. };
  36164. // Create a new vertex between this vertex and `other` by linearly
  36165. // interpolating all properties using a parameter of `t`. Subclasses should
  36166. // override this to interpolate additional properties.
  36167. Vertex.prototype.interpolate = function (other, t) {
  36168. 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));
  36169. };
  36170. return Vertex;
  36171. }());
  36172. // # class Plane
  36173. // Represents a plane in 3D space.
  36174. var Plane = (function () {
  36175. function Plane(normal, w) {
  36176. this.normal = normal;
  36177. this.w = w;
  36178. }
  36179. Plane.FromPoints = function (a, b, c) {
  36180. var v0 = c.subtract(a);
  36181. var v1 = b.subtract(a);
  36182. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  36183. return null;
  36184. }
  36185. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  36186. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  36187. };
  36188. Plane.prototype.clone = function () {
  36189. return new Plane(this.normal.clone(), this.w);
  36190. };
  36191. Plane.prototype.flip = function () {
  36192. this.normal.scaleInPlace(-1);
  36193. this.w = -this.w;
  36194. };
  36195. // Split `polygon` by this plane if needed, then put the polygon or polygon
  36196. // fragments in the appropriate lists. Coplanar polygons go into either
  36197. // `coplanarFront` or `coplanarBack` depending on their orientation with
  36198. // respect to this plane. Polygons in front or in back of this plane go into
  36199. // either `front` or `back`.
  36200. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  36201. var COPLANAR = 0;
  36202. var FRONT = 1;
  36203. var BACK = 2;
  36204. var SPANNING = 3;
  36205. // Classify each point as well as the entire polygon into one of the above
  36206. // four classes.
  36207. var polygonType = 0;
  36208. var types = [];
  36209. var i;
  36210. var t;
  36211. for (i = 0; i < polygon.vertices.length; i++) {
  36212. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  36213. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  36214. polygonType |= type;
  36215. types.push(type);
  36216. }
  36217. // Put the polygon in the correct list, splitting it when necessary.
  36218. switch (polygonType) {
  36219. case COPLANAR:
  36220. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  36221. break;
  36222. case FRONT:
  36223. front.push(polygon);
  36224. break;
  36225. case BACK:
  36226. back.push(polygon);
  36227. break;
  36228. case SPANNING:
  36229. var f = [], b = [];
  36230. for (i = 0; i < polygon.vertices.length; i++) {
  36231. var j = (i + 1) % polygon.vertices.length;
  36232. var ti = types[i], tj = types[j];
  36233. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  36234. if (ti !== BACK)
  36235. f.push(vi);
  36236. if (ti !== FRONT)
  36237. b.push(ti !== BACK ? vi.clone() : vi);
  36238. if ((ti | tj) === SPANNING) {
  36239. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  36240. var v = vi.interpolate(vj, t);
  36241. f.push(v);
  36242. b.push(v.clone());
  36243. }
  36244. }
  36245. var poly;
  36246. if (f.length >= 3) {
  36247. poly = new Polygon(f, polygon.shared);
  36248. if (poly.plane)
  36249. front.push(poly);
  36250. }
  36251. if (b.length >= 3) {
  36252. poly = new Polygon(b, polygon.shared);
  36253. if (poly.plane)
  36254. back.push(poly);
  36255. }
  36256. break;
  36257. }
  36258. };
  36259. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  36260. // point is on the plane.
  36261. Plane.EPSILON = 1e-5;
  36262. return Plane;
  36263. }());
  36264. // # class Polygon
  36265. // Represents a convex polygon. The vertices used to initialize a polygon must
  36266. // be coplanar and form a convex loop.
  36267. //
  36268. // Each convex polygon has a `shared` property, which is shared between all
  36269. // polygons that are clones of each other or were split from the same polygon.
  36270. // This can be used to define per-polygon properties (such as surface color).
  36271. var Polygon = (function () {
  36272. function Polygon(vertices, shared) {
  36273. this.vertices = vertices;
  36274. this.shared = shared;
  36275. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  36276. }
  36277. Polygon.prototype.clone = function () {
  36278. var vertices = this.vertices.map(function (v) { return v.clone(); });
  36279. return new Polygon(vertices, this.shared);
  36280. };
  36281. Polygon.prototype.flip = function () {
  36282. this.vertices.reverse().map(function (v) { v.flip(); });
  36283. this.plane.flip();
  36284. };
  36285. return Polygon;
  36286. }());
  36287. // # class Node
  36288. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  36289. // by picking a polygon to split along. That polygon (and all other coplanar
  36290. // polygons) are added directly to that node and the other polygons are added to
  36291. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  36292. // no distinction between internal and leaf nodes.
  36293. var Node = (function () {
  36294. function Node(polygons) {
  36295. this.plane = null;
  36296. this.front = null;
  36297. this.back = null;
  36298. this.polygons = [];
  36299. if (polygons) {
  36300. this.build(polygons);
  36301. }
  36302. }
  36303. Node.prototype.clone = function () {
  36304. var node = new Node();
  36305. node.plane = this.plane && this.plane.clone();
  36306. node.front = this.front && this.front.clone();
  36307. node.back = this.back && this.back.clone();
  36308. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  36309. return node;
  36310. };
  36311. // Convert solid space to empty space and empty space to solid space.
  36312. Node.prototype.invert = function () {
  36313. for (var i = 0; i < this.polygons.length; i++) {
  36314. this.polygons[i].flip();
  36315. }
  36316. if (this.plane) {
  36317. this.plane.flip();
  36318. }
  36319. if (this.front) {
  36320. this.front.invert();
  36321. }
  36322. if (this.back) {
  36323. this.back.invert();
  36324. }
  36325. var temp = this.front;
  36326. this.front = this.back;
  36327. this.back = temp;
  36328. };
  36329. // Recursively remove all polygons in `polygons` that are inside this BSP
  36330. // tree.
  36331. Node.prototype.clipPolygons = function (polygons) {
  36332. if (!this.plane)
  36333. return polygons.slice();
  36334. var front = [], back = [];
  36335. for (var i = 0; i < polygons.length; i++) {
  36336. this.plane.splitPolygon(polygons[i], front, back, front, back);
  36337. }
  36338. if (this.front) {
  36339. front = this.front.clipPolygons(front);
  36340. }
  36341. if (this.back) {
  36342. back = this.back.clipPolygons(back);
  36343. }
  36344. else {
  36345. back = [];
  36346. }
  36347. return front.concat(back);
  36348. };
  36349. // Remove all polygons in this BSP tree that are inside the other BSP tree
  36350. // `bsp`.
  36351. Node.prototype.clipTo = function (bsp) {
  36352. this.polygons = bsp.clipPolygons(this.polygons);
  36353. if (this.front)
  36354. this.front.clipTo(bsp);
  36355. if (this.back)
  36356. this.back.clipTo(bsp);
  36357. };
  36358. // Return a list of all polygons in this BSP tree.
  36359. Node.prototype.allPolygons = function () {
  36360. var polygons = this.polygons.slice();
  36361. if (this.front)
  36362. polygons = polygons.concat(this.front.allPolygons());
  36363. if (this.back)
  36364. polygons = polygons.concat(this.back.allPolygons());
  36365. return polygons;
  36366. };
  36367. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  36368. // new polygons are filtered down to the bottom of the tree and become new
  36369. // nodes there. Each set of polygons is partitioned using the first polygon
  36370. // (no heuristic is used to pick a good split).
  36371. Node.prototype.build = function (polygons) {
  36372. if (!polygons.length)
  36373. return;
  36374. if (!this.plane)
  36375. this.plane = polygons[0].plane.clone();
  36376. var front = [], back = [];
  36377. for (var i = 0; i < polygons.length; i++) {
  36378. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  36379. }
  36380. if (front.length) {
  36381. if (!this.front)
  36382. this.front = new Node();
  36383. this.front.build(front);
  36384. }
  36385. if (back.length) {
  36386. if (!this.back)
  36387. this.back = new Node();
  36388. this.back.build(back);
  36389. }
  36390. };
  36391. return Node;
  36392. }());
  36393. var CSG = (function () {
  36394. function CSG() {
  36395. this.polygons = new Array();
  36396. }
  36397. // Convert BABYLON.Mesh to BABYLON.CSG
  36398. CSG.FromMesh = function (mesh) {
  36399. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  36400. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  36401. if (mesh instanceof BABYLON.Mesh) {
  36402. mesh.computeWorldMatrix(true);
  36403. matrix = mesh.getWorldMatrix();
  36404. meshPosition = mesh.position.clone();
  36405. meshRotation = mesh.rotation.clone();
  36406. if (mesh.rotationQuaternion) {
  36407. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  36408. }
  36409. meshScaling = mesh.scaling.clone();
  36410. }
  36411. else {
  36412. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  36413. }
  36414. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36415. var subMeshes = mesh.subMeshes;
  36416. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  36417. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  36418. vertices = [];
  36419. for (var j = 0; j < 3; j++) {
  36420. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  36421. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  36422. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  36423. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  36424. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  36425. vertex = new Vertex(position, normal, uv);
  36426. vertices.push(vertex);
  36427. }
  36428. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  36429. // To handle the case of degenerated triangle
  36430. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  36431. if (polygon.plane)
  36432. polygons.push(polygon);
  36433. }
  36434. }
  36435. var csg = CSG.FromPolygons(polygons);
  36436. csg.matrix = matrix;
  36437. csg.position = meshPosition;
  36438. csg.rotation = meshRotation;
  36439. csg.scaling = meshScaling;
  36440. csg.rotationQuaternion = meshRotationQuaternion;
  36441. currentCSGMeshId++;
  36442. return csg;
  36443. };
  36444. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  36445. CSG.FromPolygons = function (polygons) {
  36446. var csg = new CSG();
  36447. csg.polygons = polygons;
  36448. return csg;
  36449. };
  36450. CSG.prototype.clone = function () {
  36451. var csg = new CSG();
  36452. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  36453. csg.copyTransformAttributes(this);
  36454. return csg;
  36455. };
  36456. CSG.prototype.toPolygons = function () {
  36457. return this.polygons;
  36458. };
  36459. CSG.prototype.union = function (csg) {
  36460. var a = new Node(this.clone().polygons);
  36461. var b = new Node(csg.clone().polygons);
  36462. a.clipTo(b);
  36463. b.clipTo(a);
  36464. b.invert();
  36465. b.clipTo(a);
  36466. b.invert();
  36467. a.build(b.allPolygons());
  36468. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36469. };
  36470. CSG.prototype.unionInPlace = function (csg) {
  36471. var a = new Node(this.polygons);
  36472. var b = new Node(csg.polygons);
  36473. a.clipTo(b);
  36474. b.clipTo(a);
  36475. b.invert();
  36476. b.clipTo(a);
  36477. b.invert();
  36478. a.build(b.allPolygons());
  36479. this.polygons = a.allPolygons();
  36480. };
  36481. CSG.prototype.subtract = function (csg) {
  36482. var a = new Node(this.clone().polygons);
  36483. var b = new Node(csg.clone().polygons);
  36484. a.invert();
  36485. a.clipTo(b);
  36486. b.clipTo(a);
  36487. b.invert();
  36488. b.clipTo(a);
  36489. b.invert();
  36490. a.build(b.allPolygons());
  36491. a.invert();
  36492. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36493. };
  36494. CSG.prototype.subtractInPlace = function (csg) {
  36495. var a = new Node(this.polygons);
  36496. var b = new Node(csg.polygons);
  36497. a.invert();
  36498. a.clipTo(b);
  36499. b.clipTo(a);
  36500. b.invert();
  36501. b.clipTo(a);
  36502. b.invert();
  36503. a.build(b.allPolygons());
  36504. a.invert();
  36505. this.polygons = a.allPolygons();
  36506. };
  36507. CSG.prototype.intersect = function (csg) {
  36508. var a = new Node(this.clone().polygons);
  36509. var b = new Node(csg.clone().polygons);
  36510. a.invert();
  36511. b.clipTo(a);
  36512. b.invert();
  36513. a.clipTo(b);
  36514. b.clipTo(a);
  36515. a.build(b.allPolygons());
  36516. a.invert();
  36517. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36518. };
  36519. CSG.prototype.intersectInPlace = function (csg) {
  36520. var a = new Node(this.polygons);
  36521. var b = new Node(csg.polygons);
  36522. a.invert();
  36523. b.clipTo(a);
  36524. b.invert();
  36525. a.clipTo(b);
  36526. b.clipTo(a);
  36527. a.build(b.allPolygons());
  36528. a.invert();
  36529. this.polygons = a.allPolygons();
  36530. };
  36531. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  36532. // not modified.
  36533. CSG.prototype.inverse = function () {
  36534. var csg = this.clone();
  36535. csg.inverseInPlace();
  36536. return csg;
  36537. };
  36538. CSG.prototype.inverseInPlace = function () {
  36539. this.polygons.map(function (p) { p.flip(); });
  36540. };
  36541. // This is used to keep meshes transformations so they can be restored
  36542. // when we build back a Babylon Mesh
  36543. // NB : All CSG operations are performed in world coordinates
  36544. CSG.prototype.copyTransformAttributes = function (csg) {
  36545. this.matrix = csg.matrix;
  36546. this.position = csg.position;
  36547. this.rotation = csg.rotation;
  36548. this.scaling = csg.scaling;
  36549. this.rotationQuaternion = csg.rotationQuaternion;
  36550. return this;
  36551. };
  36552. // Build Raw mesh from CSG
  36553. // Coordinates here are in world space
  36554. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  36555. var matrix = this.matrix.clone();
  36556. matrix.invert();
  36557. 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;
  36558. if (keepSubMeshes) {
  36559. // Sort Polygons, since subMeshes are indices range
  36560. polygons.sort(function (a, b) {
  36561. if (a.shared.meshId === b.shared.meshId) {
  36562. return a.shared.subMeshId - b.shared.subMeshId;
  36563. }
  36564. else {
  36565. return a.shared.meshId - b.shared.meshId;
  36566. }
  36567. });
  36568. }
  36569. for (var i = 0, il = polygons.length; i < il; i++) {
  36570. polygon = polygons[i];
  36571. // Building SubMeshes
  36572. if (!subMesh_dict[polygon.shared.meshId]) {
  36573. subMesh_dict[polygon.shared.meshId] = {};
  36574. }
  36575. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  36576. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  36577. indexStart: +Infinity,
  36578. indexEnd: -Infinity,
  36579. materialIndex: polygon.shared.materialIndex
  36580. };
  36581. }
  36582. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  36583. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  36584. polygonIndices[0] = 0;
  36585. polygonIndices[1] = j - 1;
  36586. polygonIndices[2] = j;
  36587. for (var k = 0; k < 3; k++) {
  36588. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  36589. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  36590. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  36591. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  36592. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  36593. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  36594. // Check if 2 points can be merged
  36595. if (!(typeof vertex_idx !== 'undefined' &&
  36596. normals[vertex_idx * 3] === localNormal.x &&
  36597. normals[vertex_idx * 3 + 1] === localNormal.y &&
  36598. normals[vertex_idx * 3 + 2] === localNormal.z &&
  36599. uvs[vertex_idx * 2] === uv.x &&
  36600. uvs[vertex_idx * 2 + 1] === uv.y)) {
  36601. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  36602. uvs.push(uv.x, uv.y);
  36603. normals.push(normal.x, normal.y, normal.z);
  36604. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  36605. }
  36606. indices.push(vertex_idx);
  36607. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  36608. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  36609. currentIndex++;
  36610. }
  36611. }
  36612. }
  36613. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  36614. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  36615. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  36616. mesh.setIndices(indices);
  36617. if (keepSubMeshes) {
  36618. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  36619. var materialIndexOffset = 0, materialMaxIndex;
  36620. mesh.subMeshes = new Array();
  36621. for (var m in subMesh_dict) {
  36622. materialMaxIndex = -1;
  36623. for (var sm in subMesh_dict[m]) {
  36624. subMesh_obj = subMesh_dict[m][sm];
  36625. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  36626. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  36627. }
  36628. materialIndexOffset += ++materialMaxIndex;
  36629. }
  36630. }
  36631. return mesh;
  36632. };
  36633. // Build Mesh from CSG taking material and transforms into account
  36634. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  36635. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  36636. mesh.material = material;
  36637. mesh.position.copyFrom(this.position);
  36638. mesh.rotation.copyFrom(this.rotation);
  36639. if (this.rotationQuaternion) {
  36640. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  36641. }
  36642. mesh.scaling.copyFrom(this.scaling);
  36643. mesh.computeWorldMatrix(true);
  36644. return mesh;
  36645. };
  36646. return CSG;
  36647. }());
  36648. BABYLON.CSG = CSG;
  36649. })(BABYLON || (BABYLON = {}));
  36650. var BABYLON;
  36651. (function (BABYLON) {
  36652. var VRDistortionCorrectionPostProcess = (function (_super) {
  36653. __extends(VRDistortionCorrectionPostProcess, _super);
  36654. //ANY
  36655. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  36656. var _this = this;
  36657. _super.call(this, name, "vrDistortionCorrection", [
  36658. 'LensCenter',
  36659. 'Scale',
  36660. 'ScaleIn',
  36661. 'HmdWarpParam'
  36662. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  36663. this._isRightEye = isRightEye;
  36664. this._distortionFactors = vrMetrics.distortionK;
  36665. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  36666. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  36667. this.onSizeChanged = function () {
  36668. _this.aspectRatio = _this.width * .5 / _this.height;
  36669. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  36670. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  36671. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  36672. };
  36673. this.onApply = function (effect) {
  36674. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  36675. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  36676. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  36677. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  36678. };
  36679. }
  36680. return VRDistortionCorrectionPostProcess;
  36681. }(BABYLON.PostProcess));
  36682. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  36683. })(BABYLON || (BABYLON = {}));
  36684. // Mainly based on these 2 articles :
  36685. // 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
  36686. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  36687. var BABYLON;
  36688. (function (BABYLON) {
  36689. (function (JoystickAxis) {
  36690. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  36691. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  36692. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  36693. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  36694. var JoystickAxis = BABYLON.JoystickAxis;
  36695. var VirtualJoystick = (function () {
  36696. function VirtualJoystick(leftJoystick) {
  36697. var _this = this;
  36698. if (leftJoystick) {
  36699. this._leftJoystick = true;
  36700. }
  36701. else {
  36702. this._leftJoystick = false;
  36703. }
  36704. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  36705. VirtualJoystick._globalJoystickIndex++;
  36706. // By default left & right arrow keys are moving the X
  36707. // and up & down keys are moving the Y
  36708. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36709. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36710. this.reverseLeftRight = false;
  36711. this.reverseUpDown = false;
  36712. // collections of pointers
  36713. this._touches = new BABYLON.SmartCollection();
  36714. this.deltaPosition = BABYLON.Vector3.Zero();
  36715. this._joystickSensibility = 25;
  36716. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36717. this._rotationSpeed = 25;
  36718. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  36719. this._rotateOnAxisRelativeToMesh = false;
  36720. this._onResize = function (evt) {
  36721. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36722. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36723. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  36724. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  36725. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  36726. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  36727. };
  36728. // injecting a canvas element on top of the canvas 3D game
  36729. if (!VirtualJoystick.vjCanvas) {
  36730. window.addEventListener("resize", this._onResize, false);
  36731. VirtualJoystick.vjCanvas = document.createElement("canvas");
  36732. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36733. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36734. VirtualJoystick.vjCanvas.width = window.innerWidth;
  36735. VirtualJoystick.vjCanvas.height = window.innerHeight;
  36736. VirtualJoystick.vjCanvas.style.width = "100%";
  36737. VirtualJoystick.vjCanvas.style.height = "100%";
  36738. VirtualJoystick.vjCanvas.style.position = "absolute";
  36739. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  36740. VirtualJoystick.vjCanvas.style.top = "0px";
  36741. VirtualJoystick.vjCanvas.style.left = "0px";
  36742. VirtualJoystick.vjCanvas.style.zIndex = "5";
  36743. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  36744. // Support for jQuery PEP polyfill
  36745. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  36746. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  36747. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  36748. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36749. document.body.appendChild(VirtualJoystick.vjCanvas);
  36750. }
  36751. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  36752. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  36753. this.pressed = false;
  36754. // default joystick color
  36755. this._joystickColor = "cyan";
  36756. this._joystickPointerID = -1;
  36757. // current joystick position
  36758. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  36759. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  36760. // origin joystick position
  36761. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  36762. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  36763. this._onPointerDownHandlerRef = function (evt) {
  36764. _this._onPointerDown(evt);
  36765. };
  36766. this._onPointerMoveHandlerRef = function (evt) {
  36767. _this._onPointerMove(evt);
  36768. };
  36769. this._onPointerOutHandlerRef = function (evt) {
  36770. _this._onPointerUp(evt);
  36771. };
  36772. this._onPointerUpHandlerRef = function (evt) {
  36773. _this._onPointerUp(evt);
  36774. };
  36775. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  36776. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  36777. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  36778. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  36779. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  36780. evt.preventDefault(); // Disables system menu
  36781. }, false);
  36782. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36783. }
  36784. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  36785. this._joystickSensibility = newJoystickSensibility;
  36786. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36787. };
  36788. VirtualJoystick.prototype._onPointerDown = function (e) {
  36789. var positionOnScreenCondition;
  36790. e.preventDefault();
  36791. if (this._leftJoystick === true) {
  36792. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  36793. }
  36794. else {
  36795. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  36796. }
  36797. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  36798. // First contact will be dedicated to the virtual joystick
  36799. this._joystickPointerID = e.pointerId;
  36800. this._joystickPointerStartPos.x = e.clientX;
  36801. this._joystickPointerStartPos.y = e.clientY;
  36802. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  36803. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  36804. this._deltaJoystickVector.x = 0;
  36805. this._deltaJoystickVector.y = 0;
  36806. this.pressed = true;
  36807. this._touches.add(e.pointerId.toString(), e);
  36808. }
  36809. else {
  36810. // You can only trigger the action buttons with a joystick declared
  36811. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  36812. this._action();
  36813. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  36814. }
  36815. }
  36816. };
  36817. VirtualJoystick.prototype._onPointerMove = function (e) {
  36818. // If the current pointer is the one associated to the joystick (first touch contact)
  36819. if (this._joystickPointerID == e.pointerId) {
  36820. this._joystickPointerPos.x = e.clientX;
  36821. this._joystickPointerPos.y = e.clientY;
  36822. this._deltaJoystickVector = this._joystickPointerPos.clone();
  36823. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  36824. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  36825. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  36826. switch (this._axisTargetedByLeftAndRight) {
  36827. case JoystickAxis.X:
  36828. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  36829. break;
  36830. case JoystickAxis.Y:
  36831. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  36832. break;
  36833. case JoystickAxis.Z:
  36834. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  36835. break;
  36836. }
  36837. var directionUpDown = this.reverseUpDown ? 1 : -1;
  36838. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  36839. switch (this._axisTargetedByUpAndDown) {
  36840. case JoystickAxis.X:
  36841. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  36842. break;
  36843. case JoystickAxis.Y:
  36844. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  36845. break;
  36846. case JoystickAxis.Z:
  36847. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  36848. break;
  36849. }
  36850. }
  36851. else {
  36852. if (this._touches.item(e.pointerId.toString())) {
  36853. this._touches.item(e.pointerId.toString()).x = e.clientX;
  36854. this._touches.item(e.pointerId.toString()).y = e.clientY;
  36855. }
  36856. }
  36857. };
  36858. VirtualJoystick.prototype._onPointerUp = function (e) {
  36859. if (this._joystickPointerID == e.pointerId) {
  36860. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  36861. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  36862. this._joystickPointerID = -1;
  36863. this.pressed = false;
  36864. }
  36865. else {
  36866. var touch = this._touches.item(e.pointerId.toString());
  36867. if (touch) {
  36868. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  36869. }
  36870. }
  36871. this._deltaJoystickVector.x = 0;
  36872. this._deltaJoystickVector.y = 0;
  36873. this._touches.remove(e.pointerId.toString());
  36874. };
  36875. /**
  36876. * Change the color of the virtual joystick
  36877. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  36878. */
  36879. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  36880. this._joystickColor = newColor;
  36881. };
  36882. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  36883. this._action = action;
  36884. };
  36885. // Define which axis you'd like to control for left & right
  36886. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  36887. switch (axis) {
  36888. case JoystickAxis.X:
  36889. case JoystickAxis.Y:
  36890. case JoystickAxis.Z:
  36891. this._axisTargetedByLeftAndRight = axis;
  36892. break;
  36893. default:
  36894. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36895. break;
  36896. }
  36897. };
  36898. // Define which axis you'd like to control for up & down
  36899. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  36900. switch (axis) {
  36901. case JoystickAxis.X:
  36902. case JoystickAxis.Y:
  36903. case JoystickAxis.Z:
  36904. this._axisTargetedByUpAndDown = axis;
  36905. break;
  36906. default:
  36907. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36908. break;
  36909. }
  36910. };
  36911. VirtualJoystick.prototype._clearCanvas = function () {
  36912. if (this._leftJoystick) {
  36913. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  36914. }
  36915. else {
  36916. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  36917. }
  36918. };
  36919. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  36920. var _this = this;
  36921. if (this.pressed) {
  36922. this._touches.forEach(function (touch) {
  36923. if (touch.pointerId === _this._joystickPointerID) {
  36924. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  36925. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  36926. VirtualJoystick.vjCanvasContext.beginPath();
  36927. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  36928. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36929. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  36930. VirtualJoystick.vjCanvasContext.stroke();
  36931. VirtualJoystick.vjCanvasContext.closePath();
  36932. VirtualJoystick.vjCanvasContext.beginPath();
  36933. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36934. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36935. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  36936. VirtualJoystick.vjCanvasContext.stroke();
  36937. VirtualJoystick.vjCanvasContext.closePath();
  36938. VirtualJoystick.vjCanvasContext.beginPath();
  36939. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36940. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  36941. VirtualJoystick.vjCanvasContext.stroke();
  36942. VirtualJoystick.vjCanvasContext.closePath();
  36943. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  36944. }
  36945. else {
  36946. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  36947. VirtualJoystick.vjCanvasContext.beginPath();
  36948. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  36949. VirtualJoystick.vjCanvasContext.beginPath();
  36950. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  36951. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  36952. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  36953. VirtualJoystick.vjCanvasContext.stroke();
  36954. VirtualJoystick.vjCanvasContext.closePath();
  36955. touch.prevX = touch.x;
  36956. touch.prevY = touch.y;
  36957. }
  36958. ;
  36959. });
  36960. }
  36961. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36962. };
  36963. VirtualJoystick.prototype.releaseCanvas = function () {
  36964. if (VirtualJoystick.vjCanvas) {
  36965. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  36966. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  36967. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  36968. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  36969. window.removeEventListener("resize", this._onResize);
  36970. document.body.removeChild(VirtualJoystick.vjCanvas);
  36971. VirtualJoystick.vjCanvas = null;
  36972. }
  36973. };
  36974. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  36975. VirtualJoystick._globalJoystickIndex = 0;
  36976. return VirtualJoystick;
  36977. }());
  36978. BABYLON.VirtualJoystick = VirtualJoystick;
  36979. })(BABYLON || (BABYLON = {}));
  36980. var BABYLON;
  36981. (function (BABYLON) {
  36982. // We're mainly based on the logic defined into the FreeCamera code
  36983. var VirtualJoysticksCamera = (function (_super) {
  36984. __extends(VirtualJoysticksCamera, _super);
  36985. function VirtualJoysticksCamera(name, position, scene) {
  36986. _super.call(this, name, position, scene);
  36987. this.inputs.addVirtualJoystick();
  36988. }
  36989. return VirtualJoysticksCamera;
  36990. }(BABYLON.FreeCamera));
  36991. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  36992. })(BABYLON || (BABYLON = {}));
  36993. var BABYLON;
  36994. (function (BABYLON) {
  36995. var AnaglyphPostProcess = (function (_super) {
  36996. __extends(AnaglyphPostProcess, _super);
  36997. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  36998. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  36999. }
  37000. return AnaglyphPostProcess;
  37001. }(BABYLON.PostProcess));
  37002. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  37003. })(BABYLON || (BABYLON = {}));
  37004. var BABYLON;
  37005. (function (BABYLON) {
  37006. var OutlineRenderer = (function () {
  37007. function OutlineRenderer(scene) {
  37008. this._scene = scene;
  37009. }
  37010. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  37011. var _this = this;
  37012. if (useOverlay === void 0) { useOverlay = false; }
  37013. var scene = this._scene;
  37014. var engine = this._scene.getEngine();
  37015. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37016. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  37017. return;
  37018. }
  37019. var mesh = subMesh.getRenderingMesh();
  37020. var material = subMesh.getMaterial();
  37021. engine.enableEffect(this._effect);
  37022. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  37023. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  37024. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  37025. // Bones
  37026. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37027. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37028. }
  37029. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  37030. // Alpha test
  37031. if (material && material.needAlphaTesting()) {
  37032. var alphaTexture = material.getAlphaTestTexture();
  37033. this._effect.setTexture("diffuseSampler", alphaTexture);
  37034. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37035. }
  37036. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  37037. };
  37038. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  37039. var defines = [];
  37040. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  37041. var mesh = subMesh.getMesh();
  37042. var material = subMesh.getMaterial();
  37043. // Alpha test
  37044. if (material && material.needAlphaTesting()) {
  37045. defines.push("#define ALPHATEST");
  37046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37047. attribs.push(BABYLON.VertexBuffer.UVKind);
  37048. defines.push("#define UV1");
  37049. }
  37050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37051. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37052. defines.push("#define UV2");
  37053. }
  37054. }
  37055. // Bones
  37056. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37057. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37058. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37059. if (mesh.numBoneInfluencers > 4) {
  37060. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37061. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37062. }
  37063. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37064. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37065. }
  37066. else {
  37067. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37068. }
  37069. // Instances
  37070. if (useInstances) {
  37071. defines.push("#define INSTANCES");
  37072. attribs.push("world0");
  37073. attribs.push("world1");
  37074. attribs.push("world2");
  37075. attribs.push("world3");
  37076. }
  37077. // Get correct effect
  37078. var join = defines.join("\n");
  37079. if (this._cachedDefines !== join) {
  37080. this._cachedDefines = join;
  37081. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  37082. }
  37083. return this._effect.isReady();
  37084. };
  37085. return OutlineRenderer;
  37086. }());
  37087. BABYLON.OutlineRenderer = OutlineRenderer;
  37088. })(BABYLON || (BABYLON = {}));
  37089. var BABYLON;
  37090. (function (BABYLON) {
  37091. var MeshAssetTask = (function () {
  37092. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  37093. this.name = name;
  37094. this.meshesNames = meshesNames;
  37095. this.rootUrl = rootUrl;
  37096. this.sceneFilename = sceneFilename;
  37097. this.isCompleted = false;
  37098. }
  37099. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37100. var _this = this;
  37101. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  37102. _this.loadedMeshes = meshes;
  37103. _this.loadedParticleSystems = particleSystems;
  37104. _this.loadedSkeletons = skeletons;
  37105. _this.isCompleted = true;
  37106. if (_this.onSuccess) {
  37107. _this.onSuccess(_this);
  37108. }
  37109. onSuccess();
  37110. }, null, function () {
  37111. if (_this.onError) {
  37112. _this.onError(_this);
  37113. }
  37114. onError();
  37115. });
  37116. };
  37117. return MeshAssetTask;
  37118. }());
  37119. BABYLON.MeshAssetTask = MeshAssetTask;
  37120. var TextFileAssetTask = (function () {
  37121. function TextFileAssetTask(name, url) {
  37122. this.name = name;
  37123. this.url = url;
  37124. this.isCompleted = false;
  37125. }
  37126. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37127. var _this = this;
  37128. BABYLON.Tools.LoadFile(this.url, function (data) {
  37129. _this.text = data;
  37130. _this.isCompleted = true;
  37131. if (_this.onSuccess) {
  37132. _this.onSuccess(_this);
  37133. }
  37134. onSuccess();
  37135. }, null, scene.database, false, function () {
  37136. if (_this.onError) {
  37137. _this.onError(_this);
  37138. }
  37139. onError();
  37140. });
  37141. };
  37142. return TextFileAssetTask;
  37143. }());
  37144. BABYLON.TextFileAssetTask = TextFileAssetTask;
  37145. var BinaryFileAssetTask = (function () {
  37146. function BinaryFileAssetTask(name, url) {
  37147. this.name = name;
  37148. this.url = url;
  37149. this.isCompleted = false;
  37150. }
  37151. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37152. var _this = this;
  37153. BABYLON.Tools.LoadFile(this.url, function (data) {
  37154. _this.data = data;
  37155. _this.isCompleted = true;
  37156. if (_this.onSuccess) {
  37157. _this.onSuccess(_this);
  37158. }
  37159. onSuccess();
  37160. }, null, scene.database, true, function () {
  37161. if (_this.onError) {
  37162. _this.onError(_this);
  37163. }
  37164. onError();
  37165. });
  37166. };
  37167. return BinaryFileAssetTask;
  37168. }());
  37169. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  37170. var ImageAssetTask = (function () {
  37171. function ImageAssetTask(name, url) {
  37172. this.name = name;
  37173. this.url = url;
  37174. this.isCompleted = false;
  37175. }
  37176. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37177. var _this = this;
  37178. var img = new Image();
  37179. img.onload = function () {
  37180. _this.image = img;
  37181. _this.isCompleted = true;
  37182. if (_this.onSuccess) {
  37183. _this.onSuccess(_this);
  37184. }
  37185. onSuccess();
  37186. };
  37187. img.onerror = function () {
  37188. if (_this.onError) {
  37189. _this.onError(_this);
  37190. }
  37191. onError();
  37192. };
  37193. img.src = this.url;
  37194. };
  37195. return ImageAssetTask;
  37196. }());
  37197. BABYLON.ImageAssetTask = ImageAssetTask;
  37198. var TextureAssetTask = (function () {
  37199. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  37200. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37201. this.name = name;
  37202. this.url = url;
  37203. this.noMipmap = noMipmap;
  37204. this.invertY = invertY;
  37205. this.samplingMode = samplingMode;
  37206. this.isCompleted = false;
  37207. }
  37208. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37209. var _this = this;
  37210. var onload = function () {
  37211. _this.isCompleted = true;
  37212. if (_this.onSuccess) {
  37213. _this.onSuccess(_this);
  37214. }
  37215. onSuccess();
  37216. };
  37217. var onerror = function () {
  37218. if (_this.onError) {
  37219. _this.onError(_this);
  37220. }
  37221. onError();
  37222. };
  37223. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  37224. };
  37225. return TextureAssetTask;
  37226. }());
  37227. BABYLON.TextureAssetTask = TextureAssetTask;
  37228. var AssetsManager = (function () {
  37229. function AssetsManager(scene) {
  37230. this._tasks = new Array();
  37231. this._waitingTasksCount = 0;
  37232. this.useDefaultLoadingScreen = true;
  37233. this._scene = scene;
  37234. }
  37235. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  37236. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  37237. this._tasks.push(task);
  37238. return task;
  37239. };
  37240. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  37241. var task = new TextFileAssetTask(taskName, url);
  37242. this._tasks.push(task);
  37243. return task;
  37244. };
  37245. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  37246. var task = new BinaryFileAssetTask(taskName, url);
  37247. this._tasks.push(task);
  37248. return task;
  37249. };
  37250. AssetsManager.prototype.addImageTask = function (taskName, url) {
  37251. var task = new ImageAssetTask(taskName, url);
  37252. this._tasks.push(task);
  37253. return task;
  37254. };
  37255. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  37256. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37257. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  37258. this._tasks.push(task);
  37259. return task;
  37260. };
  37261. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  37262. this._waitingTasksCount--;
  37263. if (this._waitingTasksCount === 0) {
  37264. if (this.onFinish) {
  37265. this.onFinish(this._tasks);
  37266. }
  37267. this._scene.getEngine().hideLoadingUI();
  37268. }
  37269. };
  37270. AssetsManager.prototype._runTask = function (task) {
  37271. var _this = this;
  37272. task.run(this._scene, function () {
  37273. if (_this.onTaskSuccess) {
  37274. _this.onTaskSuccess(task);
  37275. }
  37276. _this._decreaseWaitingTasksCount();
  37277. }, function () {
  37278. if (_this.onTaskError) {
  37279. _this.onTaskError(task);
  37280. }
  37281. _this._decreaseWaitingTasksCount();
  37282. });
  37283. };
  37284. AssetsManager.prototype.reset = function () {
  37285. this._tasks = new Array();
  37286. return this;
  37287. };
  37288. AssetsManager.prototype.load = function () {
  37289. this._waitingTasksCount = this._tasks.length;
  37290. if (this._waitingTasksCount === 0) {
  37291. if (this.onFinish) {
  37292. this.onFinish(this._tasks);
  37293. }
  37294. return this;
  37295. }
  37296. if (this.useDefaultLoadingScreen) {
  37297. this._scene.getEngine().displayLoadingUI();
  37298. }
  37299. for (var index = 0; index < this._tasks.length; index++) {
  37300. var task = this._tasks[index];
  37301. this._runTask(task);
  37302. }
  37303. return this;
  37304. };
  37305. return AssetsManager;
  37306. }());
  37307. BABYLON.AssetsManager = AssetsManager;
  37308. })(BABYLON || (BABYLON = {}));
  37309. var BABYLON;
  37310. (function (BABYLON) {
  37311. var VRCameraMetrics = (function () {
  37312. function VRCameraMetrics() {
  37313. this.compensateDistortion = true;
  37314. }
  37315. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  37316. get: function () {
  37317. return this.hResolution / (2 * this.vResolution);
  37318. },
  37319. enumerable: true,
  37320. configurable: true
  37321. });
  37322. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  37323. get: function () {
  37324. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  37325. },
  37326. enumerable: true,
  37327. configurable: true
  37328. });
  37329. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  37330. get: function () {
  37331. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37332. var h = (4 * meters) / this.hScreenSize;
  37333. return BABYLON.Matrix.Translation(h, 0, 0);
  37334. },
  37335. enumerable: true,
  37336. configurable: true
  37337. });
  37338. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  37339. get: function () {
  37340. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37341. var h = (4 * meters) / this.hScreenSize;
  37342. return BABYLON.Matrix.Translation(-h, 0, 0);
  37343. },
  37344. enumerable: true,
  37345. configurable: true
  37346. });
  37347. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  37348. get: function () {
  37349. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  37350. },
  37351. enumerable: true,
  37352. configurable: true
  37353. });
  37354. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  37355. get: function () {
  37356. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  37357. },
  37358. enumerable: true,
  37359. configurable: true
  37360. });
  37361. VRCameraMetrics.GetDefault = function () {
  37362. var result = new VRCameraMetrics();
  37363. result.hResolution = 1280;
  37364. result.vResolution = 800;
  37365. result.hScreenSize = 0.149759993;
  37366. result.vScreenSize = 0.0935999975;
  37367. result.vScreenCenter = 0.0467999987,
  37368. result.eyeToScreenDistance = 0.0410000011;
  37369. result.lensSeparationDistance = 0.0635000020;
  37370. result.interpupillaryDistance = 0.0640000030;
  37371. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  37372. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  37373. result.postProcessScaleFactor = 1.714605507808412;
  37374. result.lensCenterOffset = 0.151976421;
  37375. return result;
  37376. };
  37377. return VRCameraMetrics;
  37378. }());
  37379. BABYLON.VRCameraMetrics = VRCameraMetrics;
  37380. })(BABYLON || (BABYLON = {}));
  37381. var BABYLON;
  37382. (function (BABYLON) {
  37383. var VRDeviceOrientationFreeCamera = (function (_super) {
  37384. __extends(VRDeviceOrientationFreeCamera, _super);
  37385. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  37386. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37387. _super.call(this, name, position, scene);
  37388. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37389. metrics.compensateDistortion = compensateDistortion;
  37390. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37391. this.inputs.addVRDeviceOrientation();
  37392. }
  37393. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  37394. return "VRDeviceOrientationFreeCamera";
  37395. };
  37396. return VRDeviceOrientationFreeCamera;
  37397. }(BABYLON.FreeCamera));
  37398. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  37399. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  37400. __extends(VRDeviceOrientationArcRotateCamera, _super);
  37401. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  37402. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37403. _super.call(this, name, alpha, beta, radius, target, scene);
  37404. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37405. metrics.compensateDistortion = compensateDistortion;
  37406. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37407. this.inputs.addVRDeviceOrientation();
  37408. }
  37409. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  37410. return "VRDeviceOrientationArcRotateCamera";
  37411. };
  37412. return VRDeviceOrientationArcRotateCamera;
  37413. }(BABYLON.ArcRotateCamera));
  37414. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  37415. })(BABYLON || (BABYLON = {}));
  37416. var BABYLON;
  37417. (function (BABYLON) {
  37418. var WebVRFreeCamera = (function (_super) {
  37419. __extends(WebVRFreeCamera, _super);
  37420. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  37421. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37422. _super.call(this, name, position, scene);
  37423. this._hmdDevice = null;
  37424. this._sensorDevice = null;
  37425. this._cacheState = null;
  37426. this._cacheQuaternion = new BABYLON.Quaternion();
  37427. this._cacheRotation = BABYLON.Vector3.Zero();
  37428. this._vrEnabled = false;
  37429. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37430. metrics.compensateDistortion = compensateDistortion;
  37431. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37432. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  37433. }
  37434. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  37435. var size = devices.length;
  37436. var i = 0;
  37437. // Reset devices.
  37438. this._sensorDevice = null;
  37439. this._hmdDevice = null;
  37440. // Search for a HmdDevice.
  37441. while (i < size && this._hmdDevice === null) {
  37442. if (devices[i] instanceof HMDVRDevice) {
  37443. this._hmdDevice = devices[i];
  37444. }
  37445. i++;
  37446. }
  37447. i = 0;
  37448. while (i < size && this._sensorDevice === null) {
  37449. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  37450. this._sensorDevice = devices[i];
  37451. }
  37452. i++;
  37453. }
  37454. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  37455. };
  37456. WebVRFreeCamera.prototype._checkInputs = function () {
  37457. if (this._vrEnabled) {
  37458. this._cacheState = this._sensorDevice.getState();
  37459. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  37460. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  37461. this.rotation.x = -this._cacheRotation.x;
  37462. this.rotation.y = -this._cacheRotation.y;
  37463. this.rotation.z = this._cacheRotation.z;
  37464. }
  37465. _super.prototype._checkInputs.call(this);
  37466. };
  37467. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37468. _super.prototype.attachControl.call(this, element, noPreventDefault);
  37469. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37470. if (navigator.getVRDevices) {
  37471. navigator.getVRDevices().then(this._getWebVRDevices);
  37472. }
  37473. else if (navigator.mozGetVRDevices) {
  37474. navigator.mozGetVRDevices(this._getWebVRDevices);
  37475. }
  37476. };
  37477. WebVRFreeCamera.prototype.detachControl = function (element) {
  37478. _super.prototype.detachControl.call(this, element);
  37479. this._vrEnabled = false;
  37480. };
  37481. WebVRFreeCamera.prototype.getTypeName = function () {
  37482. return "WebVRFreeCamera";
  37483. };
  37484. return WebVRFreeCamera;
  37485. }(BABYLON.FreeCamera));
  37486. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  37487. })(BABYLON || (BABYLON = {}));
  37488. var BABYLON;
  37489. (function (BABYLON) {
  37490. // Standard optimizations
  37491. var SceneOptimization = (function () {
  37492. function SceneOptimization(priority) {
  37493. if (priority === void 0) { priority = 0; }
  37494. this.priority = priority;
  37495. this.apply = function (scene) {
  37496. return true; // Return true if everything that can be done was applied
  37497. };
  37498. }
  37499. return SceneOptimization;
  37500. }());
  37501. BABYLON.SceneOptimization = SceneOptimization;
  37502. var TextureOptimization = (function (_super) {
  37503. __extends(TextureOptimization, _super);
  37504. function TextureOptimization(priority, maximumSize) {
  37505. var _this = this;
  37506. if (priority === void 0) { priority = 0; }
  37507. if (maximumSize === void 0) { maximumSize = 1024; }
  37508. _super.call(this, priority);
  37509. this.priority = priority;
  37510. this.maximumSize = maximumSize;
  37511. this.apply = function (scene) {
  37512. var allDone = true;
  37513. for (var index = 0; index < scene.textures.length; index++) {
  37514. var texture = scene.textures[index];
  37515. if (!texture.canRescale) {
  37516. continue;
  37517. }
  37518. var currentSize = texture.getSize();
  37519. var maxDimension = Math.max(currentSize.width, currentSize.height);
  37520. if (maxDimension > _this.maximumSize) {
  37521. texture.scale(0.5);
  37522. allDone = false;
  37523. }
  37524. }
  37525. return allDone;
  37526. };
  37527. }
  37528. return TextureOptimization;
  37529. }(SceneOptimization));
  37530. BABYLON.TextureOptimization = TextureOptimization;
  37531. var HardwareScalingOptimization = (function (_super) {
  37532. __extends(HardwareScalingOptimization, _super);
  37533. function HardwareScalingOptimization(priority, maximumScale) {
  37534. var _this = this;
  37535. if (priority === void 0) { priority = 0; }
  37536. if (maximumScale === void 0) { maximumScale = 2; }
  37537. _super.call(this, priority);
  37538. this.priority = priority;
  37539. this.maximumScale = maximumScale;
  37540. this._currentScale = 1;
  37541. this.apply = function (scene) {
  37542. _this._currentScale++;
  37543. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  37544. return _this._currentScale >= _this.maximumScale;
  37545. };
  37546. }
  37547. return HardwareScalingOptimization;
  37548. }(SceneOptimization));
  37549. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  37550. var ShadowsOptimization = (function (_super) {
  37551. __extends(ShadowsOptimization, _super);
  37552. function ShadowsOptimization() {
  37553. _super.apply(this, arguments);
  37554. this.apply = function (scene) {
  37555. scene.shadowsEnabled = false;
  37556. return true;
  37557. };
  37558. }
  37559. return ShadowsOptimization;
  37560. }(SceneOptimization));
  37561. BABYLON.ShadowsOptimization = ShadowsOptimization;
  37562. var PostProcessesOptimization = (function (_super) {
  37563. __extends(PostProcessesOptimization, _super);
  37564. function PostProcessesOptimization() {
  37565. _super.apply(this, arguments);
  37566. this.apply = function (scene) {
  37567. scene.postProcessesEnabled = false;
  37568. return true;
  37569. };
  37570. }
  37571. return PostProcessesOptimization;
  37572. }(SceneOptimization));
  37573. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  37574. var LensFlaresOptimization = (function (_super) {
  37575. __extends(LensFlaresOptimization, _super);
  37576. function LensFlaresOptimization() {
  37577. _super.apply(this, arguments);
  37578. this.apply = function (scene) {
  37579. scene.lensFlaresEnabled = false;
  37580. return true;
  37581. };
  37582. }
  37583. return LensFlaresOptimization;
  37584. }(SceneOptimization));
  37585. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  37586. var ParticlesOptimization = (function (_super) {
  37587. __extends(ParticlesOptimization, _super);
  37588. function ParticlesOptimization() {
  37589. _super.apply(this, arguments);
  37590. this.apply = function (scene) {
  37591. scene.particlesEnabled = false;
  37592. return true;
  37593. };
  37594. }
  37595. return ParticlesOptimization;
  37596. }(SceneOptimization));
  37597. BABYLON.ParticlesOptimization = ParticlesOptimization;
  37598. var RenderTargetsOptimization = (function (_super) {
  37599. __extends(RenderTargetsOptimization, _super);
  37600. function RenderTargetsOptimization() {
  37601. _super.apply(this, arguments);
  37602. this.apply = function (scene) {
  37603. scene.renderTargetsEnabled = false;
  37604. return true;
  37605. };
  37606. }
  37607. return RenderTargetsOptimization;
  37608. }(SceneOptimization));
  37609. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  37610. var MergeMeshesOptimization = (function (_super) {
  37611. __extends(MergeMeshesOptimization, _super);
  37612. function MergeMeshesOptimization() {
  37613. var _this = this;
  37614. _super.apply(this, arguments);
  37615. this._canBeMerged = function (abstractMesh) {
  37616. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  37617. return false;
  37618. }
  37619. var mesh = abstractMesh;
  37620. if (!mesh.isVisible || !mesh.isEnabled()) {
  37621. return false;
  37622. }
  37623. if (mesh.instances.length > 0) {
  37624. return false;
  37625. }
  37626. if (mesh.skeleton || mesh.hasLODLevels) {
  37627. return false;
  37628. }
  37629. if (mesh.parent) {
  37630. return false;
  37631. }
  37632. return true;
  37633. };
  37634. this.apply = function (scene, updateSelectionTree) {
  37635. var globalPool = scene.meshes.slice(0);
  37636. var globalLength = globalPool.length;
  37637. for (var index = 0; index < globalLength; index++) {
  37638. var currentPool = new Array();
  37639. var current = globalPool[index];
  37640. // Checks
  37641. if (!_this._canBeMerged(current)) {
  37642. continue;
  37643. }
  37644. currentPool.push(current);
  37645. // Find compatible meshes
  37646. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  37647. var otherMesh = globalPool[subIndex];
  37648. if (!_this._canBeMerged(otherMesh)) {
  37649. continue;
  37650. }
  37651. if (otherMesh.material !== current.material) {
  37652. continue;
  37653. }
  37654. if (otherMesh.checkCollisions !== current.checkCollisions) {
  37655. continue;
  37656. }
  37657. currentPool.push(otherMesh);
  37658. globalLength--;
  37659. globalPool.splice(subIndex, 1);
  37660. subIndex--;
  37661. }
  37662. if (currentPool.length < 2) {
  37663. continue;
  37664. }
  37665. // Merge meshes
  37666. BABYLON.Mesh.MergeMeshes(currentPool);
  37667. }
  37668. if (updateSelectionTree != undefined) {
  37669. if (updateSelectionTree) {
  37670. scene.createOrUpdateSelectionOctree();
  37671. }
  37672. }
  37673. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  37674. scene.createOrUpdateSelectionOctree();
  37675. }
  37676. return true;
  37677. };
  37678. }
  37679. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  37680. get: function () {
  37681. return MergeMeshesOptimization._UpdateSelectionTree;
  37682. },
  37683. set: function (value) {
  37684. MergeMeshesOptimization._UpdateSelectionTree = value;
  37685. },
  37686. enumerable: true,
  37687. configurable: true
  37688. });
  37689. MergeMeshesOptimization._UpdateSelectionTree = false;
  37690. return MergeMeshesOptimization;
  37691. }(SceneOptimization));
  37692. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  37693. // Options
  37694. var SceneOptimizerOptions = (function () {
  37695. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  37696. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  37697. if (trackerDuration === void 0) { trackerDuration = 2000; }
  37698. this.targetFrameRate = targetFrameRate;
  37699. this.trackerDuration = trackerDuration;
  37700. this.optimizations = new Array();
  37701. }
  37702. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  37703. var result = new SceneOptimizerOptions(targetFrameRate);
  37704. var priority = 0;
  37705. result.optimizations.push(new MergeMeshesOptimization(priority));
  37706. result.optimizations.push(new ShadowsOptimization(priority));
  37707. result.optimizations.push(new LensFlaresOptimization(priority));
  37708. // Next priority
  37709. priority++;
  37710. result.optimizations.push(new PostProcessesOptimization(priority));
  37711. result.optimizations.push(new ParticlesOptimization(priority));
  37712. // Next priority
  37713. priority++;
  37714. result.optimizations.push(new TextureOptimization(priority, 1024));
  37715. return result;
  37716. };
  37717. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  37718. var result = new SceneOptimizerOptions(targetFrameRate);
  37719. var priority = 0;
  37720. result.optimizations.push(new MergeMeshesOptimization(priority));
  37721. result.optimizations.push(new ShadowsOptimization(priority));
  37722. result.optimizations.push(new LensFlaresOptimization(priority));
  37723. // Next priority
  37724. priority++;
  37725. result.optimizations.push(new PostProcessesOptimization(priority));
  37726. result.optimizations.push(new ParticlesOptimization(priority));
  37727. // Next priority
  37728. priority++;
  37729. result.optimizations.push(new TextureOptimization(priority, 512));
  37730. // Next priority
  37731. priority++;
  37732. result.optimizations.push(new RenderTargetsOptimization(priority));
  37733. // Next priority
  37734. priority++;
  37735. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  37736. return result;
  37737. };
  37738. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  37739. var result = new SceneOptimizerOptions(targetFrameRate);
  37740. var priority = 0;
  37741. result.optimizations.push(new MergeMeshesOptimization(priority));
  37742. result.optimizations.push(new ShadowsOptimization(priority));
  37743. result.optimizations.push(new LensFlaresOptimization(priority));
  37744. // Next priority
  37745. priority++;
  37746. result.optimizations.push(new PostProcessesOptimization(priority));
  37747. result.optimizations.push(new ParticlesOptimization(priority));
  37748. // Next priority
  37749. priority++;
  37750. result.optimizations.push(new TextureOptimization(priority, 256));
  37751. // Next priority
  37752. priority++;
  37753. result.optimizations.push(new RenderTargetsOptimization(priority));
  37754. // Next priority
  37755. priority++;
  37756. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  37757. return result;
  37758. };
  37759. return SceneOptimizerOptions;
  37760. }());
  37761. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  37762. // Scene optimizer tool
  37763. var SceneOptimizer = (function () {
  37764. function SceneOptimizer() {
  37765. }
  37766. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  37767. // TODO: add an epsilon
  37768. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  37769. if (onSuccess) {
  37770. onSuccess();
  37771. }
  37772. return;
  37773. }
  37774. // Apply current level of optimizations
  37775. var allDone = true;
  37776. var noOptimizationApplied = true;
  37777. for (var index = 0; index < options.optimizations.length; index++) {
  37778. var optimization = options.optimizations[index];
  37779. if (optimization.priority === currentPriorityLevel) {
  37780. noOptimizationApplied = false;
  37781. allDone = allDone && optimization.apply(scene);
  37782. }
  37783. }
  37784. // If no optimization was applied, this is a failure :(
  37785. if (noOptimizationApplied) {
  37786. if (onFailure) {
  37787. onFailure();
  37788. }
  37789. return;
  37790. }
  37791. // If all optimizations were done, move to next level
  37792. if (allDone) {
  37793. currentPriorityLevel++;
  37794. }
  37795. // Let's the system running for a specific amount of time before checking FPS
  37796. scene.executeWhenReady(function () {
  37797. setTimeout(function () {
  37798. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  37799. }, options.trackerDuration);
  37800. });
  37801. };
  37802. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  37803. if (!options) {
  37804. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  37805. }
  37806. // Let's the system running for a specific amount of time before checking FPS
  37807. scene.executeWhenReady(function () {
  37808. setTimeout(function () {
  37809. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  37810. }, options.trackerDuration);
  37811. });
  37812. };
  37813. return SceneOptimizer;
  37814. }());
  37815. BABYLON.SceneOptimizer = SceneOptimizer;
  37816. })(BABYLON || (BABYLON = {}));
  37817. var BABYLON;
  37818. (function (BABYLON) {
  37819. var Internals;
  37820. (function (Internals) {
  37821. var MeshLODLevel = (function () {
  37822. function MeshLODLevel(distance, mesh) {
  37823. this.distance = distance;
  37824. this.mesh = mesh;
  37825. }
  37826. return MeshLODLevel;
  37827. }());
  37828. Internals.MeshLODLevel = MeshLODLevel;
  37829. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37830. })(BABYLON || (BABYLON = {}));
  37831. var BABYLON;
  37832. (function (BABYLON) {
  37833. var RawTexture = (function (_super) {
  37834. __extends(RawTexture, _super);
  37835. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  37836. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37837. if (invertY === void 0) { invertY = false; }
  37838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37839. _super.call(this, null, scene, !generateMipMaps, invertY);
  37840. this.format = format;
  37841. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  37842. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37843. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37844. }
  37845. RawTexture.prototype.update = function (data) {
  37846. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  37847. };
  37848. // Statics
  37849. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37850. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37851. if (invertY === void 0) { invertY = false; }
  37852. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37853. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  37854. };
  37855. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37856. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37857. if (invertY === void 0) { invertY = false; }
  37858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37859. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37860. };
  37861. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37862. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37863. if (invertY === void 0) { invertY = false; }
  37864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37865. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37866. };
  37867. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37868. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37869. if (invertY === void 0) { invertY = false; }
  37870. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37871. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  37872. };
  37873. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37874. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37875. if (invertY === void 0) { invertY = false; }
  37876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37877. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  37878. };
  37879. return RawTexture;
  37880. }(BABYLON.Texture));
  37881. BABYLON.RawTexture = RawTexture;
  37882. })(BABYLON || (BABYLON = {}));
  37883. var BABYLON;
  37884. (function (BABYLON) {
  37885. var IndexedVector2 = (function (_super) {
  37886. __extends(IndexedVector2, _super);
  37887. function IndexedVector2(original, index) {
  37888. _super.call(this, original.x, original.y);
  37889. this.index = index;
  37890. }
  37891. return IndexedVector2;
  37892. }(BABYLON.Vector2));
  37893. var PolygonPoints = (function () {
  37894. function PolygonPoints() {
  37895. this.elements = new Array();
  37896. }
  37897. PolygonPoints.prototype.add = function (originalPoints) {
  37898. var _this = this;
  37899. var result = new Array();
  37900. originalPoints.forEach(function (point) {
  37901. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  37902. var newPoint = new IndexedVector2(point, _this.elements.length);
  37903. result.push(newPoint);
  37904. _this.elements.push(newPoint);
  37905. }
  37906. });
  37907. return result;
  37908. };
  37909. PolygonPoints.prototype.computeBounds = function () {
  37910. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  37911. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  37912. this.elements.forEach(function (point) {
  37913. // x
  37914. if (point.x < lmin.x) {
  37915. lmin.x = point.x;
  37916. }
  37917. else if (point.x > lmax.x) {
  37918. lmax.x = point.x;
  37919. }
  37920. // y
  37921. if (point.y < lmin.y) {
  37922. lmin.y = point.y;
  37923. }
  37924. else if (point.y > lmax.y) {
  37925. lmax.y = point.y;
  37926. }
  37927. });
  37928. return {
  37929. min: lmin,
  37930. max: lmax,
  37931. width: lmax.x - lmin.x,
  37932. height: lmax.y - lmin.y
  37933. };
  37934. };
  37935. return PolygonPoints;
  37936. }());
  37937. var Polygon = (function () {
  37938. function Polygon() {
  37939. }
  37940. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  37941. return [
  37942. new BABYLON.Vector2(xmin, ymin),
  37943. new BABYLON.Vector2(xmax, ymin),
  37944. new BABYLON.Vector2(xmax, ymax),
  37945. new BABYLON.Vector2(xmin, ymax)
  37946. ];
  37947. };
  37948. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  37949. if (cx === void 0) { cx = 0; }
  37950. if (cy === void 0) { cy = 0; }
  37951. if (numberOfSides === void 0) { numberOfSides = 32; }
  37952. var result = new Array();
  37953. var angle = 0;
  37954. var increment = (Math.PI * 2) / numberOfSides;
  37955. for (var i = 0; i < numberOfSides; i++) {
  37956. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  37957. angle -= increment;
  37958. }
  37959. return result;
  37960. };
  37961. Polygon.Parse = function (input) {
  37962. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  37963. var i, result = [];
  37964. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  37965. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  37966. }
  37967. return result;
  37968. };
  37969. Polygon.StartingAt = function (x, y) {
  37970. return BABYLON.Path2.StartingAt(x, y);
  37971. };
  37972. return Polygon;
  37973. }());
  37974. BABYLON.Polygon = Polygon;
  37975. var PolygonMeshBuilder = (function () {
  37976. function PolygonMeshBuilder(name, contours, scene) {
  37977. this._points = new PolygonPoints();
  37978. this._outlinepoints = new PolygonPoints();
  37979. this._holes = [];
  37980. if (!("poly2tri" in window)) {
  37981. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  37982. }
  37983. this._name = name;
  37984. this._scene = scene;
  37985. var points;
  37986. if (contours instanceof BABYLON.Path2) {
  37987. points = contours.getPoints();
  37988. }
  37989. else {
  37990. points = contours;
  37991. }
  37992. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  37993. this._outlinepoints.add(points);
  37994. }
  37995. PolygonMeshBuilder.prototype.addHole = function (hole) {
  37996. this._swctx.addHole(this._points.add(hole));
  37997. var holepoints = new PolygonPoints();
  37998. holepoints.add(hole);
  37999. this._holes.push(holepoints);
  38000. return this;
  38001. };
  38002. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  38003. var _this = this;
  38004. if (updatable === void 0) { updatable = false; }
  38005. var result = new BABYLON.Mesh(this._name, this._scene);
  38006. var normals = [];
  38007. var positions = [];
  38008. var uvs = [];
  38009. var bounds = this._points.computeBounds();
  38010. this._points.elements.forEach(function (p) {
  38011. normals.push(0, 1.0, 0);
  38012. positions.push(p.x, 0, p.y);
  38013. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  38014. });
  38015. var indices = [];
  38016. this._swctx.triangulate();
  38017. this._swctx.getTriangles().forEach(function (triangle) {
  38018. triangle.getPoints().forEach(function (point) {
  38019. indices.push(point.index);
  38020. });
  38021. });
  38022. if (depth > 0) {
  38023. var positionscount = (positions.length / 3); //get the current pointcount
  38024. this._points.elements.forEach(function (p) {
  38025. normals.push(0, -1.0, 0);
  38026. positions.push(p.x, -depth, p.y);
  38027. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  38028. });
  38029. var p1; //we need to change order of point so the triangles are made in the rigth way.
  38030. var p2;
  38031. var poscounter = 0;
  38032. this._swctx.getTriangles().forEach(function (triangle) {
  38033. triangle.getPoints().forEach(function (point) {
  38034. switch (poscounter) {
  38035. case 0:
  38036. p1 = point;
  38037. break;
  38038. case 1:
  38039. p2 = point;
  38040. break;
  38041. case 2:
  38042. indices.push(point.index + positionscount);
  38043. indices.push(p2.index + positionscount);
  38044. indices.push(p1.index + positionscount);
  38045. poscounter = -1;
  38046. break;
  38047. }
  38048. poscounter++;
  38049. //indices.push((<IndexedVector2>point).index + positionscount);
  38050. });
  38051. });
  38052. //Add the sides
  38053. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  38054. this._holes.forEach(function (hole) {
  38055. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  38056. });
  38057. }
  38058. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  38059. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  38060. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  38061. result.setIndices(indices);
  38062. return result;
  38063. };
  38064. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  38065. var StartIndex = positions.length / 3;
  38066. var ulength = 0;
  38067. for (var i = 0; i < points.elements.length; i++) {
  38068. var p = points.elements[i];
  38069. var p1;
  38070. if ((i + 1) > points.elements.length - 1) {
  38071. p1 = points.elements[0];
  38072. }
  38073. else {
  38074. p1 = points.elements[i + 1];
  38075. }
  38076. positions.push(p.x, 0, p.y);
  38077. positions.push(p.x, -depth, p.y);
  38078. positions.push(p1.x, 0, p1.y);
  38079. positions.push(p1.x, -depth, p1.y);
  38080. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  38081. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  38082. var v3 = v2.subtract(v1);
  38083. var v4 = new BABYLON.Vector3(0, 1, 0);
  38084. var vn = BABYLON.Vector3.Cross(v3, v4);
  38085. vn = vn.normalize();
  38086. uvs.push(ulength / bounds.width, 0);
  38087. uvs.push(ulength / bounds.width, 1);
  38088. ulength += v3.length();
  38089. uvs.push((ulength / bounds.width), 0);
  38090. uvs.push((ulength / bounds.width), 1);
  38091. if (!flip) {
  38092. normals.push(-vn.x, -vn.y, -vn.z);
  38093. normals.push(-vn.x, -vn.y, -vn.z);
  38094. normals.push(-vn.x, -vn.y, -vn.z);
  38095. normals.push(-vn.x, -vn.y, -vn.z);
  38096. indices.push(StartIndex);
  38097. indices.push(StartIndex + 1);
  38098. indices.push(StartIndex + 2);
  38099. indices.push(StartIndex + 1);
  38100. indices.push(StartIndex + 3);
  38101. indices.push(StartIndex + 2);
  38102. }
  38103. else {
  38104. normals.push(vn.x, vn.y, vn.z);
  38105. normals.push(vn.x, vn.y, vn.z);
  38106. normals.push(vn.x, vn.y, vn.z);
  38107. normals.push(vn.x, vn.y, vn.z);
  38108. indices.push(StartIndex);
  38109. indices.push(StartIndex + 2);
  38110. indices.push(StartIndex + 1);
  38111. indices.push(StartIndex + 1);
  38112. indices.push(StartIndex + 2);
  38113. indices.push(StartIndex + 3);
  38114. }
  38115. StartIndex += 4;
  38116. }
  38117. ;
  38118. };
  38119. return PolygonMeshBuilder;
  38120. }());
  38121. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  38122. })(BABYLON || (BABYLON = {}));
  38123. var BABYLON;
  38124. (function (BABYLON) {
  38125. var Octree = (function () {
  38126. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  38127. if (maxDepth === void 0) { maxDepth = 2; }
  38128. this.maxDepth = maxDepth;
  38129. this.dynamicContent = new Array();
  38130. this._maxBlockCapacity = maxBlockCapacity || 64;
  38131. this._selectionContent = new BABYLON.SmartArray(1024);
  38132. this._creationFunc = creationFunc;
  38133. }
  38134. // Methods
  38135. Octree.prototype.update = function (worldMin, worldMax, entries) {
  38136. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  38137. };
  38138. Octree.prototype.addMesh = function (entry) {
  38139. for (var index = 0; index < this.blocks.length; index++) {
  38140. var block = this.blocks[index];
  38141. block.addEntry(entry);
  38142. }
  38143. };
  38144. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  38145. this._selectionContent.reset();
  38146. for (var index = 0; index < this.blocks.length; index++) {
  38147. var block = this.blocks[index];
  38148. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  38149. }
  38150. if (allowDuplicate) {
  38151. this._selectionContent.concat(this.dynamicContent);
  38152. }
  38153. else {
  38154. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38155. }
  38156. return this._selectionContent;
  38157. };
  38158. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  38159. this._selectionContent.reset();
  38160. for (var index = 0; index < this.blocks.length; index++) {
  38161. var block = this.blocks[index];
  38162. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  38163. }
  38164. if (allowDuplicate) {
  38165. this._selectionContent.concat(this.dynamicContent);
  38166. }
  38167. else {
  38168. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38169. }
  38170. return this._selectionContent;
  38171. };
  38172. Octree.prototype.intersectsRay = function (ray) {
  38173. this._selectionContent.reset();
  38174. for (var index = 0; index < this.blocks.length; index++) {
  38175. var block = this.blocks[index];
  38176. block.intersectsRay(ray, this._selectionContent);
  38177. }
  38178. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38179. return this._selectionContent;
  38180. };
  38181. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  38182. target.blocks = new Array();
  38183. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  38184. // Segmenting space
  38185. for (var x = 0; x < 2; x++) {
  38186. for (var y = 0; y < 2; y++) {
  38187. for (var z = 0; z < 2; z++) {
  38188. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  38189. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  38190. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  38191. block.addEntries(entries);
  38192. target.blocks.push(block);
  38193. }
  38194. }
  38195. }
  38196. };
  38197. Octree.CreationFuncForMeshes = function (entry, block) {
  38198. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38199. block.entries.push(entry);
  38200. }
  38201. };
  38202. Octree.CreationFuncForSubMeshes = function (entry, block) {
  38203. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38204. block.entries.push(entry);
  38205. }
  38206. };
  38207. return Octree;
  38208. }());
  38209. BABYLON.Octree = Octree;
  38210. })(BABYLON || (BABYLON = {}));
  38211. var BABYLON;
  38212. (function (BABYLON) {
  38213. var OctreeBlock = (function () {
  38214. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  38215. this.entries = new Array();
  38216. this._boundingVectors = new Array();
  38217. this._capacity = capacity;
  38218. this._depth = depth;
  38219. this._maxDepth = maxDepth;
  38220. this._creationFunc = creationFunc;
  38221. this._minPoint = minPoint;
  38222. this._maxPoint = maxPoint;
  38223. this._boundingVectors.push(minPoint.clone());
  38224. this._boundingVectors.push(maxPoint.clone());
  38225. this._boundingVectors.push(minPoint.clone());
  38226. this._boundingVectors[2].x = maxPoint.x;
  38227. this._boundingVectors.push(minPoint.clone());
  38228. this._boundingVectors[3].y = maxPoint.y;
  38229. this._boundingVectors.push(minPoint.clone());
  38230. this._boundingVectors[4].z = maxPoint.z;
  38231. this._boundingVectors.push(maxPoint.clone());
  38232. this._boundingVectors[5].z = minPoint.z;
  38233. this._boundingVectors.push(maxPoint.clone());
  38234. this._boundingVectors[6].x = minPoint.x;
  38235. this._boundingVectors.push(maxPoint.clone());
  38236. this._boundingVectors[7].y = minPoint.y;
  38237. }
  38238. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  38239. // Property
  38240. get: function () {
  38241. return this._capacity;
  38242. },
  38243. enumerable: true,
  38244. configurable: true
  38245. });
  38246. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  38247. get: function () {
  38248. return this._minPoint;
  38249. },
  38250. enumerable: true,
  38251. configurable: true
  38252. });
  38253. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  38254. get: function () {
  38255. return this._maxPoint;
  38256. },
  38257. enumerable: true,
  38258. configurable: true
  38259. });
  38260. // Methods
  38261. OctreeBlock.prototype.addEntry = function (entry) {
  38262. if (this.blocks) {
  38263. for (var index = 0; index < this.blocks.length; index++) {
  38264. var block = this.blocks[index];
  38265. block.addEntry(entry);
  38266. }
  38267. return;
  38268. }
  38269. this._creationFunc(entry, this);
  38270. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  38271. this.createInnerBlocks();
  38272. }
  38273. };
  38274. OctreeBlock.prototype.addEntries = function (entries) {
  38275. for (var index = 0; index < entries.length; index++) {
  38276. var mesh = entries[index];
  38277. this.addEntry(mesh);
  38278. }
  38279. };
  38280. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  38281. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  38282. if (this.blocks) {
  38283. for (var index = 0; index < this.blocks.length; index++) {
  38284. var block = this.blocks[index];
  38285. block.select(frustumPlanes, selection, allowDuplicate);
  38286. }
  38287. return;
  38288. }
  38289. if (allowDuplicate) {
  38290. selection.concat(this.entries);
  38291. }
  38292. else {
  38293. selection.concatWithNoDuplicate(this.entries);
  38294. }
  38295. }
  38296. };
  38297. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  38298. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  38299. if (this.blocks) {
  38300. for (var index = 0; index < this.blocks.length; index++) {
  38301. var block = this.blocks[index];
  38302. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  38303. }
  38304. return;
  38305. }
  38306. if (allowDuplicate) {
  38307. selection.concat(this.entries);
  38308. }
  38309. else {
  38310. selection.concatWithNoDuplicate(this.entries);
  38311. }
  38312. }
  38313. };
  38314. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  38315. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  38316. if (this.blocks) {
  38317. for (var index = 0; index < this.blocks.length; index++) {
  38318. var block = this.blocks[index];
  38319. block.intersectsRay(ray, selection);
  38320. }
  38321. return;
  38322. }
  38323. selection.concatWithNoDuplicate(this.entries);
  38324. }
  38325. };
  38326. OctreeBlock.prototype.createInnerBlocks = function () {
  38327. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  38328. };
  38329. return OctreeBlock;
  38330. }());
  38331. BABYLON.OctreeBlock = OctreeBlock;
  38332. })(BABYLON || (BABYLON = {}));
  38333. var BABYLON;
  38334. (function (BABYLON) {
  38335. var BlurPostProcess = (function (_super) {
  38336. __extends(BlurPostProcess, _super);
  38337. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  38338. var _this = this;
  38339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38340. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  38341. this.direction = direction;
  38342. this.blurWidth = blurWidth;
  38343. this.onApply = function (effect) {
  38344. effect.setFloat2("screenSize", _this.width, _this.height);
  38345. effect.setVector2("direction", _this.direction);
  38346. effect.setFloat("blurWidth", _this.blurWidth);
  38347. };
  38348. }
  38349. return BlurPostProcess;
  38350. }(BABYLON.PostProcess));
  38351. BABYLON.BlurPostProcess = BlurPostProcess;
  38352. })(BABYLON || (BABYLON = {}));
  38353. var BABYLON;
  38354. (function (BABYLON) {
  38355. var RefractionPostProcess = (function (_super) {
  38356. __extends(RefractionPostProcess, _super);
  38357. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  38358. var _this = this;
  38359. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  38360. this.color = color;
  38361. this.depth = depth;
  38362. this.colorLevel = colorLevel;
  38363. this.onActivate = function (cam) {
  38364. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  38365. };
  38366. this.onApply = function (effect) {
  38367. effect.setColor3("baseColor", _this.color);
  38368. effect.setFloat("depth", _this.depth);
  38369. effect.setFloat("colorLevel", _this.colorLevel);
  38370. effect.setTexture("refractionSampler", _this._refRexture);
  38371. };
  38372. }
  38373. // Methods
  38374. RefractionPostProcess.prototype.dispose = function (camera) {
  38375. if (this._refRexture) {
  38376. this._refRexture.dispose();
  38377. }
  38378. _super.prototype.dispose.call(this, camera);
  38379. };
  38380. return RefractionPostProcess;
  38381. }(BABYLON.PostProcess));
  38382. BABYLON.RefractionPostProcess = RefractionPostProcess;
  38383. })(BABYLON || (BABYLON = {}));
  38384. var BABYLON;
  38385. (function (BABYLON) {
  38386. var BlackAndWhitePostProcess = (function (_super) {
  38387. __extends(BlackAndWhitePostProcess, _super);
  38388. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38389. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  38390. }
  38391. return BlackAndWhitePostProcess;
  38392. }(BABYLON.PostProcess));
  38393. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  38394. })(BABYLON || (BABYLON = {}));
  38395. var BABYLON;
  38396. (function (BABYLON) {
  38397. var ConvolutionPostProcess = (function (_super) {
  38398. __extends(ConvolutionPostProcess, _super);
  38399. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  38400. var _this = this;
  38401. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  38402. this.kernel = kernel;
  38403. this.onApply = function (effect) {
  38404. effect.setFloat2("screenSize", _this.width, _this.height);
  38405. effect.setArray("kernel", _this.kernel);
  38406. };
  38407. }
  38408. // Statics
  38409. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  38410. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  38411. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  38412. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  38413. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  38414. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  38415. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  38416. return ConvolutionPostProcess;
  38417. }(BABYLON.PostProcess));
  38418. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  38419. })(BABYLON || (BABYLON = {}));
  38420. var BABYLON;
  38421. (function (BABYLON) {
  38422. var FilterPostProcess = (function (_super) {
  38423. __extends(FilterPostProcess, _super);
  38424. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  38425. var _this = this;
  38426. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  38427. this.kernelMatrix = kernelMatrix;
  38428. this.onApply = function (effect) {
  38429. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  38430. };
  38431. }
  38432. return FilterPostProcess;
  38433. }(BABYLON.PostProcess));
  38434. BABYLON.FilterPostProcess = FilterPostProcess;
  38435. })(BABYLON || (BABYLON = {}));
  38436. var BABYLON;
  38437. (function (BABYLON) {
  38438. var FxaaPostProcess = (function (_super) {
  38439. __extends(FxaaPostProcess, _super);
  38440. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38441. var _this = this;
  38442. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  38443. this.onSizeChanged = function () {
  38444. _this.texelWidth = 1.0 / _this.width;
  38445. _this.texelHeight = 1.0 / _this.height;
  38446. };
  38447. this.onApply = function (effect) {
  38448. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  38449. };
  38450. }
  38451. return FxaaPostProcess;
  38452. }(BABYLON.PostProcess));
  38453. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38454. })(BABYLON || (BABYLON = {}));
  38455. var BABYLON;
  38456. (function (BABYLON) {
  38457. var StereoscopicInterlacePostProcess = (function (_super) {
  38458. __extends(StereoscopicInterlacePostProcess, _super);
  38459. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  38460. var _this = this;
  38461. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  38462. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  38463. this.onSizeChanged = function () {
  38464. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  38465. };
  38466. this.onApply = function (effect) {
  38467. effect.setTextureFromPostProcess("camASampler", postProcessA);
  38468. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  38469. };
  38470. }
  38471. return StereoscopicInterlacePostProcess;
  38472. }(BABYLON.PostProcess));
  38473. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  38474. })(BABYLON || (BABYLON = {}));
  38475. var BABYLON;
  38476. (function (BABYLON) {
  38477. var LensFlare = (function () {
  38478. function LensFlare(size, position, color, imgUrl, system) {
  38479. this.size = size;
  38480. this.position = position;
  38481. this.dispose = function () {
  38482. if (this.texture) {
  38483. this.texture.dispose();
  38484. }
  38485. // Remove from scene
  38486. var index = this._system.lensFlares.indexOf(this);
  38487. this._system.lensFlares.splice(index, 1);
  38488. };
  38489. this.color = color || new BABYLON.Color3(1, 1, 1);
  38490. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  38491. this._system = system;
  38492. system.lensFlares.push(this);
  38493. }
  38494. return LensFlare;
  38495. }());
  38496. BABYLON.LensFlare = LensFlare;
  38497. })(BABYLON || (BABYLON = {}));
  38498. var BABYLON;
  38499. (function (BABYLON) {
  38500. var LensFlareSystem = (function () {
  38501. function LensFlareSystem(name, emitter, scene) {
  38502. this.name = name;
  38503. this.lensFlares = new Array();
  38504. this.borderLimit = 300;
  38505. this.layerMask = 0x0FFFFFFF;
  38506. this._vertexDeclaration = [2];
  38507. this._vertexStrideSize = 2 * 4;
  38508. this._isEnabled = true;
  38509. this._scene = scene;
  38510. this._emitter = emitter;
  38511. scene.lensFlareSystems.push(this);
  38512. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  38513. // VBO
  38514. var vertices = [];
  38515. vertices.push(1, 1);
  38516. vertices.push(-1, 1);
  38517. vertices.push(-1, -1);
  38518. vertices.push(1, -1);
  38519. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  38520. // Indices
  38521. var indices = [];
  38522. indices.push(0);
  38523. indices.push(1);
  38524. indices.push(2);
  38525. indices.push(0);
  38526. indices.push(2);
  38527. indices.push(3);
  38528. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38529. // Effects
  38530. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  38531. }
  38532. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  38533. get: function () {
  38534. return this._isEnabled;
  38535. },
  38536. set: function (value) {
  38537. this._isEnabled = value;
  38538. },
  38539. enumerable: true,
  38540. configurable: true
  38541. });
  38542. LensFlareSystem.prototype.getScene = function () {
  38543. return this._scene;
  38544. };
  38545. LensFlareSystem.prototype.getEmitter = function () {
  38546. return this._emitter;
  38547. };
  38548. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  38549. this._emitter = newEmitter;
  38550. };
  38551. LensFlareSystem.prototype.getEmitterPosition = function () {
  38552. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  38553. };
  38554. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  38555. var position = this.getEmitterPosition();
  38556. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  38557. this._positionX = position.x;
  38558. this._positionY = position.y;
  38559. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  38560. if (position.z > 0) {
  38561. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  38562. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  38563. return true;
  38564. }
  38565. }
  38566. return false;
  38567. };
  38568. LensFlareSystem.prototype._isVisible = function () {
  38569. if (!this._isEnabled) {
  38570. return false;
  38571. }
  38572. var emitterPosition = this.getEmitterPosition();
  38573. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  38574. var distance = direction.length();
  38575. direction.normalize();
  38576. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  38577. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  38578. return !pickInfo.hit || pickInfo.distance > distance;
  38579. };
  38580. LensFlareSystem.prototype.render = function () {
  38581. if (!this._effect.isReady())
  38582. return false;
  38583. var engine = this._scene.getEngine();
  38584. var viewport = this._scene.activeCamera.viewport;
  38585. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  38586. // Position
  38587. if (!this.computeEffectivePosition(globalViewport)) {
  38588. return false;
  38589. }
  38590. // Visibility
  38591. if (!this._isVisible()) {
  38592. return false;
  38593. }
  38594. // Intensity
  38595. var awayX;
  38596. var awayY;
  38597. if (this._positionX < this.borderLimit + globalViewport.x) {
  38598. awayX = this.borderLimit + globalViewport.x - this._positionX;
  38599. }
  38600. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  38601. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  38602. }
  38603. else {
  38604. awayX = 0;
  38605. }
  38606. if (this._positionY < this.borderLimit + globalViewport.y) {
  38607. awayY = this.borderLimit + globalViewport.y - this._positionY;
  38608. }
  38609. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  38610. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  38611. }
  38612. else {
  38613. awayY = 0;
  38614. }
  38615. var away = (awayX > awayY) ? awayX : awayY;
  38616. if (away > this.borderLimit) {
  38617. away = this.borderLimit;
  38618. }
  38619. var intensity = 1.0 - (away / this.borderLimit);
  38620. if (intensity < 0) {
  38621. return false;
  38622. }
  38623. if (intensity > 1.0) {
  38624. intensity = 1.0;
  38625. }
  38626. // Position
  38627. var centerX = globalViewport.x + globalViewport.width / 2;
  38628. var centerY = globalViewport.y + globalViewport.height / 2;
  38629. var distX = centerX - this._positionX;
  38630. var distY = centerY - this._positionY;
  38631. // Effects
  38632. engine.enableEffect(this._effect);
  38633. engine.setState(false);
  38634. engine.setDepthBuffer(false);
  38635. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38636. // VBOs
  38637. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  38638. // Flares
  38639. for (var index = 0; index < this.lensFlares.length; index++) {
  38640. var flare = this.lensFlares[index];
  38641. var x = centerX - (distX * flare.position);
  38642. var y = centerY - (distY * flare.position);
  38643. var cw = flare.size;
  38644. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  38645. var cx = 2 * (x / globalViewport.width) - 1.0;
  38646. var cy = 1.0 - 2 * (y / globalViewport.height);
  38647. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  38648. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  38649. // Texture
  38650. this._effect.setTexture("textureSampler", flare.texture);
  38651. // Color
  38652. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  38653. // Draw order
  38654. engine.draw(true, 0, 6);
  38655. }
  38656. engine.setDepthBuffer(true);
  38657. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38658. return true;
  38659. };
  38660. LensFlareSystem.prototype.dispose = function () {
  38661. if (this._vertexBuffer) {
  38662. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  38663. this._vertexBuffer = null;
  38664. }
  38665. if (this._indexBuffer) {
  38666. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38667. this._indexBuffer = null;
  38668. }
  38669. while (this.lensFlares.length) {
  38670. this.lensFlares[0].dispose();
  38671. }
  38672. // Remove from scene
  38673. var index = this._scene.lensFlareSystems.indexOf(this);
  38674. this._scene.lensFlareSystems.splice(index, 1);
  38675. };
  38676. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  38677. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  38678. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  38679. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  38680. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  38681. var parsedFlare = parsedLensFlareSystem.flares[index];
  38682. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  38683. }
  38684. return lensFlareSystem;
  38685. };
  38686. LensFlareSystem.prototype.serialize = function () {
  38687. var serializationObject = {};
  38688. serializationObject.emitterId = this.getEmitter().id;
  38689. serializationObject.borderLimit = this.borderLimit;
  38690. serializationObject.flares = [];
  38691. for (var index = 0; index < this.lensFlares.length; index++) {
  38692. var flare = this.lensFlares[index];
  38693. serializationObject.flares.push({
  38694. size: flare.size,
  38695. position: flare.position,
  38696. color: flare.color.asArray(),
  38697. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  38698. });
  38699. }
  38700. return serializationObject;
  38701. };
  38702. return LensFlareSystem;
  38703. }());
  38704. BABYLON.LensFlareSystem = LensFlareSystem;
  38705. })(BABYLON || (BABYLON = {}));
  38706. var BABYLON;
  38707. (function (BABYLON) {
  38708. // We're mainly based on the logic defined into the FreeCamera code
  38709. var DeviceOrientationCamera = (function (_super) {
  38710. __extends(DeviceOrientationCamera, _super);
  38711. //-- end properties for backward compatibility for inputs
  38712. function DeviceOrientationCamera(name, position, scene) {
  38713. _super.call(this, name, position, scene);
  38714. this.inputs.addDeviceOrientation();
  38715. }
  38716. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  38717. //-- Begin properties for backward compatibility for inputs
  38718. get: function () {
  38719. var gamepad = this.inputs.attached["deviceOrientation"];
  38720. if (gamepad)
  38721. return gamepad.angularSensibility;
  38722. },
  38723. set: function (value) {
  38724. var gamepad = this.inputs.attached["deviceOrientation"];
  38725. if (gamepad)
  38726. gamepad.angularSensibility = value;
  38727. },
  38728. enumerable: true,
  38729. configurable: true
  38730. });
  38731. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  38732. get: function () {
  38733. var gamepad = this.inputs.attached["deviceOrientation"];
  38734. if (gamepad)
  38735. return gamepad.moveSensibility;
  38736. },
  38737. set: function (value) {
  38738. var gamepad = this.inputs.attached["deviceOrientation"];
  38739. if (gamepad)
  38740. gamepad.moveSensibility = value;
  38741. },
  38742. enumerable: true,
  38743. configurable: true
  38744. });
  38745. DeviceOrientationCamera.prototype.getTypeName = function () {
  38746. return "DeviceOrientationCamera";
  38747. };
  38748. return DeviceOrientationCamera;
  38749. }(BABYLON.FreeCamera));
  38750. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  38751. })(BABYLON || (BABYLON = {}));
  38752. var BABYLON;
  38753. (function (BABYLON) {
  38754. // We're mainly based on the logic defined into the FreeCamera code
  38755. var UniversalCamera = (function (_super) {
  38756. __extends(UniversalCamera, _super);
  38757. //-- end properties for backward compatibility for inputs
  38758. function UniversalCamera(name, position, scene) {
  38759. _super.call(this, name, position, scene);
  38760. this.inputs.addGamepad();
  38761. }
  38762. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  38763. //-- Begin properties for backward compatibility for inputs
  38764. get: function () {
  38765. var gamepad = this.inputs.attached["gamepad"];
  38766. if (gamepad)
  38767. return gamepad.gamepadAngularSensibility;
  38768. },
  38769. set: function (value) {
  38770. var gamepad = this.inputs.attached["gamepad"];
  38771. if (gamepad)
  38772. gamepad.gamepadAngularSensibility = value;
  38773. },
  38774. enumerable: true,
  38775. configurable: true
  38776. });
  38777. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  38778. get: function () {
  38779. var gamepad = this.inputs.attached["gamepad"];
  38780. if (gamepad)
  38781. return gamepad.gamepadMoveSensibility;
  38782. },
  38783. set: function (value) {
  38784. var gamepad = this.inputs.attached["gamepad"];
  38785. if (gamepad)
  38786. gamepad.gamepadMoveSensibility = value;
  38787. },
  38788. enumerable: true,
  38789. configurable: true
  38790. });
  38791. UniversalCamera.prototype.getTypeName = function () {
  38792. return "UniversalCamera";
  38793. };
  38794. return UniversalCamera;
  38795. }(BABYLON.TouchCamera));
  38796. BABYLON.UniversalCamera = UniversalCamera;
  38797. })(BABYLON || (BABYLON = {}));
  38798. var BABYLON;
  38799. (function (BABYLON) {
  38800. var Gamepads = (function () {
  38801. function Gamepads(ongamedpadconnected) {
  38802. var _this = this;
  38803. this.babylonGamepads = [];
  38804. this.oneGamepadConnected = false;
  38805. this.isMonitoring = false;
  38806. this.gamepadEventSupported = 'GamepadEvent' in window;
  38807. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38808. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38809. this._callbackGamepadConnected = ongamedpadconnected;
  38810. if (this.gamepadSupportAvailable) {
  38811. // Checking if the gamepad connected event is supported (like in Firefox)
  38812. if (this.gamepadEventSupported) {
  38813. this._onGamepadConnectedEvent = function (evt) {
  38814. _this._onGamepadConnected(evt);
  38815. };
  38816. this._onGamepadDisonnectedEvent = function (evt) {
  38817. _this._onGamepadDisconnected(evt);
  38818. };
  38819. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38820. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38821. }
  38822. else {
  38823. this._startMonitoringGamepads();
  38824. }
  38825. }
  38826. }
  38827. Gamepads.prototype.dispose = function () {
  38828. if (Gamepads.gamepadDOMInfo) {
  38829. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38830. }
  38831. if (this._onGamepadConnectedEvent) {
  38832. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38833. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38834. this._onGamepadConnectedEvent = null;
  38835. this._onGamepadDisonnectedEvent = null;
  38836. }
  38837. };
  38838. Gamepads.prototype._onGamepadConnected = function (evt) {
  38839. var newGamepad = this._addNewGamepad(evt.gamepad);
  38840. if (this._callbackGamepadConnected)
  38841. this._callbackGamepadConnected(newGamepad);
  38842. this._startMonitoringGamepads();
  38843. };
  38844. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38845. if (!this.oneGamepadConnected) {
  38846. this.oneGamepadConnected = true;
  38847. if (Gamepads.gamepadDOMInfo) {
  38848. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38849. Gamepads.gamepadDOMInfo = null;
  38850. }
  38851. }
  38852. var newGamepad;
  38853. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38854. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38855. }
  38856. else {
  38857. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38858. }
  38859. this.babylonGamepads.push(newGamepad);
  38860. return newGamepad;
  38861. };
  38862. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38863. // Remove the gamepad from the list of gamepads to monitor.
  38864. for (var i in this.babylonGamepads) {
  38865. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38866. this.babylonGamepads.splice(+i, 1);
  38867. break;
  38868. }
  38869. }
  38870. // If no gamepads are left, stop the polling loop.
  38871. if (this.babylonGamepads.length == 0) {
  38872. this._stopMonitoringGamepads();
  38873. }
  38874. };
  38875. Gamepads.prototype._startMonitoringGamepads = function () {
  38876. if (!this.isMonitoring) {
  38877. this.isMonitoring = true;
  38878. this._checkGamepadsStatus();
  38879. }
  38880. };
  38881. Gamepads.prototype._stopMonitoringGamepads = function () {
  38882. this.isMonitoring = false;
  38883. };
  38884. Gamepads.prototype._checkGamepadsStatus = function () {
  38885. var _this = this;
  38886. // updating gamepad objects
  38887. this._updateGamepadObjects();
  38888. for (var i in this.babylonGamepads) {
  38889. this.babylonGamepads[i].update();
  38890. }
  38891. if (this.isMonitoring) {
  38892. if (window.requestAnimationFrame) {
  38893. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38894. }
  38895. else if (window.mozRequestAnimationFrame) {
  38896. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38897. }
  38898. else if (window.webkitRequestAnimationFrame) {
  38899. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38900. }
  38901. }
  38902. };
  38903. // This function is called only on Chrome, which does not yet support
  38904. // connection/disconnection events, but requires you to monitor
  38905. // an array for changes.
  38906. Gamepads.prototype._updateGamepadObjects = function () {
  38907. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38908. for (var i = 0; i < gamepads.length; i++) {
  38909. if (gamepads[i]) {
  38910. if (!(gamepads[i].index in this.babylonGamepads)) {
  38911. var newGamepad = this._addNewGamepad(gamepads[i]);
  38912. if (this._callbackGamepadConnected) {
  38913. this._callbackGamepadConnected(newGamepad);
  38914. }
  38915. }
  38916. else {
  38917. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38918. }
  38919. }
  38920. }
  38921. };
  38922. return Gamepads;
  38923. }());
  38924. BABYLON.Gamepads = Gamepads;
  38925. var StickValues = (function () {
  38926. function StickValues(x, y) {
  38927. this.x = x;
  38928. this.y = y;
  38929. }
  38930. return StickValues;
  38931. }());
  38932. BABYLON.StickValues = StickValues;
  38933. var Gamepad = (function () {
  38934. function Gamepad(id, index, browserGamepad) {
  38935. this.id = id;
  38936. this.index = index;
  38937. this.browserGamepad = browserGamepad;
  38938. if (this.browserGamepad.axes.length >= 2) {
  38939. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38940. }
  38941. if (this.browserGamepad.axes.length >= 4) {
  38942. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38943. }
  38944. }
  38945. Gamepad.prototype.onleftstickchanged = function (callback) {
  38946. this._onleftstickchanged = callback;
  38947. };
  38948. Gamepad.prototype.onrightstickchanged = function (callback) {
  38949. this._onrightstickchanged = callback;
  38950. };
  38951. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38952. get: function () {
  38953. return this._leftStick;
  38954. },
  38955. set: function (newValues) {
  38956. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38957. this._onleftstickchanged(newValues);
  38958. }
  38959. this._leftStick = newValues;
  38960. },
  38961. enumerable: true,
  38962. configurable: true
  38963. });
  38964. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38965. get: function () {
  38966. return this._rightStick;
  38967. },
  38968. set: function (newValues) {
  38969. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38970. this._onrightstickchanged(newValues);
  38971. }
  38972. this._rightStick = newValues;
  38973. },
  38974. enumerable: true,
  38975. configurable: true
  38976. });
  38977. Gamepad.prototype.update = function () {
  38978. if (this._leftStick) {
  38979. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38980. }
  38981. if (this._rightStick) {
  38982. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38983. }
  38984. };
  38985. return Gamepad;
  38986. }());
  38987. BABYLON.Gamepad = Gamepad;
  38988. var GenericPad = (function (_super) {
  38989. __extends(GenericPad, _super);
  38990. function GenericPad(id, index, gamepad) {
  38991. _super.call(this, id, index, gamepad);
  38992. this.id = id;
  38993. this.index = index;
  38994. this.gamepad = gamepad;
  38995. this._buttons = new Array(gamepad.buttons.length);
  38996. }
  38997. GenericPad.prototype.onbuttondown = function (callback) {
  38998. this._onbuttondown = callback;
  38999. };
  39000. GenericPad.prototype.onbuttonup = function (callback) {
  39001. this._onbuttonup = callback;
  39002. };
  39003. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  39004. if (newValue !== currentValue) {
  39005. if (this._onbuttondown && newValue === 1) {
  39006. this._onbuttondown(buttonIndex);
  39007. }
  39008. if (this._onbuttonup && newValue === 0) {
  39009. this._onbuttonup(buttonIndex);
  39010. }
  39011. }
  39012. return newValue;
  39013. };
  39014. GenericPad.prototype.update = function () {
  39015. _super.prototype.update.call(this);
  39016. for (var index = 0; index < this._buttons.length; index++) {
  39017. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  39018. }
  39019. };
  39020. return GenericPad;
  39021. }(Gamepad));
  39022. BABYLON.GenericPad = GenericPad;
  39023. (function (Xbox360Button) {
  39024. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  39025. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  39026. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  39027. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  39028. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  39029. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  39030. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  39031. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  39032. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  39033. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  39034. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  39035. var Xbox360Button = BABYLON.Xbox360Button;
  39036. (function (Xbox360Dpad) {
  39037. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  39038. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  39039. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  39040. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  39041. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  39042. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  39043. var Xbox360Pad = (function (_super) {
  39044. __extends(Xbox360Pad, _super);
  39045. function Xbox360Pad() {
  39046. _super.apply(this, arguments);
  39047. this._leftTrigger = 0;
  39048. this._rightTrigger = 0;
  39049. this._buttonA = 0;
  39050. this._buttonB = 0;
  39051. this._buttonX = 0;
  39052. this._buttonY = 0;
  39053. this._buttonBack = 0;
  39054. this._buttonStart = 0;
  39055. this._buttonLB = 0;
  39056. this._buttonRB = 0;
  39057. this._buttonLeftStick = 0;
  39058. this._buttonRightStick = 0;
  39059. this._dPadUp = 0;
  39060. this._dPadDown = 0;
  39061. this._dPadLeft = 0;
  39062. this._dPadRight = 0;
  39063. }
  39064. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  39065. this._onlefttriggerchanged = callback;
  39066. };
  39067. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  39068. this._onrighttriggerchanged = callback;
  39069. };
  39070. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  39071. get: function () {
  39072. return this._leftTrigger;
  39073. },
  39074. set: function (newValue) {
  39075. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  39076. this._onlefttriggerchanged(newValue);
  39077. }
  39078. this._leftTrigger = newValue;
  39079. },
  39080. enumerable: true,
  39081. configurable: true
  39082. });
  39083. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  39084. get: function () {
  39085. return this._rightTrigger;
  39086. },
  39087. set: function (newValue) {
  39088. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  39089. this._onrighttriggerchanged(newValue);
  39090. }
  39091. this._rightTrigger = newValue;
  39092. },
  39093. enumerable: true,
  39094. configurable: true
  39095. });
  39096. Xbox360Pad.prototype.onbuttondown = function (callback) {
  39097. this._onbuttondown = callback;
  39098. };
  39099. Xbox360Pad.prototype.onbuttonup = function (callback) {
  39100. this._onbuttonup = callback;
  39101. };
  39102. Xbox360Pad.prototype.ondpaddown = function (callback) {
  39103. this._ondpaddown = callback;
  39104. };
  39105. Xbox360Pad.prototype.ondpadup = function (callback) {
  39106. this._ondpadup = callback;
  39107. };
  39108. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  39109. if (newValue !== currentValue) {
  39110. if (this._onbuttondown && newValue === 1) {
  39111. this._onbuttondown(buttonType);
  39112. }
  39113. if (this._onbuttonup && newValue === 0) {
  39114. this._onbuttonup(buttonType);
  39115. }
  39116. }
  39117. return newValue;
  39118. };
  39119. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  39120. if (newValue !== currentValue) {
  39121. if (this._ondpaddown && newValue === 1) {
  39122. this._ondpaddown(buttonType);
  39123. }
  39124. if (this._ondpadup && newValue === 0) {
  39125. this._ondpadup(buttonType);
  39126. }
  39127. }
  39128. return newValue;
  39129. };
  39130. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  39131. get: function () {
  39132. return this._buttonA;
  39133. },
  39134. set: function (value) {
  39135. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  39136. },
  39137. enumerable: true,
  39138. configurable: true
  39139. });
  39140. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  39141. get: function () {
  39142. return this._buttonB;
  39143. },
  39144. set: function (value) {
  39145. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  39146. },
  39147. enumerable: true,
  39148. configurable: true
  39149. });
  39150. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  39151. get: function () {
  39152. return this._buttonX;
  39153. },
  39154. set: function (value) {
  39155. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  39156. },
  39157. enumerable: true,
  39158. configurable: true
  39159. });
  39160. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  39161. get: function () {
  39162. return this._buttonY;
  39163. },
  39164. set: function (value) {
  39165. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  39166. },
  39167. enumerable: true,
  39168. configurable: true
  39169. });
  39170. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  39171. get: function () {
  39172. return this._buttonStart;
  39173. },
  39174. set: function (value) {
  39175. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39176. },
  39177. enumerable: true,
  39178. configurable: true
  39179. });
  39180. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39181. get: function () {
  39182. return this._buttonBack;
  39183. },
  39184. set: function (value) {
  39185. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39186. },
  39187. enumerable: true,
  39188. configurable: true
  39189. });
  39190. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39191. get: function () {
  39192. return this._buttonLB;
  39193. },
  39194. set: function (value) {
  39195. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39196. },
  39197. enumerable: true,
  39198. configurable: true
  39199. });
  39200. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39201. get: function () {
  39202. return this._buttonRB;
  39203. },
  39204. set: function (value) {
  39205. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39206. },
  39207. enumerable: true,
  39208. configurable: true
  39209. });
  39210. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39211. get: function () {
  39212. return this._buttonLeftStick;
  39213. },
  39214. set: function (value) {
  39215. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39216. },
  39217. enumerable: true,
  39218. configurable: true
  39219. });
  39220. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39221. get: function () {
  39222. return this._buttonRightStick;
  39223. },
  39224. set: function (value) {
  39225. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39226. },
  39227. enumerable: true,
  39228. configurable: true
  39229. });
  39230. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39231. get: function () {
  39232. return this._dPadUp;
  39233. },
  39234. set: function (value) {
  39235. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39236. },
  39237. enumerable: true,
  39238. configurable: true
  39239. });
  39240. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39241. get: function () {
  39242. return this._dPadDown;
  39243. },
  39244. set: function (value) {
  39245. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39246. },
  39247. enumerable: true,
  39248. configurable: true
  39249. });
  39250. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39251. get: function () {
  39252. return this._dPadLeft;
  39253. },
  39254. set: function (value) {
  39255. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39256. },
  39257. enumerable: true,
  39258. configurable: true
  39259. });
  39260. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39261. get: function () {
  39262. return this._dPadRight;
  39263. },
  39264. set: function (value) {
  39265. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39266. },
  39267. enumerable: true,
  39268. configurable: true
  39269. });
  39270. Xbox360Pad.prototype.update = function () {
  39271. _super.prototype.update.call(this);
  39272. this.buttonA = this.browserGamepad.buttons[0].value;
  39273. this.buttonB = this.browserGamepad.buttons[1].value;
  39274. this.buttonX = this.browserGamepad.buttons[2].value;
  39275. this.buttonY = this.browserGamepad.buttons[3].value;
  39276. this.buttonLB = this.browserGamepad.buttons[4].value;
  39277. this.buttonRB = this.browserGamepad.buttons[5].value;
  39278. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39279. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39280. this.buttonBack = this.browserGamepad.buttons[8].value;
  39281. this.buttonStart = this.browserGamepad.buttons[9].value;
  39282. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39283. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39284. this.dPadUp = this.browserGamepad.buttons[12].value;
  39285. this.dPadDown = this.browserGamepad.buttons[13].value;
  39286. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39287. this.dPadRight = this.browserGamepad.buttons[15].value;
  39288. };
  39289. return Xbox360Pad;
  39290. }(Gamepad));
  39291. BABYLON.Xbox360Pad = Xbox360Pad;
  39292. })(BABYLON || (BABYLON = {}));
  39293. var BABYLON;
  39294. (function (BABYLON) {
  39295. // We're mainly based on the logic defined into the FreeCamera code
  39296. var GamepadCamera = (function (_super) {
  39297. __extends(GamepadCamera, _super);
  39298. //-- end properties for backward compatibility for inputs
  39299. function GamepadCamera(name, position, scene) {
  39300. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39301. _super.call(this, name, position, scene);
  39302. }
  39303. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  39304. //-- Begin properties for backward compatibility for inputs
  39305. get: function () {
  39306. var gamepad = this.inputs.attached["gamepad"];
  39307. if (gamepad)
  39308. return gamepad.gamepadAngularSensibility;
  39309. },
  39310. set: function (value) {
  39311. var gamepad = this.inputs.attached["gamepad"];
  39312. if (gamepad)
  39313. gamepad.gamepadAngularSensibility = value;
  39314. },
  39315. enumerable: true,
  39316. configurable: true
  39317. });
  39318. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  39319. get: function () {
  39320. var gamepad = this.inputs.attached["gamepad"];
  39321. if (gamepad)
  39322. return gamepad.gamepadMoveSensibility;
  39323. },
  39324. set: function (value) {
  39325. var gamepad = this.inputs.attached["gamepad"];
  39326. if (gamepad)
  39327. gamepad.gamepadMoveSensibility = value;
  39328. },
  39329. enumerable: true,
  39330. configurable: true
  39331. });
  39332. GamepadCamera.prototype.getTypeName = function () {
  39333. return "GamepadCamera";
  39334. };
  39335. return GamepadCamera;
  39336. }(BABYLON.UniversalCamera));
  39337. BABYLON.GamepadCamera = GamepadCamera;
  39338. })(BABYLON || (BABYLON = {}));
  39339. var BABYLON;
  39340. (function (BABYLON) {
  39341. var Analyser = (function () {
  39342. function Analyser(scene) {
  39343. this.SMOOTHING = 0.75;
  39344. this.FFT_SIZE = 512;
  39345. this.BARGRAPHAMPLITUDE = 256;
  39346. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39347. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39348. this._scene = scene;
  39349. this._audioEngine = BABYLON.Engine.audioEngine;
  39350. if (this._audioEngine.canUseWebAudio) {
  39351. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39352. this._webAudioAnalyser.minDecibels = -140;
  39353. this._webAudioAnalyser.maxDecibels = 0;
  39354. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39355. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39356. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39357. }
  39358. }
  39359. Analyser.prototype.getFrequencyBinCount = function () {
  39360. if (this._audioEngine.canUseWebAudio) {
  39361. return this._webAudioAnalyser.frequencyBinCount;
  39362. }
  39363. else {
  39364. return 0;
  39365. }
  39366. };
  39367. Analyser.prototype.getByteFrequencyData = function () {
  39368. if (this._audioEngine.canUseWebAudio) {
  39369. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39370. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39371. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  39372. }
  39373. return this._byteFreqs;
  39374. };
  39375. Analyser.prototype.getByteTimeDomainData = function () {
  39376. if (this._audioEngine.canUseWebAudio) {
  39377. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39378. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39379. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  39380. }
  39381. return this._byteTime;
  39382. };
  39383. Analyser.prototype.getFloatFrequencyData = function () {
  39384. if (this._audioEngine.canUseWebAudio) {
  39385. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39386. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39387. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  39388. }
  39389. return this._floatFreqs;
  39390. };
  39391. Analyser.prototype.drawDebugCanvas = function () {
  39392. var _this = this;
  39393. if (this._audioEngine.canUseWebAudio) {
  39394. if (!this._debugCanvas) {
  39395. this._debugCanvas = document.createElement("canvas");
  39396. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  39397. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  39398. this._debugCanvas.style.position = "absolute";
  39399. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  39400. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  39401. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  39402. document.body.appendChild(this._debugCanvas);
  39403. this._registerFunc = function () {
  39404. _this.drawDebugCanvas();
  39405. };
  39406. this._scene.registerBeforeRender(this._registerFunc);
  39407. }
  39408. if (this._registerFunc) {
  39409. var workingArray = this.getByteFrequencyData();
  39410. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  39411. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  39412. // Draw the frequency domain chart.
  39413. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  39414. var value = workingArray[i];
  39415. var percent = value / this.BARGRAPHAMPLITUDE;
  39416. var height = this.DEBUGCANVASSIZE.height * percent;
  39417. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  39418. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  39419. var hue = i / this.getFrequencyBinCount() * 360;
  39420. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  39421. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  39422. }
  39423. }
  39424. }
  39425. };
  39426. Analyser.prototype.stopDebugCanvas = function () {
  39427. if (this._debugCanvas) {
  39428. this._scene.unregisterBeforeRender(this._registerFunc);
  39429. this._registerFunc = null;
  39430. document.body.removeChild(this._debugCanvas);
  39431. this._debugCanvas = null;
  39432. this._debugCanvasContext = null;
  39433. }
  39434. };
  39435. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39436. if (this._audioEngine.canUseWebAudio) {
  39437. inputAudioNode.connect(this._webAudioAnalyser);
  39438. this._webAudioAnalyser.connect(outputAudioNode);
  39439. }
  39440. };
  39441. Analyser.prototype.dispose = function () {
  39442. if (this._audioEngine.canUseWebAudio) {
  39443. this._webAudioAnalyser.disconnect();
  39444. }
  39445. };
  39446. return Analyser;
  39447. }());
  39448. BABYLON.Analyser = Analyser;
  39449. })(BABYLON || (BABYLON = {}));
  39450. var BABYLON;
  39451. (function (BABYLON) {
  39452. var DepthRenderer = (function () {
  39453. function DepthRenderer(scene, type) {
  39454. var _this = this;
  39455. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  39456. this._viewMatrix = BABYLON.Matrix.Zero();
  39457. this._projectionMatrix = BABYLON.Matrix.Zero();
  39458. this._transformMatrix = BABYLON.Matrix.Zero();
  39459. this._worldViewProjection = BABYLON.Matrix.Zero();
  39460. this._scene = scene;
  39461. var engine = scene.getEngine();
  39462. // Render target
  39463. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  39464. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39465. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39466. this._depthMap.refreshRate = 1;
  39467. this._depthMap.renderParticles = false;
  39468. this._depthMap.renderList = null;
  39469. // set default depth value to 1.0 (far away)
  39470. this._depthMap.onClear = function (engine) {
  39471. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  39472. };
  39473. // Custom render function
  39474. var renderSubMesh = function (subMesh) {
  39475. var mesh = subMesh.getRenderingMesh();
  39476. var scene = _this._scene;
  39477. var engine = scene.getEngine();
  39478. // Culling
  39479. engine.setState(subMesh.getMaterial().backFaceCulling);
  39480. // Managing instances
  39481. var batch = mesh._getInstancesRenderList(subMesh._id);
  39482. if (batch.mustReturn) {
  39483. return;
  39484. }
  39485. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39486. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39487. engine.enableEffect(_this._effect);
  39488. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  39489. var material = subMesh.getMaterial();
  39490. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  39491. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  39492. // Alpha test
  39493. if (material && material.needAlphaTesting()) {
  39494. var alphaTexture = material.getAlphaTestTexture();
  39495. _this._effect.setTexture("diffuseSampler", alphaTexture);
  39496. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39497. }
  39498. // Bones
  39499. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39500. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39501. }
  39502. // Draw
  39503. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  39504. }
  39505. };
  39506. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  39507. var index;
  39508. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39509. renderSubMesh(opaqueSubMeshes.data[index]);
  39510. }
  39511. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39512. renderSubMesh(alphaTestSubMeshes.data[index]);
  39513. }
  39514. };
  39515. }
  39516. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  39517. var material = subMesh.getMaterial();
  39518. if (material.disableDepthWrite) {
  39519. return false;
  39520. }
  39521. var defines = [];
  39522. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39523. var mesh = subMesh.getMesh();
  39524. var scene = mesh.getScene();
  39525. // Alpha test
  39526. if (material && material.needAlphaTesting()) {
  39527. defines.push("#define ALPHATEST");
  39528. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39529. attribs.push(BABYLON.VertexBuffer.UVKind);
  39530. defines.push("#define UV1");
  39531. }
  39532. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39533. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39534. defines.push("#define UV2");
  39535. }
  39536. }
  39537. // Bones
  39538. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39541. if (mesh.numBoneInfluencers > 4) {
  39542. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39543. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39544. }
  39545. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39546. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39547. }
  39548. else {
  39549. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39550. }
  39551. // Instances
  39552. if (useInstances) {
  39553. defines.push("#define INSTANCES");
  39554. attribs.push("world0");
  39555. attribs.push("world1");
  39556. attribs.push("world2");
  39557. attribs.push("world3");
  39558. }
  39559. // Get correct effect
  39560. var join = defines.join("\n");
  39561. if (this._cachedDefines !== join) {
  39562. this._cachedDefines = join;
  39563. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  39564. }
  39565. return this._effect.isReady();
  39566. };
  39567. DepthRenderer.prototype.getDepthMap = function () {
  39568. return this._depthMap;
  39569. };
  39570. // Methods
  39571. DepthRenderer.prototype.dispose = function () {
  39572. this._depthMap.dispose();
  39573. };
  39574. return DepthRenderer;
  39575. }());
  39576. BABYLON.DepthRenderer = DepthRenderer;
  39577. })(BABYLON || (BABYLON = {}));
  39578. var BABYLON;
  39579. (function (BABYLON) {
  39580. var SSAORenderingPipeline = (function (_super) {
  39581. __extends(SSAORenderingPipeline, _super);
  39582. /**
  39583. * @constructor
  39584. * @param {string} name - The rendering pipeline name
  39585. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39586. * @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 }
  39587. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39588. */
  39589. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  39590. var _this = this;
  39591. _super.call(this, scene.getEngine(), name);
  39592. // Members
  39593. /**
  39594. * The PassPostProcess id in the pipeline that contains the original scene color
  39595. * @type {string}
  39596. */
  39597. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  39598. /**
  39599. * The SSAO PostProcess id in the pipeline
  39600. * @type {string}
  39601. */
  39602. this.SSAORenderEffect = "SSAORenderEffect";
  39603. /**
  39604. * The horizontal blur PostProcess id in the pipeline
  39605. * @type {string}
  39606. */
  39607. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  39608. /**
  39609. * The vertical blur PostProcess id in the pipeline
  39610. * @type {string}
  39611. */
  39612. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  39613. /**
  39614. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  39615. * @type {string}
  39616. */
  39617. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  39618. /**
  39619. * The output strength of the SSAO post-process. Default value is 1.0.
  39620. * @type {number}
  39621. */
  39622. this.totalStrength = 1.0;
  39623. /**
  39624. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  39625. * @type {number}
  39626. */
  39627. this.radius = 0.0001;
  39628. /**
  39629. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  39630. * Must not be equal to fallOff and superior to fallOff.
  39631. * Default value is 0.975
  39632. * @type {number}
  39633. */
  39634. this.area = 0.0075;
  39635. /**
  39636. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  39637. * Must not be equal to area and inferior to area.
  39638. * Default value is 0.0
  39639. * @type {number}
  39640. */
  39641. this.fallOff = 0.000001;
  39642. /**
  39643. * The base color of the SSAO post-process
  39644. * The final result is "base + ssao" between [0, 1]
  39645. * @type {number}
  39646. */
  39647. this.base = 0.5;
  39648. this._firstUpdate = true;
  39649. this._scene = scene;
  39650. // Set up assets
  39651. this._createRandomTexture();
  39652. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  39653. var ssaoRatio = ratio.ssaoRatio || ratio;
  39654. var combineRatio = ratio.combineRatio || ratio;
  39655. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39656. this._createSSAOPostProcess(ssaoRatio);
  39657. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39658. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39659. this._createSSAOCombinePostProcess(combineRatio);
  39660. // Set up pipeline
  39661. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  39662. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  39663. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  39664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  39665. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  39666. // Finish
  39667. scene.postProcessRenderPipelineManager.addPipeline(this);
  39668. if (cameras)
  39669. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39670. }
  39671. // Public Methods
  39672. /**
  39673. * Returns the horizontal blur PostProcess
  39674. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  39675. */
  39676. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  39677. return this._blurHPostProcess;
  39678. };
  39679. /**
  39680. * Returns the vertical blur PostProcess
  39681. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  39682. */
  39683. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  39684. return this._blurVPostProcess;
  39685. };
  39686. /**
  39687. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  39688. */
  39689. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  39690. if (disableDepthRender === void 0) { disableDepthRender = false; }
  39691. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39692. this._originalColorPostProcess = undefined;
  39693. this._ssaoPostProcess = undefined;
  39694. this._blurHPostProcess = undefined;
  39695. this._blurVPostProcess = undefined;
  39696. this._ssaoCombinePostProcess = undefined;
  39697. this._randomTexture.dispose();
  39698. if (disableDepthRender)
  39699. this._scene.disableDepthRenderer();
  39700. };
  39701. // Private Methods
  39702. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  39703. var _this = this;
  39704. var numSamples = 16;
  39705. var sampleSphere = [
  39706. 0.5381, 0.1856, -0.4319,
  39707. 0.1379, 0.2486, 0.4430,
  39708. 0.3371, 0.5679, -0.0057,
  39709. -0.6999, -0.0451, -0.0019,
  39710. 0.0689, -0.1598, -0.8547,
  39711. 0.0560, 0.0069, -0.1843,
  39712. -0.0146, 0.1402, 0.0762,
  39713. 0.0100, -0.1924, -0.0344,
  39714. -0.3577, -0.5301, -0.4358,
  39715. -0.3169, 0.1063, 0.0158,
  39716. 0.0103, -0.5869, 0.0046,
  39717. -0.0897, -0.4940, 0.3287,
  39718. 0.7119, -0.0154, -0.0918,
  39719. -0.0533, 0.0596, -0.5411,
  39720. 0.0352, -0.0631, 0.5460,
  39721. -0.4776, 0.2847, -0.0271
  39722. ];
  39723. var samplesFactor = 1.0 / numSamples;
  39724. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  39725. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  39726. "area", "fallOff", "base"
  39727. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  39728. this._ssaoPostProcess.onApply = function (effect) {
  39729. if (_this._firstUpdate) {
  39730. effect.setArray3("sampleSphere", sampleSphere);
  39731. effect.setFloat("samplesFactor", samplesFactor);
  39732. effect.setFloat("randTextureTiles", 4.0);
  39733. _this._firstUpdate = false;
  39734. }
  39735. effect.setFloat("totalStrength", _this.totalStrength);
  39736. effect.setFloat("radius", _this.radius);
  39737. effect.setFloat("area", _this.area);
  39738. effect.setFloat("fallOff", _this.fallOff);
  39739. effect.setFloat("base", _this.base);
  39740. effect.setTexture("textureSampler", _this._depthTexture);
  39741. effect.setTexture("randomSampler", _this._randomTexture);
  39742. };
  39743. };
  39744. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  39745. var _this = this;
  39746. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39747. this._ssaoCombinePostProcess.onApply = function (effect) {
  39748. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  39749. };
  39750. };
  39751. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  39752. var size = 512;
  39753. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39754. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39755. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39756. var context = this._randomTexture.getContext();
  39757. var rand = function (min, max) {
  39758. return Math.random() * (max - min) + min;
  39759. };
  39760. var randVector = BABYLON.Vector3.Zero();
  39761. for (var x = 0; x < size; x++) {
  39762. for (var y = 0; y < size; y++) {
  39763. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  39764. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  39765. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  39766. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  39767. context.fillRect(x, y, 1, 1);
  39768. }
  39769. }
  39770. this._randomTexture.update(false);
  39771. };
  39772. return SSAORenderingPipeline;
  39773. }(BABYLON.PostProcessRenderPipeline));
  39774. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  39775. })(BABYLON || (BABYLON = {}));
  39776. var BABYLON;
  39777. (function (BABYLON) {
  39778. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  39779. var VolumetricLightScatteringPostProcess = (function (_super) {
  39780. __extends(VolumetricLightScatteringPostProcess, _super);
  39781. /**
  39782. * @constructor
  39783. * @param {string} name - The post-process name
  39784. * @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)
  39785. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  39786. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  39787. * @param {number} samples - The post-process quality, default 100
  39788. * @param {number} samplingMode - The post-process filtering mode
  39789. * @param {BABYLON.Engine} engine - The babylon engine
  39790. * @param {boolean} reusable - If the post-process is reusable
  39791. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  39792. */
  39793. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  39794. var _this = this;
  39795. if (samples === void 0) { samples = 100; }
  39796. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39797. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  39798. this._screenCoordinates = BABYLON.Vector2.Zero();
  39799. /**
  39800. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  39801. * @type {Vector3}
  39802. */
  39803. this.customMeshPosition = BABYLON.Vector3.Zero();
  39804. /**
  39805. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  39806. * @type {boolean}
  39807. */
  39808. this.useCustomMeshPosition = false;
  39809. /**
  39810. * If the post-process should inverse the light scattering direction
  39811. * @type {boolean}
  39812. */
  39813. this.invert = true;
  39814. /**
  39815. * Array containing the excluded meshes not rendered in the internal pass
  39816. */
  39817. this.excludedMeshes = new Array();
  39818. /**
  39819. * Controls the overall intensity of the post-process
  39820. * @type {number}
  39821. */
  39822. this.exposure = 0.3;
  39823. /**
  39824. * Dissipates each sample's contribution in range [0, 1]
  39825. * @type {number}
  39826. */
  39827. this.decay = 0.96815;
  39828. /**
  39829. * Controls the overall intensity of each sample
  39830. * @type {number}
  39831. */
  39832. this.weight = 0.58767;
  39833. /**
  39834. * Controls the density of each sample
  39835. * @type {number}
  39836. */
  39837. this.density = 0.926;
  39838. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  39839. var engine = scene.getEngine();
  39840. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  39841. // Configure mesh
  39842. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  39843. // Configure
  39844. this._createPass(scene, ratio.passRatio || ratio);
  39845. this.onActivate = function (camera) {
  39846. if (!_this.isSupported) {
  39847. _this.dispose(camera);
  39848. }
  39849. _this.onActivate = null;
  39850. };
  39851. this.onApply = function (effect) {
  39852. _this._updateMeshScreenCoordinates(scene);
  39853. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  39854. effect.setFloat("exposure", _this.exposure);
  39855. effect.setFloat("decay", _this.decay);
  39856. effect.setFloat("weight", _this.weight);
  39857. effect.setFloat("density", _this.density);
  39858. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  39859. };
  39860. }
  39861. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  39862. get: function () {
  39863. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39864. return false;
  39865. },
  39866. set: function (useDiffuseColor) {
  39867. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39868. },
  39869. enumerable: true,
  39870. configurable: true
  39871. });
  39872. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  39873. var mesh = subMesh.getMesh();
  39874. // Render this.mesh as default
  39875. if (mesh === this.mesh) {
  39876. return mesh.material.isReady(mesh);
  39877. }
  39878. var defines = [];
  39879. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39880. var material = subMesh.getMaterial();
  39881. var needUV = false;
  39882. // Alpha test
  39883. if (material) {
  39884. if (material.needAlphaTesting()) {
  39885. defines.push("#define ALPHATEST");
  39886. }
  39887. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39888. attribs.push(BABYLON.VertexBuffer.UVKind);
  39889. defines.push("#define UV1");
  39890. }
  39891. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39892. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39893. defines.push("#define UV2");
  39894. }
  39895. }
  39896. // Bones
  39897. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39898. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39899. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39900. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39901. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39902. }
  39903. else {
  39904. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39905. }
  39906. // Instances
  39907. if (useInstances) {
  39908. defines.push("#define INSTANCES");
  39909. attribs.push("world0");
  39910. attribs.push("world1");
  39911. attribs.push("world2");
  39912. attribs.push("world3");
  39913. }
  39914. // Get correct effect
  39915. var join = defines.join("\n");
  39916. if (this._cachedDefines !== join) {
  39917. this._cachedDefines = join;
  39918. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  39919. }
  39920. return this._volumetricLightScatteringPass.isReady();
  39921. };
  39922. /**
  39923. * Sets the new light position for light scattering effect
  39924. * @param {BABYLON.Vector3} The new custom light position
  39925. */
  39926. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  39927. this.customMeshPosition = position;
  39928. };
  39929. /**
  39930. * Returns the light position for light scattering effect
  39931. * @return {BABYLON.Vector3} The custom light position
  39932. */
  39933. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  39934. return this.customMeshPosition;
  39935. };
  39936. /**
  39937. * Disposes the internal assets and detaches the post-process from the camera
  39938. */
  39939. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  39940. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  39941. if (rttIndex !== -1) {
  39942. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  39943. }
  39944. this._volumetricLightScatteringRTT.dispose();
  39945. _super.prototype.dispose.call(this, camera);
  39946. };
  39947. /**
  39948. * Returns the render target texture used by the post-process
  39949. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  39950. */
  39951. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  39952. return this._volumetricLightScatteringRTT;
  39953. };
  39954. // Private methods
  39955. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  39956. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  39957. return true;
  39958. }
  39959. return false;
  39960. };
  39961. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  39962. var _this = this;
  39963. var engine = scene.getEngine();
  39964. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39965. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39966. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39967. this._volumetricLightScatteringRTT.renderList = null;
  39968. this._volumetricLightScatteringRTT.renderParticles = false;
  39969. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  39970. // Custom render function for submeshes
  39971. var renderSubMesh = function (subMesh) {
  39972. var mesh = subMesh.getRenderingMesh();
  39973. if (_this._meshExcluded(mesh)) {
  39974. return;
  39975. }
  39976. var scene = mesh.getScene();
  39977. var engine = scene.getEngine();
  39978. // Culling
  39979. engine.setState(subMesh.getMaterial().backFaceCulling);
  39980. // Managing instances
  39981. var batch = mesh._getInstancesRenderList(subMesh._id);
  39982. if (batch.mustReturn) {
  39983. return;
  39984. }
  39985. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39986. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39987. var effect = _this._volumetricLightScatteringPass;
  39988. if (mesh === _this.mesh) {
  39989. effect = subMesh.getMaterial().getEffect();
  39990. }
  39991. engine.enableEffect(effect);
  39992. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  39993. if (mesh === _this.mesh) {
  39994. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  39995. }
  39996. else {
  39997. var material = subMesh.getMaterial();
  39998. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  39999. // Alpha test
  40000. if (material && material.needAlphaTesting()) {
  40001. var alphaTexture = material.getAlphaTestTexture();
  40002. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  40003. if (alphaTexture) {
  40004. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40005. }
  40006. }
  40007. // Bones
  40008. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40009. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40010. }
  40011. }
  40012. // Draw
  40013. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  40014. }
  40015. };
  40016. // Render target texture callbacks
  40017. var savedSceneClearColor;
  40018. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  40019. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  40020. savedSceneClearColor = scene.clearColor;
  40021. scene.clearColor = sceneClearColor;
  40022. };
  40023. this._volumetricLightScatteringRTT.onAfterRender = function () {
  40024. scene.clearColor = savedSceneClearColor;
  40025. };
  40026. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  40027. var engine = scene.getEngine();
  40028. var index;
  40029. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40030. renderSubMesh(opaqueSubMeshes.data[index]);
  40031. }
  40032. engine.setAlphaTesting(true);
  40033. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40034. renderSubMesh(alphaTestSubMeshes.data[index]);
  40035. }
  40036. engine.setAlphaTesting(false);
  40037. if (transparentSubMeshes.length) {
  40038. // Sort sub meshes
  40039. for (index = 0; index < transparentSubMeshes.length; index++) {
  40040. var submesh = transparentSubMeshes.data[index];
  40041. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  40042. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  40043. }
  40044. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  40045. sortedArray.sort(function (a, b) {
  40046. // Alpha index first
  40047. if (a._alphaIndex > b._alphaIndex) {
  40048. return 1;
  40049. }
  40050. if (a._alphaIndex < b._alphaIndex) {
  40051. return -1;
  40052. }
  40053. // Then distance to camera
  40054. if (a._distanceToCamera < b._distanceToCamera) {
  40055. return 1;
  40056. }
  40057. if (a._distanceToCamera > b._distanceToCamera) {
  40058. return -1;
  40059. }
  40060. return 0;
  40061. });
  40062. // Render sub meshes
  40063. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40064. for (index = 0; index < sortedArray.length; index++) {
  40065. renderSubMesh(sortedArray[index]);
  40066. }
  40067. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40068. }
  40069. };
  40070. };
  40071. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  40072. var transform = scene.getTransformMatrix();
  40073. var meshPosition;
  40074. if (this.useCustomMeshPosition) {
  40075. meshPosition = this.customMeshPosition;
  40076. }
  40077. else if (this.attachedNode) {
  40078. meshPosition = this.attachedNode.position;
  40079. }
  40080. else {
  40081. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  40082. }
  40083. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  40084. this._screenCoordinates.x = pos.x / this._viewPort.width;
  40085. this._screenCoordinates.y = pos.y / this._viewPort.height;
  40086. if (this.invert)
  40087. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  40088. };
  40089. // Static methods
  40090. /**
  40091. * Creates a default mesh for the Volumeric Light Scattering post-process
  40092. * @param {string} The mesh name
  40093. * @param {BABYLON.Scene} The scene where to create the mesh
  40094. * @return {BABYLON.Mesh} the default mesh
  40095. */
  40096. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  40097. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  40098. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  40099. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  40100. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  40101. mesh.material = material;
  40102. return mesh;
  40103. };
  40104. __decorate([
  40105. BABYLON.serializeAsVector3()
  40106. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  40107. __decorate([
  40108. BABYLON.serialize()
  40109. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  40110. __decorate([
  40111. BABYLON.serialize()
  40112. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  40113. __decorate([
  40114. BABYLON.serializeAsMeshReference()
  40115. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  40116. __decorate([
  40117. BABYLON.serialize()
  40118. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  40119. __decorate([
  40120. BABYLON.serialize()
  40121. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  40122. __decorate([
  40123. BABYLON.serialize()
  40124. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  40125. __decorate([
  40126. BABYLON.serialize()
  40127. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  40128. __decorate([
  40129. BABYLON.serialize()
  40130. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  40131. return VolumetricLightScatteringPostProcess;
  40132. }(BABYLON.PostProcess));
  40133. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  40134. })(BABYLON || (BABYLON = {}));
  40135. // BABYLON.JS Chromatic Aberration GLSL Shader
  40136. // Author: Olivier Guyot
  40137. // Separates very slightly R, G and B colors on the edges of the screen
  40138. // Inspired by Francois Tarlier & Martins Upitis
  40139. var BABYLON;
  40140. (function (BABYLON) {
  40141. var LensRenderingPipeline = (function (_super) {
  40142. __extends(LensRenderingPipeline, _super);
  40143. /**
  40144. * @constructor
  40145. *
  40146. * Effect parameters are as follow:
  40147. * {
  40148. * chromatic_aberration: number; // from 0 to x (1 for realism)
  40149. * edge_blur: number; // from 0 to x (1 for realism)
  40150. * distortion: number; // from 0 to x (1 for realism)
  40151. * grain_amount: number; // from 0 to 1
  40152. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  40153. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  40154. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  40155. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  40156. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  40157. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  40158. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  40159. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  40160. * }
  40161. * Note: if an effect parameter is unset, effect is disabled
  40162. *
  40163. * @param {string} name - The rendering pipeline name
  40164. * @param {object} parameters - An object containing all parameters (see above)
  40165. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40166. * @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)
  40167. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40168. */
  40169. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  40170. var _this = this;
  40171. if (ratio === void 0) { ratio = 1.0; }
  40172. _super.call(this, scene.getEngine(), name);
  40173. // Lens effects can be of the following:
  40174. // - chromatic aberration (slight shift of RGB colors)
  40175. // - blur on the edge of the lens
  40176. // - lens distortion
  40177. // - depth-of-field blur & highlights enhancing
  40178. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  40179. // - grain effect (noise or custom texture)
  40180. // Two additional texture samplers are needed:
  40181. // - depth map (for depth-of-field)
  40182. // - grain texture
  40183. /**
  40184. * The chromatic aberration PostProcess id in the pipeline
  40185. * @type {string}
  40186. */
  40187. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  40188. /**
  40189. * The highlights enhancing PostProcess id in the pipeline
  40190. * @type {string}
  40191. */
  40192. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  40193. /**
  40194. * The depth-of-field PostProcess id in the pipeline
  40195. * @type {string}
  40196. */
  40197. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  40198. this._scene = scene;
  40199. // Fetch texture samplers
  40200. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40201. if (parameters.grain_texture) {
  40202. this._grainTexture = parameters.grain_texture;
  40203. }
  40204. else {
  40205. this._createGrainTexture();
  40206. }
  40207. // save parameters
  40208. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  40209. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  40210. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  40211. this._distortion = parameters.distortion ? parameters.distortion : 0;
  40212. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  40213. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  40214. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  40215. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  40216. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  40217. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  40218. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  40219. // Create effects
  40220. this._createChromaticAberrationPostProcess(ratio);
  40221. this._createHighlightsPostProcess(ratio);
  40222. this._createDepthOfFieldPostProcess(ratio / 4);
  40223. // Set up pipeline
  40224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  40225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  40226. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  40227. if (this._highlightsGain === -1) {
  40228. this._disableEffect(this.HighlightsEnhancingEffect, null);
  40229. }
  40230. // Finish
  40231. scene.postProcessRenderPipelineManager.addPipeline(this);
  40232. if (cameras) {
  40233. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40234. }
  40235. }
  40236. // public methods (self explanatory)
  40237. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  40238. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  40239. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  40240. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  40241. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  40242. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  40243. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  40244. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  40245. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  40246. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  40247. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  40248. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  40249. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  40250. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  40251. };
  40252. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  40253. this._highlightsPostProcess.updateEffect();
  40254. };
  40255. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  40256. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  40257. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  40258. this._highlightsGain = amount;
  40259. };
  40260. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  40261. if (this._highlightsGain === -1) {
  40262. this._highlightsGain = 1.0;
  40263. }
  40264. this._highlightsThreshold = amount;
  40265. };
  40266. LensRenderingPipeline.prototype.disableHighlights = function () {
  40267. this._highlightsGain = -1;
  40268. };
  40269. /**
  40270. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  40271. */
  40272. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40273. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40274. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40275. this._chromaticAberrationPostProcess = undefined;
  40276. this._highlightsPostProcess = undefined;
  40277. this._depthOfFieldPostProcess = undefined;
  40278. this._grainTexture.dispose();
  40279. if (disableDepthRender)
  40280. this._scene.disableDepthRenderer();
  40281. };
  40282. // colors shifting and distortion
  40283. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  40284. var _this = this;
  40285. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  40286. [], // samplers
  40287. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40288. this._chromaticAberrationPostProcess.onApply = function (effect) {
  40289. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  40290. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40291. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40292. };
  40293. };
  40294. // highlights enhancing
  40295. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  40296. var _this = this;
  40297. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  40298. [], // samplers
  40299. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  40300. this._highlightsPostProcess.onApply = function (effect) {
  40301. effect.setFloat('gain', _this._highlightsGain);
  40302. effect.setFloat('threshold', _this._highlightsThreshold);
  40303. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  40304. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40305. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40306. };
  40307. };
  40308. // colors shifting and distortion
  40309. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  40310. var _this = this;
  40311. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  40312. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  40313. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  40314. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40315. this._depthOfFieldPostProcess.onApply = function (effect) {
  40316. effect.setTexture("depthSampler", _this._depthTexture);
  40317. effect.setTexture("grainSampler", _this._grainTexture);
  40318. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  40319. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  40320. effect.setFloat('grain_amount', _this._grainAmount);
  40321. effect.setBool('blur_noise', _this._blurNoise);
  40322. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40323. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40324. effect.setFloat('distortion', _this._distortion);
  40325. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  40326. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  40327. effect.setFloat('aperture', _this._dofAperture);
  40328. effect.setFloat('darken', _this._dofDarken);
  40329. effect.setFloat('edge_blur', _this._edgeBlur);
  40330. effect.setBool('highlights', (_this._highlightsGain !== -1));
  40331. effect.setFloat('near', _this._scene.activeCamera.minZ);
  40332. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  40333. };
  40334. };
  40335. // creates a black and white random noise texture, 512x512
  40336. LensRenderingPipeline.prototype._createGrainTexture = function () {
  40337. var size = 512;
  40338. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40339. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40340. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40341. var context = this._grainTexture.getContext();
  40342. var rand = function (min, max) {
  40343. return Math.random() * (max - min) + min;
  40344. };
  40345. var value;
  40346. for (var x = 0; x < size; x++) {
  40347. for (var y = 0; y < size; y++) {
  40348. value = Math.floor(rand(0.42, 0.58) * 255);
  40349. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  40350. context.fillRect(x, y, 1, 1);
  40351. }
  40352. }
  40353. this._grainTexture.update(false);
  40354. };
  40355. return LensRenderingPipeline;
  40356. }(BABYLON.PostProcessRenderPipeline));
  40357. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  40358. })(BABYLON || (BABYLON = {}));
  40359. //
  40360. // This post-process allows the modification of rendered colors by using
  40361. // a 'look-up table' (LUT). This effect is also called Color Grading.
  40362. //
  40363. // The object needs to be provided an url to a texture containing the color
  40364. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  40365. // Use an image editing software to tweak the LUT to match your needs.
  40366. //
  40367. // For an example of a color LUT, see here:
  40368. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  40369. // For explanations on color grading, see here:
  40370. // http://udn.epicgames.com/Three/ColorGrading.html
  40371. //
  40372. var BABYLON;
  40373. (function (BABYLON) {
  40374. var ColorCorrectionPostProcess = (function (_super) {
  40375. __extends(ColorCorrectionPostProcess, _super);
  40376. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  40377. var _this = this;
  40378. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  40379. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  40380. this._colorTableTexture.anisotropicFilteringLevel = 1;
  40381. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40382. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40383. this.onApply = function (effect) {
  40384. effect.setTexture("colorTable", _this._colorTableTexture);
  40385. };
  40386. }
  40387. return ColorCorrectionPostProcess;
  40388. }(BABYLON.PostProcess));
  40389. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  40390. })(BABYLON || (BABYLON = {}));
  40391. var BABYLON;
  40392. (function (BABYLON) {
  40393. var AnaglyphFreeCamera = (function (_super) {
  40394. __extends(AnaglyphFreeCamera, _super);
  40395. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  40396. _super.call(this, name, position, scene);
  40397. this.interaxialDistance = interaxialDistance;
  40398. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40399. }
  40400. AnaglyphFreeCamera.prototype.getTypeName = function () {
  40401. return "AnaglyphFreeCamera";
  40402. };
  40403. return AnaglyphFreeCamera;
  40404. }(BABYLON.FreeCamera));
  40405. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  40406. var AnaglyphArcRotateCamera = (function (_super) {
  40407. __extends(AnaglyphArcRotateCamera, _super);
  40408. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  40409. _super.call(this, name, alpha, beta, radius, target, scene);
  40410. this.interaxialDistance = interaxialDistance;
  40411. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40412. }
  40413. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  40414. return "AnaglyphArcRotateCamera";
  40415. };
  40416. return AnaglyphArcRotateCamera;
  40417. }(BABYLON.ArcRotateCamera));
  40418. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  40419. var AnaglyphGamepadCamera = (function (_super) {
  40420. __extends(AnaglyphGamepadCamera, _super);
  40421. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  40422. _super.call(this, name, position, scene);
  40423. this.interaxialDistance = interaxialDistance;
  40424. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40425. }
  40426. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  40427. return "AnaglyphGamepadCamera";
  40428. };
  40429. return AnaglyphGamepadCamera;
  40430. }(BABYLON.GamepadCamera));
  40431. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  40432. var AnaglyphUniversalCamera = (function (_super) {
  40433. __extends(AnaglyphUniversalCamera, _super);
  40434. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  40435. _super.call(this, name, position, scene);
  40436. this.interaxialDistance = interaxialDistance;
  40437. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40438. }
  40439. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  40440. return "AnaglyphUniversalCamera";
  40441. };
  40442. return AnaglyphUniversalCamera;
  40443. }(BABYLON.UniversalCamera));
  40444. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  40445. var StereoscopicFreeCamera = (function (_super) {
  40446. __extends(StereoscopicFreeCamera, _super);
  40447. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40448. _super.call(this, name, position, scene);
  40449. this.interaxialDistance = interaxialDistance;
  40450. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40451. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40452. }
  40453. StereoscopicFreeCamera.prototype.getTypeName = function () {
  40454. return "StereoscopicFreeCamera";
  40455. };
  40456. return StereoscopicFreeCamera;
  40457. }(BABYLON.FreeCamera));
  40458. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  40459. var StereoscopicArcRotateCamera = (function (_super) {
  40460. __extends(StereoscopicArcRotateCamera, _super);
  40461. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  40462. _super.call(this, name, alpha, beta, radius, target, scene);
  40463. this.interaxialDistance = interaxialDistance;
  40464. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40465. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40466. }
  40467. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  40468. return "StereoscopicArcRotateCamera";
  40469. };
  40470. return StereoscopicArcRotateCamera;
  40471. }(BABYLON.ArcRotateCamera));
  40472. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  40473. var StereoscopicGamepadCamera = (function (_super) {
  40474. __extends(StereoscopicGamepadCamera, _super);
  40475. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40476. _super.call(this, name, position, scene);
  40477. this.interaxialDistance = interaxialDistance;
  40478. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40479. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40480. }
  40481. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  40482. return "StereoscopicGamepadCamera";
  40483. };
  40484. return StereoscopicGamepadCamera;
  40485. }(BABYLON.GamepadCamera));
  40486. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  40487. var StereoscopicUniversalCamera = (function (_super) {
  40488. __extends(StereoscopicUniversalCamera, _super);
  40489. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40490. _super.call(this, name, position, scene);
  40491. this.interaxialDistance = interaxialDistance;
  40492. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40493. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40494. }
  40495. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  40496. return "StereoscopicUniversalCamera";
  40497. };
  40498. return StereoscopicUniversalCamera;
  40499. }(BABYLON.UniversalCamera));
  40500. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  40501. })(BABYLON || (BABYLON = {}));
  40502. var BABYLON;
  40503. (function (BABYLON) {
  40504. var HDRRenderingPipeline = (function (_super) {
  40505. __extends(HDRRenderingPipeline, _super);
  40506. /**
  40507. * @constructor
  40508. * @param {string} name - The rendering pipeline name
  40509. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40510. * @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)
  40511. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  40512. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40513. */
  40514. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  40515. var _this = this;
  40516. if (originalPostProcess === void 0) { originalPostProcess = null; }
  40517. _super.call(this, scene.getEngine(), name);
  40518. /**
  40519. * Public members
  40520. */
  40521. // Gaussian Blur
  40522. /**
  40523. * Gaussian blur coefficient
  40524. * @type {number}
  40525. */
  40526. this.gaussCoeff = 0.3;
  40527. /**
  40528. * Gaussian blur mean
  40529. * @type {number}
  40530. */
  40531. this.gaussMean = 1.0;
  40532. /**
  40533. * Gaussian blur standard deviation
  40534. * @type {number}
  40535. */
  40536. this.gaussStandDev = 0.8;
  40537. /**
  40538. * Gaussian blur multiplier. Multiplies the blur effect
  40539. * @type {number}
  40540. */
  40541. this.gaussMultiplier = 4.0;
  40542. // HDR
  40543. /**
  40544. * Exposure, controls the overall intensity of the pipeline
  40545. * @type {number}
  40546. */
  40547. this.exposure = 1.0;
  40548. /**
  40549. * Minimum luminance that the post-process can output. Luminance is >= 0
  40550. * @type {number}
  40551. */
  40552. this.minimumLuminance = 1.0;
  40553. /**
  40554. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  40555. * @type {number}
  40556. */
  40557. this.maximumLuminance = 1e20;
  40558. /**
  40559. * Increase rate for luminance: eye adaptation speed to dark
  40560. * @type {number}
  40561. */
  40562. this.luminanceIncreaserate = 0.5;
  40563. /**
  40564. * Decrease rate for luminance: eye adaptation speed to bright
  40565. * @type {number}
  40566. */
  40567. this.luminanceDecreaseRate = 0.5;
  40568. // Bright pass
  40569. /**
  40570. * Minimum luminance needed to compute HDR
  40571. * @type {number}
  40572. */
  40573. this.brightThreshold = 0.8;
  40574. this._needUpdate = true;
  40575. this._scene = scene;
  40576. // Bright pass
  40577. this._createBrightPassPostProcess(scene, ratio);
  40578. // Down sample X4
  40579. this._createDownSampleX4PostProcess(scene, ratio);
  40580. // Create gaussian blur post-processes
  40581. this._createGaussianBlurPostProcess(scene, ratio);
  40582. // Texture adder
  40583. this._createTextureAdderPostProcess(scene, ratio);
  40584. // Luminance generator
  40585. this._createLuminanceGeneratorPostProcess(scene);
  40586. // HDR
  40587. this._createHDRPostProcess(scene, ratio);
  40588. // Pass postprocess
  40589. if (originalPostProcess === null) {
  40590. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40591. }
  40592. else {
  40593. this._originalPostProcess = originalPostProcess;
  40594. }
  40595. // Configure pipeline
  40596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  40597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  40598. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  40599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  40600. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  40601. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  40602. var addDownSamplerPostProcess = function (id) {
  40603. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  40604. };
  40605. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40606. addDownSamplerPostProcess(i);
  40607. }
  40608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  40609. // Finish
  40610. scene.postProcessRenderPipelineManager.addPipeline(this);
  40611. if (cameras !== null) {
  40612. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40613. }
  40614. this.update();
  40615. }
  40616. /**
  40617. * Tells the pipeline to update its post-processes
  40618. */
  40619. HDRRenderingPipeline.prototype.update = function () {
  40620. this._needUpdate = true;
  40621. };
  40622. /**
  40623. * Returns the current calculated luminance
  40624. */
  40625. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  40626. return this._hdrCurrentLuminance;
  40627. };
  40628. /**
  40629. * Returns the currently drawn luminance
  40630. */
  40631. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  40632. return this._hdrOutputLuminance;
  40633. };
  40634. /**
  40635. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  40636. */
  40637. HDRRenderingPipeline.prototype.dispose = function () {
  40638. this._originalPostProcess = undefined;
  40639. this._brightPassPostProcess = undefined;
  40640. this._downSampleX4PostProcess = undefined;
  40641. this._guassianBlurHPostProcess = undefined;
  40642. this._guassianBlurVPostProcess = undefined;
  40643. this._textureAdderPostProcess = undefined;
  40644. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40645. this._downSamplePostProcesses[i] = undefined;
  40646. }
  40647. this._hdrPostProcess = undefined;
  40648. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40649. };
  40650. /**
  40651. * Creates the HDR post-process and computes the luminance adaptation
  40652. */
  40653. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  40654. var _this = this;
  40655. var hdrLastLuminance = 0.0;
  40656. this._hdrOutputLuminance = -1.0;
  40657. this._hdrCurrentLuminance = 1.0;
  40658. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  40659. this._hdrPostProcess.onApply = function (effect) {
  40660. if (_this._hdrOutputLuminance < 0.0) {
  40661. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40662. }
  40663. else {
  40664. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  40665. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  40666. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  40667. }
  40668. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  40669. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  40670. }
  40671. else {
  40672. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40673. }
  40674. }
  40675. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  40676. hdrLastLuminance += scene.getEngine().getDeltaTime();
  40677. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40678. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40679. effect.setFloat("exposure", _this.exposure);
  40680. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  40681. _this._needUpdate = false;
  40682. };
  40683. };
  40684. /**
  40685. * Texture Adder post-process
  40686. */
  40687. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  40688. var _this = this;
  40689. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  40690. this._textureAdderPostProcess.onApply = function (effect) {
  40691. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40692. };
  40693. };
  40694. /**
  40695. * Down sample X4 post-process
  40696. */
  40697. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  40698. var _this = this;
  40699. var downSampleX4Offsets = new Array(32);
  40700. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  40701. this._downSampleX4PostProcess.onApply = function (effect) {
  40702. if (_this._needUpdate) {
  40703. var id = 0;
  40704. for (var i = -2; i < 2; i++) {
  40705. for (var j = -2; j < 2; j++) {
  40706. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  40707. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  40708. id += 2;
  40709. }
  40710. }
  40711. }
  40712. effect.setArray2("dsOffsets", downSampleX4Offsets);
  40713. };
  40714. };
  40715. /**
  40716. * Bright pass post-process
  40717. */
  40718. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  40719. var _this = this;
  40720. var brightOffsets = new Array(8);
  40721. var brightPassCallback = function (effect) {
  40722. if (_this._needUpdate) {
  40723. var sU = (1.0 / _this._brightPassPostProcess.width);
  40724. var sV = (1.0 / _this._brightPassPostProcess.height);
  40725. brightOffsets[0] = -0.5 * sU;
  40726. brightOffsets[1] = 0.5 * sV;
  40727. brightOffsets[2] = 0.5 * sU;
  40728. brightOffsets[3] = 0.5 * sV;
  40729. brightOffsets[4] = -0.5 * sU;
  40730. brightOffsets[5] = -0.5 * sV;
  40731. brightOffsets[6] = 0.5 * sU;
  40732. brightOffsets[7] = -0.5 * sV;
  40733. }
  40734. effect.setArray2("dsOffsets", brightOffsets);
  40735. effect.setFloat("brightThreshold", _this.brightThreshold);
  40736. };
  40737. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  40738. this._brightPassPostProcess.onApply = brightPassCallback;
  40739. };
  40740. /**
  40741. * Luminance generator. Creates the luminance post-process and down sample post-processes
  40742. */
  40743. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  40744. var _this = this;
  40745. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  40746. var luminanceOffsets = new Array(8);
  40747. var downSampleOffsets = new Array(18);
  40748. var halfDestPixelSize;
  40749. this._downSamplePostProcesses = new Array(lumSteps);
  40750. // Utils for luminance
  40751. var luminanceUpdateSourceOffsets = function (width, height) {
  40752. var sU = (1.0 / width);
  40753. var sV = (1.0 / height);
  40754. luminanceOffsets[0] = -0.5 * sU;
  40755. luminanceOffsets[1] = 0.5 * sV;
  40756. luminanceOffsets[2] = 0.5 * sU;
  40757. luminanceOffsets[3] = 0.5 * sV;
  40758. luminanceOffsets[4] = -0.5 * sU;
  40759. luminanceOffsets[5] = -0.5 * sV;
  40760. luminanceOffsets[6] = 0.5 * sU;
  40761. luminanceOffsets[7] = -0.5 * sV;
  40762. };
  40763. var luminanceUpdateDestOffsets = function (width, height) {
  40764. var id = 0;
  40765. for (var x = -1; x < 2; x++) {
  40766. for (var y = -1; y < 2; y++) {
  40767. downSampleOffsets[id] = (x) / width;
  40768. downSampleOffsets[id + 1] = (y) / height;
  40769. id += 2;
  40770. }
  40771. }
  40772. };
  40773. // Luminance callback
  40774. var luminanceCallback = function (effect) {
  40775. if (_this._needUpdate) {
  40776. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  40777. }
  40778. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40779. effect.setArray2("lumOffsets", luminanceOffsets);
  40780. };
  40781. // Down sample callbacks
  40782. var downSampleCallback = function (indice) {
  40783. var i = indice;
  40784. return function (effect) {
  40785. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40786. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40787. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  40788. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  40789. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  40790. effect.setArray2("dsOffsets", downSampleOffsets);
  40791. };
  40792. };
  40793. var downSampleAfterRenderCallback = function (effect) {
  40794. // Unpack result
  40795. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  40796. 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);
  40797. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  40798. };
  40799. // Create luminance post-process
  40800. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  40801. 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);
  40802. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  40803. // Create down sample post-processes
  40804. for (var i = lumSteps - 2; i >= 0; i--) {
  40805. var length = Math.pow(3, i);
  40806. ratio = { width: length, height: length };
  40807. var defines = "#define DOWN_SAMPLE\n";
  40808. if (i === 0) {
  40809. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  40810. }
  40811. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  40812. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  40813. if (i === 0) {
  40814. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  40815. }
  40816. }
  40817. };
  40818. /**
  40819. * Gaussian blur post-processes. Horizontal and Vertical
  40820. */
  40821. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  40822. var _this = this;
  40823. var blurOffsetsW = new Array(9);
  40824. var blurOffsetsH = new Array(9);
  40825. var blurWeights = new Array(9);
  40826. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  40827. // Utils for gaussian blur
  40828. var calculateBlurOffsets = function (height) {
  40829. var lastOutputDimensions = {
  40830. width: scene.getEngine().getRenderWidth(),
  40831. height: scene.getEngine().getRenderHeight()
  40832. };
  40833. for (var i = 0; i < 9; i++) {
  40834. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  40835. if (height) {
  40836. blurOffsetsH[i] = value;
  40837. }
  40838. else {
  40839. blurOffsetsW[i] = value;
  40840. }
  40841. }
  40842. };
  40843. var calculateWeights = function () {
  40844. var x = 0.0;
  40845. for (var i = 0; i < 9; i++) {
  40846. x = (i - 4.0) / 4.0;
  40847. 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));
  40848. }
  40849. };
  40850. // Callback
  40851. var gaussianBlurCallback = function (height) {
  40852. return function (effect) {
  40853. if (_this._needUpdate) {
  40854. calculateWeights();
  40855. calculateBlurOffsets(height);
  40856. }
  40857. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  40858. effect.setArray("blurWeights", blurWeights);
  40859. effect.setFloat("multiplier", _this.gaussMultiplier);
  40860. };
  40861. };
  40862. // Create horizontal gaussian blur post-processes
  40863. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  40864. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  40865. // Create vertical gaussian blur post-process
  40866. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  40867. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  40868. };
  40869. // Luminance generator
  40870. HDRRenderingPipeline.LUM_STEPS = 6;
  40871. return HDRRenderingPipeline;
  40872. }(BABYLON.PostProcessRenderPipeline));
  40873. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  40874. })(BABYLON || (BABYLON = {}));
  40875. var BABYLON;
  40876. (function (BABYLON) {
  40877. var FaceAdjacencies = (function () {
  40878. function FaceAdjacencies() {
  40879. this.edges = new Array();
  40880. this.edgesConnectedCount = 0;
  40881. }
  40882. return FaceAdjacencies;
  40883. }());
  40884. var EdgesRenderer = (function () {
  40885. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  40886. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  40887. if (epsilon === void 0) { epsilon = 0.95; }
  40888. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  40889. this.edgesWidthScalerForOrthographic = 1000.0;
  40890. this.edgesWidthScalerForPerspective = 50.0;
  40891. this._linesPositions = new Array();
  40892. this._linesNormals = new Array();
  40893. this._linesIndices = new Array();
  40894. this._buffers = new Array();
  40895. this._checkVerticesInsteadOfIndices = false;
  40896. this._source = source;
  40897. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  40898. this._epsilon = epsilon;
  40899. this._prepareRessources();
  40900. this._generateEdgesLines();
  40901. }
  40902. EdgesRenderer.prototype._prepareRessources = function () {
  40903. if (this._lineShader) {
  40904. return;
  40905. }
  40906. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  40907. attributes: ["position", "normal"],
  40908. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  40909. });
  40910. this._lineShader.disableDepthWrite = true;
  40911. this._lineShader.backFaceCulling = false;
  40912. };
  40913. EdgesRenderer.prototype.dispose = function () {
  40914. this._vb0.dispose();
  40915. this._vb1.dispose();
  40916. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  40917. this._lineShader.dispose();
  40918. };
  40919. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  40920. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  40921. return 0;
  40922. }
  40923. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  40924. return 1;
  40925. }
  40926. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  40927. return 2;
  40928. }
  40929. return -1;
  40930. };
  40931. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  40932. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  40933. return 0;
  40934. }
  40935. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  40936. return 1;
  40937. }
  40938. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  40939. return 2;
  40940. }
  40941. return -1;
  40942. };
  40943. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  40944. var needToCreateLine;
  40945. if (edge === undefined) {
  40946. needToCreateLine = true;
  40947. }
  40948. else {
  40949. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  40950. needToCreateLine = dotProduct < this._epsilon;
  40951. }
  40952. if (needToCreateLine) {
  40953. var offset = this._linesPositions.length / 3;
  40954. var normal = p0.subtract(p1);
  40955. normal.normalize();
  40956. // Positions
  40957. this._linesPositions.push(p0.x);
  40958. this._linesPositions.push(p0.y);
  40959. this._linesPositions.push(p0.z);
  40960. this._linesPositions.push(p0.x);
  40961. this._linesPositions.push(p0.y);
  40962. this._linesPositions.push(p0.z);
  40963. this._linesPositions.push(p1.x);
  40964. this._linesPositions.push(p1.y);
  40965. this._linesPositions.push(p1.z);
  40966. this._linesPositions.push(p1.x);
  40967. this._linesPositions.push(p1.y);
  40968. this._linesPositions.push(p1.z);
  40969. // Normals
  40970. this._linesNormals.push(p1.x);
  40971. this._linesNormals.push(p1.y);
  40972. this._linesNormals.push(p1.z);
  40973. this._linesNormals.push(-1);
  40974. this._linesNormals.push(p1.x);
  40975. this._linesNormals.push(p1.y);
  40976. this._linesNormals.push(p1.z);
  40977. this._linesNormals.push(1);
  40978. this._linesNormals.push(p0.x);
  40979. this._linesNormals.push(p0.y);
  40980. this._linesNormals.push(p0.z);
  40981. this._linesNormals.push(-1);
  40982. this._linesNormals.push(p0.x);
  40983. this._linesNormals.push(p0.y);
  40984. this._linesNormals.push(p0.z);
  40985. this._linesNormals.push(1);
  40986. // Indices
  40987. this._linesIndices.push(offset);
  40988. this._linesIndices.push(offset + 1);
  40989. this._linesIndices.push(offset + 2);
  40990. this._linesIndices.push(offset);
  40991. this._linesIndices.push(offset + 2);
  40992. this._linesIndices.push(offset + 3);
  40993. }
  40994. };
  40995. EdgesRenderer.prototype._generateEdgesLines = function () {
  40996. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40997. var indices = this._source.getIndices();
  40998. // First let's find adjacencies
  40999. var adjacencies = new Array();
  41000. var faceNormals = new Array();
  41001. var index;
  41002. var faceAdjacencies;
  41003. // Prepare faces
  41004. for (index = 0; index < indices.length; index += 3) {
  41005. faceAdjacencies = new FaceAdjacencies();
  41006. var p0Index = indices[index];
  41007. var p1Index = indices[index + 1];
  41008. var p2Index = indices[index + 2];
  41009. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  41010. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  41011. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  41012. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  41013. faceNormal.normalize();
  41014. faceNormals.push(faceNormal);
  41015. adjacencies.push(faceAdjacencies);
  41016. }
  41017. // Scan
  41018. for (index = 0; index < adjacencies.length; index++) {
  41019. faceAdjacencies = adjacencies[index];
  41020. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  41021. var otherFaceAdjacencies = adjacencies[otherIndex];
  41022. if (faceAdjacencies.edgesConnectedCount === 3) {
  41023. break;
  41024. }
  41025. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  41026. continue;
  41027. }
  41028. var otherP0 = indices[otherIndex * 3];
  41029. var otherP1 = indices[otherIndex * 3 + 1];
  41030. var otherP2 = indices[otherIndex * 3 + 2];
  41031. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  41032. var otherEdgeIndex;
  41033. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  41034. continue;
  41035. }
  41036. switch (edgeIndex) {
  41037. case 0:
  41038. if (this._checkVerticesInsteadOfIndices) {
  41039. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41040. }
  41041. else {
  41042. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  41043. }
  41044. break;
  41045. case 1:
  41046. if (this._checkVerticesInsteadOfIndices) {
  41047. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41048. }
  41049. else {
  41050. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  41051. }
  41052. break;
  41053. case 2:
  41054. if (this._checkVerticesInsteadOfIndices) {
  41055. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41056. }
  41057. else {
  41058. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  41059. }
  41060. break;
  41061. }
  41062. if (otherEdgeIndex === -1) {
  41063. continue;
  41064. }
  41065. faceAdjacencies.edges[edgeIndex] = otherIndex;
  41066. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  41067. faceAdjacencies.edgesConnectedCount++;
  41068. otherFaceAdjacencies.edgesConnectedCount++;
  41069. if (faceAdjacencies.edgesConnectedCount === 3) {
  41070. break;
  41071. }
  41072. }
  41073. }
  41074. }
  41075. // Create lines
  41076. for (index = 0; index < adjacencies.length; index++) {
  41077. // 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
  41078. var current = adjacencies[index];
  41079. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  41080. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  41081. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  41082. }
  41083. // Merge into a single mesh
  41084. var engine = this._source.getScene().getEngine();
  41085. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  41086. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  41087. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  41088. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  41089. this._ib = engine.createIndexBuffer(this._linesIndices);
  41090. this._indicesCount = this._linesIndices.length;
  41091. };
  41092. EdgesRenderer.prototype.render = function () {
  41093. if (!this._lineShader.isReady()) {
  41094. return;
  41095. }
  41096. var scene = this._source.getScene();
  41097. var engine = scene.getEngine();
  41098. this._lineShader._preBind();
  41099. // VBOs
  41100. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  41101. scene.resetCachedMaterial();
  41102. this._lineShader.setColor4("color", this._source.edgesColor);
  41103. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  41104. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  41105. }
  41106. else {
  41107. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  41108. }
  41109. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  41110. this._lineShader.bind(this._source.getWorldMatrix());
  41111. // Draw order
  41112. engine.draw(true, 0, this._indicesCount);
  41113. this._lineShader.unbind();
  41114. engine.setDepthWrite(true);
  41115. };
  41116. return EdgesRenderer;
  41117. }());
  41118. BABYLON.EdgesRenderer = EdgesRenderer;
  41119. })(BABYLON || (BABYLON = {}));
  41120. var BABYLON;
  41121. (function (BABYLON) {
  41122. (function (TonemappingOperator) {
  41123. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  41124. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  41125. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  41126. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  41127. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  41128. var TonemappingOperator = BABYLON.TonemappingOperator;
  41129. ;
  41130. var TonemapPostProcess = (function (_super) {
  41131. __extends(TonemapPostProcess, _super);
  41132. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  41133. var _this = this;
  41134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41135. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41136. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  41137. this._operator = _operator;
  41138. this.exposureAdjustment = exposureAdjustment;
  41139. var defines = "#define ";
  41140. if (this._operator === TonemappingOperator.Hable)
  41141. defines += "HABLE_TONEMAPPING";
  41142. else if (this._operator === TonemappingOperator.Reinhard)
  41143. defines += "REINHARD_TONEMAPPING";
  41144. else if (this._operator === TonemappingOperator.HejiDawson)
  41145. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  41146. else if (this._operator === TonemappingOperator.Photographic)
  41147. defines += "PHOTOGRAPHIC_TONEMAPPING";
  41148. //sadly a second call to create the effect.
  41149. this.updateEffect(defines);
  41150. this.onApply = function (effect) {
  41151. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  41152. };
  41153. }
  41154. return TonemapPostProcess;
  41155. }(BABYLON.PostProcess));
  41156. BABYLON.TonemapPostProcess = TonemapPostProcess;
  41157. })(BABYLON || (BABYLON = {}));
  41158. var BABYLON;
  41159. (function (BABYLON) {
  41160. var ReflectionProbe = (function () {
  41161. function ReflectionProbe(name, size, scene, generateMipMaps) {
  41162. var _this = this;
  41163. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41164. this.name = name;
  41165. this._viewMatrix = BABYLON.Matrix.Identity();
  41166. this._target = BABYLON.Vector3.Zero();
  41167. this._add = BABYLON.Vector3.Zero();
  41168. this.position = BABYLON.Vector3.Zero();
  41169. this._scene = scene;
  41170. this._scene.reflectionProbes.push(this);
  41171. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  41172. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  41173. switch (faceIndex) {
  41174. case 0:
  41175. _this._add.copyFromFloats(1, 0, 0);
  41176. break;
  41177. case 1:
  41178. _this._add.copyFromFloats(-1, 0, 0);
  41179. break;
  41180. case 2:
  41181. _this._add.copyFromFloats(0, -1, 0);
  41182. break;
  41183. case 3:
  41184. _this._add.copyFromFloats(0, 1, 0);
  41185. break;
  41186. case 4:
  41187. _this._add.copyFromFloats(0, 0, 1);
  41188. break;
  41189. case 5:
  41190. _this._add.copyFromFloats(0, 0, -1);
  41191. break;
  41192. }
  41193. if (_this._attachedMesh) {
  41194. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  41195. }
  41196. _this.position.addToRef(_this._add, _this._target);
  41197. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  41198. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  41199. };
  41200. this._renderTargetTexture.onAfterUnbind = function () {
  41201. scene.updateTransformMatrix(true);
  41202. };
  41203. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41204. }
  41205. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  41206. get: function () {
  41207. return this._renderTargetTexture.refreshRate;
  41208. },
  41209. set: function (value) {
  41210. this._renderTargetTexture.refreshRate = value;
  41211. },
  41212. enumerable: true,
  41213. configurable: true
  41214. });
  41215. ReflectionProbe.prototype.getScene = function () {
  41216. return this._scene;
  41217. };
  41218. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  41219. get: function () {
  41220. return this._renderTargetTexture;
  41221. },
  41222. enumerable: true,
  41223. configurable: true
  41224. });
  41225. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  41226. get: function () {
  41227. return this._renderTargetTexture.renderList;
  41228. },
  41229. enumerable: true,
  41230. configurable: true
  41231. });
  41232. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  41233. this._attachedMesh = mesh;
  41234. };
  41235. ReflectionProbe.prototype.dispose = function () {
  41236. var index = this._scene.reflectionProbes.indexOf(this);
  41237. if (index !== -1) {
  41238. // Remove from the scene if found
  41239. this._scene.reflectionProbes.splice(index, 1);
  41240. }
  41241. if (this._renderTargetTexture) {
  41242. this._renderTargetTexture.dispose();
  41243. this._renderTargetTexture = null;
  41244. }
  41245. };
  41246. return ReflectionProbe;
  41247. }());
  41248. BABYLON.ReflectionProbe = ReflectionProbe;
  41249. })(BABYLON || (BABYLON = {}));
  41250. var BABYLON;
  41251. (function (BABYLON) {
  41252. var SolidParticle = (function () {
  41253. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  41254. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  41255. this.position = BABYLON.Vector3.Zero(); // position
  41256. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41257. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  41258. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  41259. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41260. this.alive = true; // alive
  41261. this.idx = particleIndex;
  41262. this._pos = positionIndex;
  41263. this._model = model;
  41264. this.shapeId = shapeId;
  41265. this.idxInShape = idxInShape;
  41266. }
  41267. Object.defineProperty(SolidParticle.prototype, "scale", {
  41268. //legacy support, changed scale to scaling
  41269. get: function () {
  41270. return this.scaling;
  41271. },
  41272. set: function (scale) {
  41273. this.scaling = scale;
  41274. },
  41275. enumerable: true,
  41276. configurable: true
  41277. });
  41278. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41279. //legacy support, changed quaternion to rotationQuaternion
  41280. get: function () {
  41281. return this.rotationQuaternion;
  41282. },
  41283. set: function (q) {
  41284. this.rotationQuaternion = q;
  41285. },
  41286. enumerable: true,
  41287. configurable: true
  41288. });
  41289. return SolidParticle;
  41290. }());
  41291. BABYLON.SolidParticle = SolidParticle;
  41292. var ModelShape = (function () {
  41293. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41294. this.shapeID = id;
  41295. this._shape = shape;
  41296. this._shapeUV = shapeUV;
  41297. this._positionFunction = posFunction;
  41298. this._vertexFunction = vtxFunction;
  41299. }
  41300. return ModelShape;
  41301. }());
  41302. BABYLON.ModelShape = ModelShape;
  41303. })(BABYLON || (BABYLON = {}));
  41304. var BABYLON;
  41305. (function (BABYLON) {
  41306. /**
  41307. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  41308. */
  41309. var SolidParticleSystem = (function () {
  41310. /**
  41311. * Creates a SPS (Solid Particle System) object.
  41312. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41313. * `scene` (Scene) is the scene in which the SPS is added.
  41314. * `updatableè (default true) : if the SPS must be updatable or immutable.
  41315. * `isPickable` (default false) : if the solid particles must be pickable.
  41316. */
  41317. function SolidParticleSystem(name, scene, options) {
  41318. // public members
  41319. /**
  41320. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41321. * Example : var p = SPS.particles[i];
  41322. */
  41323. this.particles = new Array();
  41324. /**
  41325. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41326. */
  41327. this.nbParticles = 0;
  41328. /**
  41329. * If the particles must ever face the camera (default false). Useful for planar particles.
  41330. */
  41331. this.billboard = false;
  41332. /**
  41333. * This a counter ofr your own usage. It's not set by any SPS functions.
  41334. */
  41335. this.counter = 0;
  41336. /**
  41337. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41338. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  41339. */
  41340. this.vars = {};
  41341. this._positions = new Array();
  41342. this._indices = new Array();
  41343. this._normals = new Array();
  41344. this._colors = new Array();
  41345. this._uvs = new Array();
  41346. this._index = 0; // indices index
  41347. this._updatable = true;
  41348. this._pickable = false;
  41349. this._isVisibilityBoxLocked = false;
  41350. this._alwaysVisible = false;
  41351. this._shapeCounter = 0;
  41352. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  41353. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41354. this._computeParticleColor = true;
  41355. this._computeParticleTexture = true;
  41356. this._computeParticleRotation = true;
  41357. this._computeParticleVertex = false;
  41358. this._computeBoundingBox = false;
  41359. this._cam_axisZ = BABYLON.Vector3.Zero();
  41360. this._cam_axisY = BABYLON.Vector3.Zero();
  41361. this._cam_axisX = BABYLON.Vector3.Zero();
  41362. this._axisX = BABYLON.Axis.X;
  41363. this._axisY = BABYLON.Axis.Y;
  41364. this._axisZ = BABYLON.Axis.Z;
  41365. this._fakeCamPos = BABYLON.Vector3.Zero();
  41366. this._rotMatrix = new BABYLON.Matrix();
  41367. this._invertMatrix = new BABYLON.Matrix();
  41368. this._rotated = BABYLON.Vector3.Zero();
  41369. this._quaternion = new BABYLON.Quaternion();
  41370. this._vertex = BABYLON.Vector3.Zero();
  41371. this._normal = BABYLON.Vector3.Zero();
  41372. this._yaw = 0.0;
  41373. this._pitch = 0.0;
  41374. this._roll = 0.0;
  41375. this._halfroll = 0.0;
  41376. this._halfpitch = 0.0;
  41377. this._halfyaw = 0.0;
  41378. this._sinRoll = 0.0;
  41379. this._cosRoll = 0.0;
  41380. this._sinPitch = 0.0;
  41381. this._cosPitch = 0.0;
  41382. this._sinYaw = 0.0;
  41383. this._cosYaw = 0.0;
  41384. this._w = 0.0;
  41385. this._minimum = BABYLON.Tmp.Vector3[0];
  41386. this._maximum = BABYLON.Tmp.Vector3[1];
  41387. this.name = name;
  41388. this._scene = scene;
  41389. this._camera = scene.activeCamera;
  41390. this._pickable = options ? options.isPickable : false;
  41391. if (options && options.updatable) {
  41392. this._updatable = options.updatable;
  41393. }
  41394. else {
  41395. this._updatable = true;
  41396. }
  41397. if (this._pickable) {
  41398. this.pickedParticles = [];
  41399. }
  41400. }
  41401. /**
  41402. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41403. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41404. */
  41405. SolidParticleSystem.prototype.buildMesh = function () {
  41406. if (this.nbParticles === 0) {
  41407. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41408. this.addShape(triangle, 1);
  41409. triangle.dispose();
  41410. }
  41411. this._positions32 = new Float32Array(this._positions);
  41412. this._uvs32 = new Float32Array(this._uvs);
  41413. this._colors32 = new Float32Array(this._colors);
  41414. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41415. this._normals32 = new Float32Array(this._normals);
  41416. this._fixedNormal32 = new Float32Array(this._normals);
  41417. var vertexData = new BABYLON.VertexData();
  41418. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41419. vertexData.indices = this._indices;
  41420. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41421. if (this._uvs32) {
  41422. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41423. ;
  41424. }
  41425. if (this._colors32) {
  41426. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41427. }
  41428. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41429. vertexData.applyToMesh(mesh, this._updatable);
  41430. this.mesh = mesh;
  41431. this.mesh.isPickable = this._pickable;
  41432. // free memory
  41433. this._positions = null;
  41434. this._normals = null;
  41435. this._uvs = null;
  41436. this._colors = null;
  41437. if (!this._updatable) {
  41438. this.particles.length = 0;
  41439. }
  41440. return mesh;
  41441. };
  41442. /**
  41443. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41444. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41445. * Thus the particles generated from `digest()` have their property `position` set yet.
  41446. * `mesh` (`Mesh`) is the mesh to be digested
  41447. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41448. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41449. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41450. */
  41451. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41452. var size = (options && options.facetNb) || 1;
  41453. var number = (options && options.number);
  41454. var delta = (options && options.delta) || 0;
  41455. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41456. var meshInd = mesh.getIndices();
  41457. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41458. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41459. var f = 0; // facet counter
  41460. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41461. // compute size from number
  41462. if (number) {
  41463. number = (number > totalFacets) ? totalFacets : number;
  41464. size = Math.round(totalFacets / number);
  41465. delta = 0;
  41466. }
  41467. else {
  41468. size = (size > totalFacets) ? totalFacets : size;
  41469. }
  41470. var facetPos = []; // submesh positions
  41471. var facetInd = []; // submesh indices
  41472. var facetUV = []; // submesh UV
  41473. var facetCol = []; // submesh colors
  41474. var barycenter = BABYLON.Tmp.Vector3[0];
  41475. var rand;
  41476. var sizeO = size;
  41477. while (f < totalFacets) {
  41478. size = sizeO + Math.floor((1 + delta) * Math.random());
  41479. if (f > totalFacets - size) {
  41480. size = totalFacets - f;
  41481. }
  41482. // reset temp arrays
  41483. facetPos.length = 0;
  41484. facetInd.length = 0;
  41485. facetUV.length = 0;
  41486. facetCol.length = 0;
  41487. // iterate over "size" facets
  41488. var fi = 0;
  41489. for (var j = f * 3; j < (f + size) * 3; j++) {
  41490. facetInd.push(fi);
  41491. var i = meshInd[j];
  41492. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41493. if (meshUV) {
  41494. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41495. }
  41496. if (meshCol) {
  41497. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41498. }
  41499. fi++;
  41500. }
  41501. // create a model shape for each single particle
  41502. var idx = this.nbParticles;
  41503. var shape = this._posToShape(facetPos);
  41504. var shapeUV = this._uvsToShapeUV(facetUV);
  41505. // compute the barycenter of the shape
  41506. var v;
  41507. for (v = 0; v < shape.length; v++) {
  41508. barycenter.addInPlace(shape[v]);
  41509. }
  41510. barycenter.scaleInPlace(1 / shape.length);
  41511. // shift the shape from its barycenter to the origin
  41512. for (v = 0; v < shape.length; v++) {
  41513. shape[v].subtractInPlace(barycenter);
  41514. }
  41515. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41516. // add the particle in the SPS
  41517. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  41518. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  41519. // initialize the particle position
  41520. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41521. this._index += shape.length;
  41522. idx++;
  41523. this.nbParticles++;
  41524. this._shapeCounter++;
  41525. f += size;
  41526. }
  41527. return this;
  41528. };
  41529. //reset copy
  41530. SolidParticleSystem.prototype._resetCopy = function () {
  41531. this._copy.position.x = 0;
  41532. this._copy.position.y = 0;
  41533. this._copy.position.z = 0;
  41534. this._copy.rotation.x = 0;
  41535. this._copy.rotation.y = 0;
  41536. this._copy.rotation.z = 0;
  41537. this._copy.rotationQuaternion = null;
  41538. this._copy.scaling.x = 1;
  41539. this._copy.scaling.y = 1;
  41540. this._copy.scaling.z = 1;
  41541. this._copy.uvs.x = 0;
  41542. this._copy.uvs.y = 0;
  41543. this._copy.uvs.z = 1;
  41544. this._copy.uvs.w = 1;
  41545. this._copy.color = null;
  41546. };
  41547. // _meshBuilder : inserts the shape model in the global SPS mesh
  41548. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  41549. var i;
  41550. var u = 0;
  41551. var c = 0;
  41552. this._resetCopy();
  41553. if (options && options.positionFunction) {
  41554. options.positionFunction(this._copy, idx, idxInShape);
  41555. }
  41556. if (this._copy.rotationQuaternion) {
  41557. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41558. }
  41559. else {
  41560. this._yaw = this._copy.rotation.y;
  41561. this._pitch = this._copy.rotation.x;
  41562. this._roll = this._copy.rotation.z;
  41563. this._quaternionRotationYPR();
  41564. }
  41565. this._quaternionToRotationMatrix();
  41566. for (i = 0; i < shape.length; i++) {
  41567. this._vertex.x = shape[i].x;
  41568. this._vertex.y = shape[i].y;
  41569. this._vertex.z = shape[i].z;
  41570. if (options && options.vertexFunction) {
  41571. options.vertexFunction(this._copy, this._vertex, i);
  41572. }
  41573. this._vertex.x *= this._copy.scaling.x;
  41574. this._vertex.y *= this._copy.scaling.y;
  41575. this._vertex.z *= this._copy.scaling.z;
  41576. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41577. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41578. if (meshUV) {
  41579. 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);
  41580. u += 2;
  41581. }
  41582. if (this._copy.color) {
  41583. this._color = this._copy.color;
  41584. }
  41585. else if (meshCol && meshCol[c]) {
  41586. this._color.r = meshCol[c];
  41587. this._color.g = meshCol[c + 1];
  41588. this._color.b = meshCol[c + 2];
  41589. this._color.a = meshCol[c + 3];
  41590. }
  41591. else {
  41592. this._color.r = 1;
  41593. this._color.g = 1;
  41594. this._color.b = 1;
  41595. this._color.a = 1;
  41596. }
  41597. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41598. c += 4;
  41599. }
  41600. for (i = 0; i < meshInd.length; i++) {
  41601. indices.push(p + meshInd[i]);
  41602. }
  41603. if (this._pickable) {
  41604. var nbfaces = meshInd.length / 3;
  41605. for (i = 0; i < nbfaces; i++) {
  41606. this.pickedParticles.push({ idx: idx, faceId: i });
  41607. }
  41608. }
  41609. };
  41610. // returns a shape array from positions array
  41611. SolidParticleSystem.prototype._posToShape = function (positions) {
  41612. var shape = [];
  41613. for (var i = 0; i < positions.length; i += 3) {
  41614. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41615. }
  41616. return shape;
  41617. };
  41618. // returns a shapeUV array from a Vector4 uvs
  41619. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41620. var shapeUV = [];
  41621. if (uvs) {
  41622. for (var i = 0; i < uvs.length; i++)
  41623. shapeUV.push(uvs[i]);
  41624. }
  41625. return shapeUV;
  41626. };
  41627. // adds a new particle object in the particles array
  41628. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  41629. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  41630. };
  41631. /**
  41632. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41633. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  41634. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  41635. * `nb` (positive integer) the number of particles to be created from this model
  41636. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41637. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41638. */
  41639. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41640. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41641. var meshInd = mesh.getIndices();
  41642. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41643. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41644. var shape = this._posToShape(meshPos);
  41645. var shapeUV = this._uvsToShapeUV(meshUV);
  41646. var posfunc = options ? options.positionFunction : null;
  41647. var vtxfunc = options ? options.vertexFunction : null;
  41648. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41649. // particles
  41650. var idx = this.nbParticles;
  41651. for (var i = 0; i < nb; i++) {
  41652. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  41653. if (this._updatable) {
  41654. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  41655. }
  41656. this._index += shape.length;
  41657. idx++;
  41658. }
  41659. this.nbParticles += nb;
  41660. this._shapeCounter++;
  41661. return this._shapeCounter - 1;
  41662. };
  41663. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41664. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41665. this._resetCopy();
  41666. if (particle._model._positionFunction) {
  41667. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41668. }
  41669. if (this._copy.rotationQuaternion) {
  41670. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41671. }
  41672. else {
  41673. this._yaw = this._copy.rotation.y;
  41674. this._pitch = this._copy.rotation.x;
  41675. this._roll = this._copy.rotation.z;
  41676. this._quaternionRotationYPR();
  41677. }
  41678. this._quaternionToRotationMatrix();
  41679. this._shape = particle._model._shape;
  41680. for (var pt = 0; pt < this._shape.length; pt++) {
  41681. this._vertex.x = this._shape[pt].x;
  41682. this._vertex.y = this._shape[pt].y;
  41683. this._vertex.z = this._shape[pt].z;
  41684. if (particle._model._vertexFunction) {
  41685. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41686. }
  41687. this._vertex.x *= this._copy.scaling.x;
  41688. this._vertex.y *= this._copy.scaling.y;
  41689. this._vertex.z *= this._copy.scaling.z;
  41690. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41691. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41692. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41693. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41694. }
  41695. particle.position.x = 0;
  41696. particle.position.y = 0;
  41697. particle.position.z = 0;
  41698. particle.rotation.x = 0;
  41699. particle.rotation.y = 0;
  41700. particle.rotation.z = 0;
  41701. particle.rotationQuaternion = null;
  41702. particle.scaling.x = 1;
  41703. particle.scaling.y = 1;
  41704. particle.scaling.z = 1;
  41705. };
  41706. /**
  41707. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41708. */
  41709. SolidParticleSystem.prototype.rebuildMesh = function () {
  41710. for (var p = 0; p < this.particles.length; p++) {
  41711. this._rebuildParticle(this.particles[p]);
  41712. }
  41713. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41714. };
  41715. /**
  41716. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41717. * This method calls `updateParticle()` for each particle of the SPS.
  41718. * For an animated SPS, it is usually called within the render loop.
  41719. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  41720. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  41721. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  41722. */
  41723. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41724. if (start === void 0) { start = 0; }
  41725. if (end === void 0) { end = this.nbParticles - 1; }
  41726. if (update === void 0) { update = true; }
  41727. if (!this._updatable) {
  41728. return;
  41729. }
  41730. // custom beforeUpdate
  41731. this.beforeUpdateParticles(start, end, update);
  41732. this._cam_axisX.x = 1;
  41733. this._cam_axisX.y = 0;
  41734. this._cam_axisX.z = 0;
  41735. this._cam_axisY.x = 0;
  41736. this._cam_axisY.y = 1;
  41737. this._cam_axisY.z = 0;
  41738. this._cam_axisZ.x = 0;
  41739. this._cam_axisZ.y = 0;
  41740. this._cam_axisZ.z = 1;
  41741. // if the particles will always face the camera
  41742. if (this.billboard) {
  41743. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  41744. this._yaw = this.mesh.rotation.y;
  41745. this._pitch = this.mesh.rotation.x;
  41746. this._roll = this.mesh.rotation.z;
  41747. this._quaternionRotationYPR();
  41748. this._quaternionToRotationMatrix();
  41749. this._rotMatrix.invertToRef(this._invertMatrix);
  41750. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  41751. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  41752. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  41753. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  41754. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  41755. this._cam_axisY.normalize();
  41756. this._cam_axisX.normalize();
  41757. this._cam_axisZ.normalize();
  41758. }
  41759. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41760. var idx = 0;
  41761. var index = 0;
  41762. var colidx = 0;
  41763. var colorIndex = 0;
  41764. var uvidx = 0;
  41765. var uvIndex = 0;
  41766. if (this._computeBoundingBox) {
  41767. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41768. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41769. }
  41770. // particle loop
  41771. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  41772. for (var p = start; p <= end; p++) {
  41773. this._particle = this.particles[p];
  41774. this._shape = this._particle._model._shape;
  41775. this._shapeUV = this._particle._model._shapeUV;
  41776. // call to custom user function to update the particle properties
  41777. this.updateParticle(this._particle);
  41778. // particle rotation matrix
  41779. if (this.billboard) {
  41780. this._particle.rotation.x = 0.0;
  41781. this._particle.rotation.y = 0.0;
  41782. }
  41783. if (this._computeParticleRotation) {
  41784. if (this._particle.rotationQuaternion) {
  41785. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41786. }
  41787. else {
  41788. this._yaw = this._particle.rotation.y;
  41789. this._pitch = this._particle.rotation.x;
  41790. this._roll = this._particle.rotation.z;
  41791. this._quaternionRotationYPR();
  41792. }
  41793. this._quaternionToRotationMatrix();
  41794. }
  41795. for (var pt = 0; pt < this._shape.length; pt++) {
  41796. idx = index + pt * 3;
  41797. colidx = colorIndex + pt * 4;
  41798. uvidx = uvIndex + pt * 2;
  41799. this._vertex.x = this._shape[pt].x;
  41800. this._vertex.y = this._shape[pt].y;
  41801. this._vertex.z = this._shape[pt].z;
  41802. if (this._computeParticleVertex) {
  41803. this.updateParticleVertex(this._particle, this._vertex, pt);
  41804. }
  41805. // positions
  41806. this._vertex.x *= this._particle.scaling.x;
  41807. this._vertex.y *= this._particle.scaling.y;
  41808. this._vertex.z *= this._particle.scaling.z;
  41809. 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];
  41810. 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;
  41811. 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;
  41812. 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;
  41813. 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;
  41814. 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;
  41815. 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;
  41816. if (this._computeBoundingBox) {
  41817. if (this._positions32[idx] < this._minimum.x) {
  41818. this._minimum.x = this._positions32[idx];
  41819. }
  41820. if (this._positions32[idx] > this._maximum.x) {
  41821. this._maximum.x = this._positions32[idx];
  41822. }
  41823. if (this._positions32[idx + 1] < this._minimum.y) {
  41824. this._minimum.y = this._positions32[idx + 1];
  41825. }
  41826. if (this._positions32[idx + 1] > this._maximum.y) {
  41827. this._maximum.y = this._positions32[idx + 1];
  41828. }
  41829. if (this._positions32[idx + 2] < this._minimum.z) {
  41830. this._minimum.z = this._positions32[idx + 2];
  41831. }
  41832. if (this._positions32[idx + 2] > this._maximum.z) {
  41833. this._maximum.z = this._positions32[idx + 2];
  41834. }
  41835. }
  41836. // normals : if the particles can't be morphed then just rotate the normals
  41837. if (!this._computeParticleVertex && !this.billboard) {
  41838. this._normal.x = this._fixedNormal32[idx];
  41839. this._normal.y = this._fixedNormal32[idx + 1];
  41840. this._normal.z = this._fixedNormal32[idx + 2];
  41841. 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];
  41842. 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;
  41843. 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;
  41844. 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;
  41845. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41846. 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;
  41847. 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;
  41848. }
  41849. if (this._computeParticleColor) {
  41850. this._colors32[colidx] = this._particle.color.r;
  41851. this._colors32[colidx + 1] = this._particle.color.g;
  41852. this._colors32[colidx + 2] = this._particle.color.b;
  41853. this._colors32[colidx + 3] = this._particle.color.a;
  41854. }
  41855. if (this._computeParticleTexture) {
  41856. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41857. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41858. }
  41859. }
  41860. index = idx + 3;
  41861. colorIndex = colidx + 4;
  41862. uvIndex = uvidx + 2;
  41863. }
  41864. if (update) {
  41865. if (this._computeParticleColor) {
  41866. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41867. }
  41868. if (this._computeParticleTexture) {
  41869. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41870. }
  41871. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41872. if (!this.mesh.areNormalsFrozen) {
  41873. if (this._computeParticleVertex || this.billboard) {
  41874. // recompute the normals only if the particles can be morphed, update then the normal reference array
  41875. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  41876. for (var i = 0; i < this._normals32.length; i++) {
  41877. this._fixedNormal32[i] = this._normals32[i];
  41878. }
  41879. }
  41880. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41881. }
  41882. }
  41883. if (this._computeBoundingBox) {
  41884. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41885. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41886. }
  41887. this.afterUpdateParticles(start, end, update);
  41888. };
  41889. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  41890. this._halfroll = this._roll * 0.5;
  41891. this._halfpitch = this._pitch * 0.5;
  41892. this._halfyaw = this._yaw * 0.5;
  41893. this._sinRoll = Math.sin(this._halfroll);
  41894. this._cosRoll = Math.cos(this._halfroll);
  41895. this._sinPitch = Math.sin(this._halfpitch);
  41896. this._cosPitch = Math.cos(this._halfpitch);
  41897. this._sinYaw = Math.sin(this._halfyaw);
  41898. this._cosYaw = Math.cos(this._halfyaw);
  41899. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  41900. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  41901. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  41902. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  41903. };
  41904. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  41905. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  41906. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  41907. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  41908. this._rotMatrix.m[3] = 0;
  41909. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  41910. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  41911. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  41912. this._rotMatrix.m[7] = 0;
  41913. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  41914. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  41915. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  41916. this._rotMatrix.m[11] = 0;
  41917. this._rotMatrix.m[12] = 0;
  41918. this._rotMatrix.m[13] = 0;
  41919. this._rotMatrix.m[14] = 0;
  41920. this._rotMatrix.m[15] = 1.0;
  41921. };
  41922. /**
  41923. * Disposes the SPS
  41924. */
  41925. SolidParticleSystem.prototype.dispose = function () {
  41926. this.mesh.dispose();
  41927. this.vars = null;
  41928. // drop references to internal big arrays for the GC
  41929. this._positions = null;
  41930. this._indices = null;
  41931. this._normals = null;
  41932. this._uvs = null;
  41933. this._colors = null;
  41934. this._positions32 = null;
  41935. this._normals32 = null;
  41936. this._fixedNormal32 = null;
  41937. this._uvs32 = null;
  41938. this._colors32 = null;
  41939. this.pickedParticles = null;
  41940. };
  41941. /**
  41942. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  41943. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41944. */
  41945. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  41946. if (!this._isVisibilityBoxLocked) {
  41947. this.mesh.refreshBoundingInfo();
  41948. }
  41949. };
  41950. /**
  41951. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  41952. * @param size the size (float) of the visibility box
  41953. * note : this doesn't lock the SPS mesh bounding box.
  41954. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41955. */
  41956. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  41957. var vis = size / 2;
  41958. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  41959. };
  41960. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  41961. // getter and setter
  41962. get: function () {
  41963. return this._alwaysVisible;
  41964. },
  41965. /**
  41966. * Sets the SPS as always visible or not
  41967. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41968. */
  41969. set: function (val) {
  41970. this._alwaysVisible = val;
  41971. this.mesh.alwaysSelectAsActiveMesh = val;
  41972. },
  41973. enumerable: true,
  41974. configurable: true
  41975. });
  41976. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  41977. get: function () {
  41978. return this._isVisibilityBoxLocked;
  41979. },
  41980. /**
  41981. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  41982. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41983. */
  41984. set: function (val) {
  41985. this._isVisibilityBoxLocked = val;
  41986. this.mesh.getBoundingInfo().isLocked = val;
  41987. },
  41988. enumerable: true,
  41989. configurable: true
  41990. });
  41991. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  41992. // getters
  41993. get: function () {
  41994. return this._computeParticleRotation;
  41995. },
  41996. // Optimizer setters
  41997. /**
  41998. * Tells to `setParticles()` to compute the particle rotations or not.
  41999. * Default value : true. The SPS is faster when it's set to false.
  42000. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42001. */
  42002. set: function (val) {
  42003. this._computeParticleRotation = val;
  42004. },
  42005. enumerable: true,
  42006. configurable: true
  42007. });
  42008. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42009. get: function () {
  42010. return this._computeParticleColor;
  42011. },
  42012. /**
  42013. * Tells to `setParticles()` to compute the particle colors or not.
  42014. * Default value : true. The SPS is faster when it's set to false.
  42015. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42016. */
  42017. set: function (val) {
  42018. this._computeParticleColor = val;
  42019. },
  42020. enumerable: true,
  42021. configurable: true
  42022. });
  42023. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42024. get: function () {
  42025. return this._computeParticleTexture;
  42026. },
  42027. /**
  42028. * Tells to `setParticles()` to compute the particle textures or not.
  42029. * Default value : true. The SPS is faster when it's set to false.
  42030. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42031. */
  42032. set: function (val) {
  42033. this._computeParticleTexture = val;
  42034. },
  42035. enumerable: true,
  42036. configurable: true
  42037. });
  42038. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42039. get: function () {
  42040. return this._computeParticleVertex;
  42041. },
  42042. /**
  42043. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42044. * Default value : false. The SPS is faster when it's set to false.
  42045. * Note : the particle custom vertex positions aren't stored values.
  42046. */
  42047. set: function (val) {
  42048. this._computeParticleVertex = val;
  42049. },
  42050. enumerable: true,
  42051. configurable: true
  42052. });
  42053. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42054. get: function () {
  42055. return this._computeBoundingBox;
  42056. },
  42057. /**
  42058. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42059. */
  42060. set: function (val) {
  42061. this._computeBoundingBox = val;
  42062. },
  42063. enumerable: true,
  42064. configurable: true
  42065. });
  42066. // =======================================================================
  42067. // Particle behavior logic
  42068. // these following methods may be overwritten by the user to fit his needs
  42069. /**
  42070. * This function does nothing. It may be overwritten to set all the particle first values.
  42071. * The SPS doesn't call this function, you may have to call it by your own.
  42072. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42073. */
  42074. SolidParticleSystem.prototype.initParticles = function () {
  42075. };
  42076. /**
  42077. * This function does nothing. It may be overwritten to recycle a particle.
  42078. * The SPS doesn't call this function, you may have to call it by your own.
  42079. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42080. */
  42081. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42082. return particle;
  42083. };
  42084. /**
  42085. * Updates a particle : this function should be overwritten by the user.
  42086. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42087. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42088. * ex : just set a particle position or velocity and recycle conditions
  42089. */
  42090. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42091. return particle;
  42092. };
  42093. /**
  42094. * Updates a vertex of a particle : it can be overwritten by the user.
  42095. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42096. * @param particle the current particle
  42097. * @param vertex the current index of the current particle
  42098. * @param pt the index of the current vertex in the particle shape
  42099. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  42100. * ex : just set a vertex particle position
  42101. */
  42102. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42103. return vertex;
  42104. };
  42105. /**
  42106. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42107. * This does nothing and may be overwritten by the user.
  42108. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42109. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42110. * @param update the boolean update value actually passed to setParticles()
  42111. */
  42112. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42113. };
  42114. /**
  42115. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42116. * This will be passed three parameters.
  42117. * This does nothing and may be overwritten by the user.
  42118. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42119. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42120. * @param update the boolean update value actually passed to setParticles()
  42121. */
  42122. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42123. };
  42124. return SolidParticleSystem;
  42125. }());
  42126. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42127. })(BABYLON || (BABYLON = {}));
  42128. var BABYLON;
  42129. (function (BABYLON) {
  42130. var Internals;
  42131. (function (Internals) {
  42132. var FileFaceOrientation = (function () {
  42133. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42134. this.name = name;
  42135. this.worldAxisForNormal = worldAxisForNormal;
  42136. this.worldAxisForFileX = worldAxisForFileX;
  42137. this.worldAxisForFileY = worldAxisForFileY;
  42138. }
  42139. return FileFaceOrientation;
  42140. }());
  42141. ;
  42142. /**
  42143. * Helper class dealing with the extraction of spherical polynomial dataArray
  42144. * from a cube map.
  42145. */
  42146. var CubeMapToSphericalPolynomialTools = (function () {
  42147. function CubeMapToSphericalPolynomialTools() {
  42148. }
  42149. /**
  42150. * Converts a cubemap to the according Spherical Polynomial data.
  42151. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42152. *
  42153. * @param cubeInfo The Cube map to extract the information from.
  42154. * @return The Spherical Polynomial data.
  42155. */
  42156. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42157. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42158. var totalSolidAngle = 0.0;
  42159. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42160. var du = 2.0 / cubeInfo.size;
  42161. var dv = du;
  42162. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42163. var minUV = du * 0.5 - 1.0;
  42164. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42165. var fileFace = this.FileFaces[faceIndex];
  42166. var dataArray = cubeInfo[fileFace.name];
  42167. var v = minUV;
  42168. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42169. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42170. // Because SP is still linear, so summation is fine in that basis.
  42171. for (var y = 0; y < cubeInfo.size; y++) {
  42172. var u = minUV;
  42173. for (var x = 0; x < cubeInfo.size; x++) {
  42174. // World direction (not normalised)
  42175. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42176. worldDirection.normalize();
  42177. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42178. if (1) {
  42179. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  42180. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  42181. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  42182. var color = new BABYLON.Color3(r, g, b);
  42183. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42184. }
  42185. else {
  42186. if (faceIndex == 0) {
  42187. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42188. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42189. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42190. }
  42191. else if (faceIndex == 1) {
  42192. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42193. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42194. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42195. }
  42196. else if (faceIndex == 2) {
  42197. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42198. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42199. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42200. }
  42201. else if (faceIndex == 3) {
  42202. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42203. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42204. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42205. }
  42206. else if (faceIndex == 4) {
  42207. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42208. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42209. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42210. }
  42211. else if (faceIndex == 5) {
  42212. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42213. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42214. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42215. }
  42216. 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]);
  42217. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42218. }
  42219. totalSolidAngle += deltaSolidAngle;
  42220. u += du;
  42221. }
  42222. v += dv;
  42223. }
  42224. }
  42225. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  42226. var correction = correctSolidAngle / totalSolidAngle;
  42227. sphericalHarmonics.scale(correction);
  42228. // Additionally scale by pi -- audit needed
  42229. sphericalHarmonics.scale(1.0 / Math.PI);
  42230. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  42231. };
  42232. CubeMapToSphericalPolynomialTools.FileFaces = [
  42233. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  42234. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  42235. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  42236. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  42237. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  42238. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  42239. ];
  42240. return CubeMapToSphericalPolynomialTools;
  42241. }());
  42242. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  42243. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42244. })(BABYLON || (BABYLON = {}));
  42245. var BABYLON;
  42246. (function (BABYLON) {
  42247. var Internals;
  42248. (function (Internals) {
  42249. /**
  42250. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  42251. */
  42252. var PanoramaToCubeMapTools = (function () {
  42253. function PanoramaToCubeMapTools() {
  42254. }
  42255. /**
  42256. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  42257. *
  42258. * @param float32Array The source data.
  42259. * @param inputWidth The width of the input panorama.
  42260. * @param inputhHeight The height of the input panorama.
  42261. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  42262. * @return The cubemap data
  42263. */
  42264. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  42265. if (!float32Array) {
  42266. throw "ConvertPanoramaToCubemap: input cannot be null";
  42267. }
  42268. if (float32Array.length != inputWidth * inputHeight * 3) {
  42269. throw "ConvertPanoramaToCubemap: input size is wrong";
  42270. }
  42271. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  42272. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  42273. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  42274. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  42275. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  42276. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  42277. return {
  42278. front: textureFront,
  42279. back: textureBack,
  42280. left: textureLeft,
  42281. right: textureRight,
  42282. up: textureUp,
  42283. down: textureDown,
  42284. size: size
  42285. };
  42286. };
  42287. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  42288. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  42289. var textureArray = new Float32Array(buffer);
  42290. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  42291. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  42292. var dy = 1 / texSize;
  42293. var fy = 0;
  42294. for (var y = 0; y < texSize; y++) {
  42295. var xv1 = faceData[0];
  42296. var xv2 = faceData[2];
  42297. for (var x = 0; x < texSize; x++) {
  42298. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  42299. v.normalize();
  42300. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  42301. // 3 channels per pixels
  42302. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  42303. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  42304. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  42305. xv1 = xv1.add(rotDX1);
  42306. xv2 = xv2.add(rotDX2);
  42307. }
  42308. fy += dy;
  42309. }
  42310. return textureArray;
  42311. };
  42312. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  42313. var theta = Math.atan2(vDir.z, vDir.x);
  42314. var phi = Math.acos(vDir.y);
  42315. while (theta < -Math.PI)
  42316. theta += 2 * Math.PI;
  42317. while (theta > Math.PI)
  42318. theta -= 2 * Math.PI;
  42319. var dx = theta / Math.PI;
  42320. var dy = phi / Math.PI;
  42321. // recenter.
  42322. dx = dx * 0.5 + 0.5;
  42323. var px = Math.round(dx * inputWidth);
  42324. if (px < 0)
  42325. px = 0;
  42326. else if (px >= inputWidth)
  42327. px = inputWidth - 1;
  42328. var py = Math.round(dy * inputHeight);
  42329. if (py < 0)
  42330. py = 0;
  42331. else if (py >= inputHeight)
  42332. py = inputHeight - 1;
  42333. var inputY = (inputHeight - py - 1);
  42334. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  42335. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  42336. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  42337. return {
  42338. r: r,
  42339. g: g,
  42340. b: b
  42341. };
  42342. };
  42343. PanoramaToCubeMapTools.FACE_FRONT = [
  42344. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42345. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42346. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42347. new BABYLON.Vector3(1.0, 1.0, -1.0)
  42348. ];
  42349. PanoramaToCubeMapTools.FACE_BACK = [
  42350. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42351. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42352. new BABYLON.Vector3(1.0, 1.0, 1.0),
  42353. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  42354. ];
  42355. PanoramaToCubeMapTools.FACE_RIGHT = [
  42356. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42357. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42358. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42359. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42360. ];
  42361. PanoramaToCubeMapTools.FACE_LEFT = [
  42362. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42363. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42364. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42365. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  42366. ];
  42367. PanoramaToCubeMapTools.FACE_DOWN = [
  42368. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42369. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42370. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42371. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42372. ];
  42373. PanoramaToCubeMapTools.FACE_UP = [
  42374. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42375. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42376. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42377. new BABYLON.Vector3(1.0, -1.0, -1.0)
  42378. ];
  42379. return PanoramaToCubeMapTools;
  42380. }());
  42381. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  42382. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42383. })(BABYLON || (BABYLON = {}));
  42384. var BABYLON;
  42385. (function (BABYLON) {
  42386. var Internals;
  42387. (function (Internals) {
  42388. ;
  42389. /**
  42390. * This groups tools to convert HDR texture to native colors array.
  42391. */
  42392. var HDRTools = (function () {
  42393. function HDRTools() {
  42394. }
  42395. HDRTools.Ldexp = function (mantissa, exponent) {
  42396. if (exponent > 1023) {
  42397. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  42398. }
  42399. if (exponent < -1074) {
  42400. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  42401. }
  42402. return mantissa * Math.pow(2, exponent);
  42403. };
  42404. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  42405. if (exponent > 0) {
  42406. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  42407. float32array[index + 0] = red * exponent;
  42408. float32array[index + 1] = green * exponent;
  42409. float32array[index + 2] = blue * exponent;
  42410. }
  42411. else {
  42412. float32array[index + 0] = 0;
  42413. float32array[index + 1] = 0;
  42414. float32array[index + 2] = 0;
  42415. }
  42416. };
  42417. HDRTools.readStringLine = function (uint8array, startIndex) {
  42418. var line = "";
  42419. var character = "";
  42420. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  42421. character = String.fromCharCode(uint8array[i]);
  42422. if (character == "\n") {
  42423. break;
  42424. }
  42425. line += character;
  42426. }
  42427. return line;
  42428. };
  42429. /**
  42430. * Reads header information from an RGBE texture stored in a native array.
  42431. * More information on this format are available here:
  42432. * https://en.wikipedia.org/wiki/RGBE_image_format
  42433. *
  42434. * @param uint8array The binary file stored in native array.
  42435. * @return The header information.
  42436. */
  42437. HDRTools.RGBE_ReadHeader = function (uint8array) {
  42438. var height = 0;
  42439. var width = 0;
  42440. var line = this.readStringLine(uint8array, 0);
  42441. if (line[0] != '#' || line[1] != '?') {
  42442. throw "Bad HDR Format.";
  42443. }
  42444. var endOfHeader = false;
  42445. var findFormat = false;
  42446. var lineIndex = 0;
  42447. do {
  42448. lineIndex += (line.length + 1);
  42449. line = this.readStringLine(uint8array, lineIndex);
  42450. if (line == "FORMAT=32-bit_rle_rgbe") {
  42451. findFormat = true;
  42452. }
  42453. else if (line.length == 0) {
  42454. endOfHeader = true;
  42455. }
  42456. } while (!endOfHeader);
  42457. if (!findFormat) {
  42458. throw "HDR Bad header format, unsupported FORMAT";
  42459. }
  42460. lineIndex += (line.length + 1);
  42461. line = this.readStringLine(uint8array, lineIndex);
  42462. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  42463. var match = sizeRegexp.exec(line);
  42464. // TODO. Support +Y and -X if needed.
  42465. if (match.length < 3) {
  42466. throw "HDR Bad header format, no size";
  42467. }
  42468. width = parseInt(match[2]);
  42469. height = parseInt(match[1]);
  42470. if (width < 8 || width > 0x7fff) {
  42471. throw "HDR Bad header format, unsupported size";
  42472. }
  42473. lineIndex += (line.length + 1);
  42474. return {
  42475. height: height,
  42476. width: width,
  42477. dataPosition: lineIndex
  42478. };
  42479. };
  42480. /**
  42481. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  42482. * This RGBE texture needs to store the information as a panorama.
  42483. *
  42484. * More information on this format are available here:
  42485. * https://en.wikipedia.org/wiki/RGBE_image_format
  42486. *
  42487. * @param buffer The binary file stored in an array buffer.
  42488. * @param size The expected size of the extracted cubemap.
  42489. * @return The Cube Map information.
  42490. */
  42491. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  42492. var uint8array = new Uint8Array(buffer);
  42493. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  42494. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42495. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  42496. return cubeMapData;
  42497. };
  42498. /**
  42499. * Returns the pixels data extracted from an RGBE texture.
  42500. * This pixels will be stored left to right up to down in the R G B order in one array.
  42501. *
  42502. * More information on this format are available here:
  42503. * https://en.wikipedia.org/wiki/RGBE_image_format
  42504. *
  42505. * @param uint8array The binary file stored in an array buffer.
  42506. * @param hdrInfo The header information of the file.
  42507. * @return The pixels data in RGB right to left up to down order.
  42508. */
  42509. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  42510. // Keep for multi format supports.
  42511. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42512. };
  42513. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  42514. var num_scanlines = hdrInfo.height;
  42515. var scanline_width = hdrInfo.width;
  42516. var a, b, c, d, count;
  42517. var dataIndex = hdrInfo.dataPosition;
  42518. var index = 0, endIndex = 0, i = 0;
  42519. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  42520. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  42521. // 3 channels of 4 bytes per pixel in float.
  42522. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  42523. var resultArray = new Float32Array(resultBuffer);
  42524. // read in each successive scanline
  42525. while (num_scanlines > 0) {
  42526. a = uint8array[dataIndex++];
  42527. b = uint8array[dataIndex++];
  42528. c = uint8array[dataIndex++];
  42529. d = uint8array[dataIndex++];
  42530. if (a != 2 || b != 2 || (c & 0x80)) {
  42531. // this file is not run length encoded
  42532. throw "HDR Bad header format, not RLE";
  42533. }
  42534. if (((c << 8) | d) != scanline_width) {
  42535. throw "HDR Bad header format, wrong scan line width";
  42536. }
  42537. index = 0;
  42538. // read each of the four channels for the scanline into the buffer
  42539. for (i = 0; i < 4; i++) {
  42540. endIndex = (i + 1) * scanline_width;
  42541. while (index < endIndex) {
  42542. a = uint8array[dataIndex++];
  42543. b = uint8array[dataIndex++];
  42544. if (a > 128) {
  42545. // a run of the same value
  42546. count = a - 128;
  42547. if ((count == 0) || (count > endIndex - index)) {
  42548. throw "HDR Bad Format, bad scanline data (run)";
  42549. }
  42550. while (count-- > 0) {
  42551. scanLineArray[index++] = b;
  42552. }
  42553. }
  42554. else {
  42555. // a non-run
  42556. count = a;
  42557. if ((count == 0) || (count > endIndex - index)) {
  42558. throw "HDR Bad Format, bad scanline data (non-run)";
  42559. }
  42560. scanLineArray[index++] = b;
  42561. if (--count > 0) {
  42562. for (var j = 0; j < count; j++) {
  42563. scanLineArray[index++] = uint8array[dataIndex++];
  42564. }
  42565. }
  42566. }
  42567. }
  42568. }
  42569. // now convert data from buffer into floats
  42570. for (i = 0; i < scanline_width; i++) {
  42571. a = scanLineArray[i];
  42572. b = scanLineArray[i + scanline_width];
  42573. c = scanLineArray[i + 2 * scanline_width];
  42574. d = scanLineArray[i + 3 * scanline_width];
  42575. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  42576. }
  42577. num_scanlines--;
  42578. }
  42579. return resultArray;
  42580. };
  42581. return HDRTools;
  42582. }());
  42583. Internals.HDRTools = HDRTools;
  42584. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42585. })(BABYLON || (BABYLON = {}));
  42586. //_______________________________________________________________
  42587. // Extracted from CubeMapGen:
  42588. // https://code.google.com/archive/p/cubemapgen/
  42589. //
  42590. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42591. //_______________________________________________________________
  42592. var BABYLON;
  42593. (function (BABYLON) {
  42594. var Internals;
  42595. (function (Internals) {
  42596. /**
  42597. * The bounding box information used during the conversion process.
  42598. */
  42599. var CMGBoundinBox = (function () {
  42600. function CMGBoundinBox() {
  42601. this.min = new BABYLON.Vector3(0, 0, 0);
  42602. this.max = new BABYLON.Vector3(0, 0, 0);
  42603. this.clear();
  42604. }
  42605. CMGBoundinBox.prototype.clear = function () {
  42606. this.min.x = CMGBoundinBox.MAX;
  42607. this.min.y = CMGBoundinBox.MAX;
  42608. this.min.z = CMGBoundinBox.MAX;
  42609. this.max.x = CMGBoundinBox.MIN;
  42610. this.max.y = CMGBoundinBox.MIN;
  42611. this.max.z = CMGBoundinBox.MIN;
  42612. };
  42613. CMGBoundinBox.prototype.augment = function (x, y, z) {
  42614. this.min.x = Math.min(this.min.x, x);
  42615. this.min.y = Math.min(this.min.y, y);
  42616. this.min.z = Math.min(this.min.z, z);
  42617. this.max.x = Math.max(this.max.x, x);
  42618. this.max.y = Math.max(this.max.y, y);
  42619. this.max.z = Math.max(this.max.z, z);
  42620. };
  42621. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  42622. this.min.x = Math.max(this.min.x, x);
  42623. this.min.y = Math.max(this.min.y, y);
  42624. this.min.z = Math.max(this.min.z, z);
  42625. };
  42626. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  42627. this.max.x = Math.min(this.max.x, x);
  42628. this.max.y = Math.min(this.max.y, y);
  42629. this.max.z = Math.min(this.max.z, z);
  42630. };
  42631. CMGBoundinBox.prototype.empty = function () {
  42632. if ((this.min.x > this.max.y) ||
  42633. (this.min.y > this.max.y) ||
  42634. (this.min.z > this.max.y)) {
  42635. return true;
  42636. }
  42637. else {
  42638. return false;
  42639. }
  42640. };
  42641. CMGBoundinBox.MAX = Number.MAX_VALUE;
  42642. CMGBoundinBox.MIN = Number.MIN_VALUE;
  42643. return CMGBoundinBox;
  42644. }());
  42645. /**
  42646. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  42647. * required by the glossinees of a material.
  42648. *
  42649. * This only supports the cosine drop power as well as Warp fixup generation method.
  42650. *
  42651. * This is using the process from CubeMapGen described here:
  42652. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42653. */
  42654. var PMREMGenerator = (function () {
  42655. /**
  42656. * Constructor of the generator.
  42657. *
  42658. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  42659. * @param inputSize The size of the cubemap faces
  42660. * @param outputSize The size of the output cubemap faces
  42661. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  42662. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  42663. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  42664. * @param specularPower The max specular level of the desired cubemap
  42665. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  42666. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  42667. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  42668. */
  42669. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  42670. this.input = input;
  42671. this.inputSize = inputSize;
  42672. this.outputSize = outputSize;
  42673. this.maxNumMipLevels = maxNumMipLevels;
  42674. this.numChannels = numChannels;
  42675. this.isFloat = isFloat;
  42676. this.specularPower = specularPower;
  42677. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  42678. this.excludeBase = excludeBase;
  42679. this.fixup = fixup;
  42680. this._outputSurface = [];
  42681. this._numMipLevels = 0;
  42682. }
  42683. /**
  42684. * Launches the filter process and return the result.
  42685. *
  42686. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  42687. */
  42688. PMREMGenerator.prototype.filterCubeMap = function () {
  42689. // Init cubemap processor
  42690. this.init();
  42691. // Filters the cubemap
  42692. this.filterCubeMapMipChain();
  42693. // Returns the filtered mips.
  42694. return this._outputSurface;
  42695. };
  42696. PMREMGenerator.prototype.init = function () {
  42697. var i;
  42698. var j;
  42699. var mipLevelSize;
  42700. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  42701. if (this.maxNumMipLevels == 0) {
  42702. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  42703. }
  42704. //first miplevel size
  42705. mipLevelSize = this.outputSize;
  42706. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  42707. for (j = 0; j < this.maxNumMipLevels; j++) {
  42708. this._outputSurface.length++;
  42709. this._outputSurface[j] = [];
  42710. //Iterate over faces for output images
  42711. for (i = 0; i < 6; i++) {
  42712. this._outputSurface[j].length++;
  42713. // Initializes a new array for the output.
  42714. if (this.isFloat) {
  42715. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42716. }
  42717. else {
  42718. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42719. }
  42720. }
  42721. //next mip level is half size
  42722. mipLevelSize >>= 1;
  42723. this._numMipLevels++;
  42724. //terminate if mip chain becomes too small
  42725. if (mipLevelSize == 0) {
  42726. this.maxNumMipLevels = j;
  42727. return;
  42728. }
  42729. }
  42730. };
  42731. //--------------------------------------------------------------------------------------
  42732. //Cube map filtering and mip chain generation.
  42733. // the cube map filtereing is specified using a number of parameters:
  42734. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  42735. // indicates the region of the hemisphere to filter over for each tap.
  42736. //
  42737. // Note that the top mip level is also a filtered version of the original input images
  42738. // as well in order to create mip chains for diffuse environment illumination.
  42739. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  42740. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  42741. //
  42742. // Then the mip angle used to genreate the next level of the mip chain from the first level
  42743. // is a_InitialMipAngle
  42744. //
  42745. // The angle for the subsequent levels of the mip chain are specified by their parents
  42746. // filtering angle and a per-level scale and bias
  42747. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  42748. //
  42749. //--------------------------------------------------------------------------------------
  42750. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  42751. // First, take count of the lighting model to modify SpecularPower
  42752. // 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;
  42753. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  42754. //Cone angle start (for generating subsequent mip levels)
  42755. var currentSpecularPower = this.specularPower;
  42756. //Build filter lookup tables based on the source miplevel size
  42757. this.precomputeFilterLookupTables(this.inputSize);
  42758. // Note that we need to filter the first level before generating mipmap
  42759. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  42760. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  42761. // TODO : Write a function to copy and scale the base mipmap in output
  42762. // I am just lazy here and just put a high specular power value, and do some if.
  42763. if (this.excludeBase && (levelIndex == 0)) {
  42764. // 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).
  42765. currentSpecularPower = 100000.0;
  42766. }
  42767. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  42768. var srcCubeImage = this.input;
  42769. var dstCubeImage = this._outputSurface[levelIndex];
  42770. var dstSize = this.outputSize >> levelIndex;
  42771. // Compute required angle.
  42772. var angle = this.getBaseFilterAngle(currentSpecularPower);
  42773. // filter cube surfaces
  42774. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  42775. // fix seams
  42776. if (this.fixup) {
  42777. this.fixupCubeEdges(dstCubeImage, dstSize);
  42778. }
  42779. // Decrease the specular power to generate the mipmap chain
  42780. // TODO : Use another method for Exclude (see first comment at start of the function
  42781. if (this.excludeBase && (levelIndex == 0)) {
  42782. currentSpecularPower = this.specularPower;
  42783. }
  42784. currentSpecularPower *= this.cosinePowerDropPerMip;
  42785. }
  42786. };
  42787. //--------------------------------------------------------------------------------------
  42788. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  42789. // It allow to optimize the texel to access base on the specular power.
  42790. //--------------------------------------------------------------------------------------
  42791. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  42792. // We want to find the alpha such that:
  42793. // cos(alpha)^cosinePower = epsilon
  42794. // That's: acos(epsilon^(1/cosinePower))
  42795. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  42796. var angle = 180.0;
  42797. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  42798. angle *= 180.0 / Math.PI; // Convert to degree
  42799. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  42800. return angle;
  42801. };
  42802. //--------------------------------------------------------------------------------------
  42803. //Builds the following lookup tables prior to filtering:
  42804. // -normalizer cube map
  42805. // -tap weight lookup table
  42806. //
  42807. //--------------------------------------------------------------------------------------
  42808. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  42809. var srcTexelAngle;
  42810. var iCubeFace;
  42811. //clear pre-existing normalizer cube map
  42812. this._normCubeMap = [];
  42813. //Normalized vectors per cubeface and per-texel solid angle
  42814. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  42815. };
  42816. //--------------------------------------------------------------------------------------
  42817. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  42818. //
  42819. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  42820. //
  42821. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  42822. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  42823. // below
  42824. //--------------------------------------------------------------------------------------
  42825. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  42826. var iCubeFace;
  42827. var u;
  42828. var v;
  42829. //iterate over cube faces
  42830. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  42831. //First three channels for norm cube, and last channel for solid angle
  42832. this._normCubeMap.push(new Float32Array(size * size * 4));
  42833. //fast texture walk, build normalizer cube map
  42834. var facesData = this.input[iCubeFace];
  42835. for (v = 0; v < size; v++) {
  42836. for (u = 0; u < size; u++) {
  42837. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  42838. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  42839. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  42840. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  42841. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  42842. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  42843. }
  42844. }
  42845. }
  42846. };
  42847. //--------------------------------------------------------------------------------------
  42848. // Convert cubemap face texel coordinates and face idx to 3D vector
  42849. // note the U and V coords are integer coords and range from 0 to size-1
  42850. // this routine can be used to generate a normalizer cube map
  42851. //--------------------------------------------------------------------------------------
  42852. // SL BEGIN
  42853. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  42854. var nvcU;
  42855. var nvcV;
  42856. var tempVec;
  42857. // Change from original AMD code
  42858. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  42859. // + 0.5f is for texel center addressing
  42860. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  42861. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  42862. // warp fixup
  42863. if (fixup && size > 1) {
  42864. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  42865. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  42866. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  42867. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  42868. }
  42869. // Get current vector
  42870. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  42871. // U contribution
  42872. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  42873. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  42874. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  42875. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  42876. // V contribution and Sum
  42877. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  42878. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  42879. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  42880. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  42881. //add face axis
  42882. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  42883. PMREMGenerator._vectorTemp.x += faceAxis[0];
  42884. PMREMGenerator._vectorTemp.y += faceAxis[1];
  42885. PMREMGenerator._vectorTemp.z += faceAxis[2];
  42886. //normalize vector
  42887. PMREMGenerator._vectorTemp.normalize();
  42888. return PMREMGenerator._vectorTemp;
  42889. };
  42890. //--------------------------------------------------------------------------------------
  42891. // Convert 3D vector to cubemap face texel coordinates and face idx
  42892. // note the U and V coords are integer coords and range from 0 to size-1
  42893. // this routine can be used to generate a normalizer cube map
  42894. //
  42895. // returns face IDX and texel coords
  42896. //--------------------------------------------------------------------------------------
  42897. // SL BEGIN
  42898. /*
  42899. Mapping Texture Coordinates to Cube Map Faces
  42900. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  42901. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  42902. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  42903. map arrangement in Pixar's RenderMan package.
  42904. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  42905. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  42906. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  42907. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  42908. the major axis direction). The target column in the table below explains how the major axis direction
  42909. maps to the 2D image of a particular cube map target.
  42910. major axis
  42911. direction target sc tc ma
  42912. ---------- --------------------------------- --- --- ---
  42913. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  42914. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  42915. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  42916. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  42917. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  42918. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  42919. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  42920. an updated (s,t) is calculated as follows
  42921. s = ( sc/|ma| + 1 ) / 2
  42922. t = ( tc/|ma| + 1 ) / 2
  42923. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  42924. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  42925. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  42926. */
  42927. // Note this method return U and V in range from 0 to size-1
  42928. // SL END
  42929. // Store the information in vector3 for convenience (faceindex, u, v)
  42930. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  42931. var maxCoord;
  42932. var faceIdx;
  42933. //absolute value 3
  42934. var absX = Math.abs(x);
  42935. var absY = Math.abs(y);
  42936. var absZ = Math.abs(z);
  42937. if (absX >= absY && absX >= absZ) {
  42938. maxCoord = absX;
  42939. if (x >= 0) {
  42940. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  42941. }
  42942. else {
  42943. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  42944. }
  42945. }
  42946. else if (absY >= absX && absY >= absZ) {
  42947. maxCoord = absY;
  42948. if (y >= 0) {
  42949. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  42950. }
  42951. else {
  42952. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  42953. }
  42954. }
  42955. else {
  42956. maxCoord = absZ;
  42957. if (z >= 0) {
  42958. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  42959. }
  42960. else {
  42961. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  42962. }
  42963. }
  42964. //divide through by max coord so face vector lies on cube face
  42965. var scale = 1 / maxCoord;
  42966. x *= scale;
  42967. y *= scale;
  42968. z *= scale;
  42969. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  42970. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  42971. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  42972. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  42973. // Modify original AMD code to return value from 0 to Size - 1
  42974. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  42975. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  42976. PMREMGenerator._vectorTemp.x = faceIdx;
  42977. PMREMGenerator._vectorTemp.y = u;
  42978. PMREMGenerator._vectorTemp.z = v;
  42979. return PMREMGenerator._vectorTemp;
  42980. };
  42981. //--------------------------------------------------------------------------------------
  42982. //Original code from Ignacio CastaÒo
  42983. // This formula is from Manne ÷hrstrˆm's thesis.
  42984. // Take two coordiantes in the range [-1, 1] that define a portion of a
  42985. // cube face and return the area of the projection of that portion on the
  42986. // surface of the sphere.
  42987. //--------------------------------------------------------------------------------------
  42988. PMREMGenerator.prototype.areaElement = function (x, y) {
  42989. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  42990. };
  42991. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  42992. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  42993. // (+ 0.5f is for texel center addressing)
  42994. u = (2.0 * (u + 0.5) / size) - 1.0;
  42995. v = (2.0 * (v + 0.5) / size) - 1.0;
  42996. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  42997. var invResolution = 1.0 / size;
  42998. // U and V are the -1..1 texture coordinate on the current face.
  42999. // Get projected area for this texel
  43000. var x0 = u - invResolution;
  43001. var y0 = v - invResolution;
  43002. var x1 = u + invResolution;
  43003. var y1 = v + invResolution;
  43004. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  43005. return solidAngle;
  43006. };
  43007. //--------------------------------------------------------------------------------------
  43008. //The key to the speed of these filtering routines is to quickly define a per-face
  43009. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  43010. // Later these pixels are selectively processed based on their dot products to see if
  43011. // they reside within the filtering cone.
  43012. //
  43013. //This is done by computing the smallest per-texel angle to get a conservative estimate
  43014. // of the number of texels needed to be covered in width and height order to filter the
  43015. // region. the bounding box for the center taps face is defined first, and if the
  43016. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  43017. // defined next
  43018. //--------------------------------------------------------------------------------------
  43019. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  43020. // note that pixels within these regions may be rejected
  43021. // based on the anlge
  43022. var iCubeFace;
  43023. var u;
  43024. var v;
  43025. // bounding box per face to specify region to process
  43026. var filterExtents = [];
  43027. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43028. filterExtents.push(new CMGBoundinBox());
  43029. }
  43030. // min angle a src texel can cover (in degrees)
  43031. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  43032. // angle about center tap to define filter cone
  43033. // filter angle is 1/2 the cone angle
  43034. var filterAngle = filterConeAngle / 2.0;
  43035. //ensure filter angle is larger than a texel
  43036. if (filterAngle < srcTexelAngle) {
  43037. filterAngle = srcTexelAngle;
  43038. }
  43039. //ensure filter cone is always smaller than the hemisphere
  43040. if (filterAngle > 90.0) {
  43041. filterAngle = 90.0;
  43042. }
  43043. // the maximum number of texels in 1D the filter cone angle will cover
  43044. // used to determine bounding box size for filter extents
  43045. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  43046. // ensure conservative region always covers at least one texel
  43047. if (filterSize < 1) {
  43048. filterSize = 1;
  43049. }
  43050. // dotProdThresh threshold based on cone angle to determine whether or not taps
  43051. // reside within the cone angle
  43052. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  43053. // process required faces
  43054. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43055. //iterate over dst cube map face texel
  43056. for (v = 0; v < dstSize; v++) {
  43057. for (u = 0; u < dstSize; u++) {
  43058. //get center tap direction
  43059. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  43060. //clear old per-face filter extents
  43061. this.clearFilterExtents(filterExtents);
  43062. //define per-face filter extents
  43063. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  43064. //perform filtering of src faces using filter extents
  43065. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  43066. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  43067. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  43068. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  43069. }
  43070. }
  43071. }
  43072. };
  43073. //--------------------------------------------------------------------------------------
  43074. //Clear filter extents for the 6 cube map faces
  43075. //--------------------------------------------------------------------------------------
  43076. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  43077. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  43078. filterExtents[iCubeFaces].clear();
  43079. }
  43080. };
  43081. //--------------------------------------------------------------------------------------
  43082. //Define per-face bounding box filter extents
  43083. //
  43084. // These define conservative texel regions in each of the faces the filter can possibly
  43085. // process. When the pixels in the regions are actually processed, the dot product
  43086. // between the tap vector and the center tap vector is used to determine the weight of
  43087. // the tap and whether or not the tap is within the cone.
  43088. //
  43089. //--------------------------------------------------------------------------------------
  43090. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  43091. //neighboring face and bleed over amount, and width of BBOX for
  43092. // left, right, top, and bottom edges of this face
  43093. var bleedOverAmount = [0, 0, 0, 0];
  43094. var bleedOverBBoxMin = [0, 0, 0, 0];
  43095. var bleedOverBBoxMax = [0, 0, 0, 0];
  43096. var neighborFace;
  43097. var neighborEdge;
  43098. var oppositeFaceIdx;
  43099. //get face idx, and u, v info from center tap dir
  43100. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  43101. var faceIdx = result.x;
  43102. var u = result.y;
  43103. var v = result.z;
  43104. //define bbox size within face
  43105. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  43106. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  43107. filterExtents[faceIdx].clampMin(0, 0, 0);
  43108. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  43109. //u and v extent in face corresponding to center tap
  43110. var minU = filterExtents[faceIdx].min.x;
  43111. var minV = filterExtents[faceIdx].min.y;
  43112. var maxU = filterExtents[faceIdx].max.x;
  43113. var maxV = filterExtents[faceIdx].max.y;
  43114. //bleed over amounts for face across u=0 edge (left)
  43115. bleedOverAmount[0] = (bboxSize - u);
  43116. bleedOverBBoxMin[0] = minV;
  43117. bleedOverBBoxMax[0] = maxV;
  43118. //bleed over amounts for face across u=1 edge (right)
  43119. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  43120. bleedOverBBoxMin[1] = minV;
  43121. bleedOverBBoxMax[1] = maxV;
  43122. //bleed over to face across v=0 edge (up)
  43123. bleedOverAmount[2] = (bboxSize - v);
  43124. bleedOverBBoxMin[2] = minU;
  43125. bleedOverBBoxMax[2] = maxU;
  43126. //bleed over to face across v=1 edge (down)
  43127. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  43128. bleedOverBBoxMin[3] = minU;
  43129. bleedOverBBoxMax[3] = maxU;
  43130. //compute bleed over regions in neighboring faces
  43131. for (var i = 0; i < 4; i++) {
  43132. if (bleedOverAmount[i] > 0) {
  43133. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  43134. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  43135. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  43136. // be flipped: the cases are
  43137. // if a left edge mates with a left or bottom edge on the neighbor
  43138. // if a top edge mates with a top or right edge on the neighbor
  43139. // if a right edge mates with a right or top edge on the neighbor
  43140. // if a bottom edge mates with a bottom or left edge on the neighbor
  43141. //Seeing as the edges are enumerated as follows
  43142. // left =0
  43143. // right =1
  43144. // top =2
  43145. // bottom =3
  43146. //
  43147. // so if the edge enums are the same, or the sum of the enums == 3,
  43148. // the bbox needs to be flipped
  43149. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  43150. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  43151. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  43152. }
  43153. //The way the bounding box is extended onto the neighboring face
  43154. // depends on which edge of neighboring face abuts with this one
  43155. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  43156. case PMREMGenerator.CP_EDGE_LEFT:
  43157. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  43158. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43159. break;
  43160. case PMREMGenerator.CP_EDGE_RIGHT:
  43161. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  43162. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43163. break;
  43164. case PMREMGenerator.CP_EDGE_TOP:
  43165. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  43166. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  43167. break;
  43168. case PMREMGenerator.CP_EDGE_BOTTOM:
  43169. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  43170. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  43171. break;
  43172. }
  43173. //clamp filter extents in non-center tap faces to remain within surface
  43174. filterExtents[neighborFace].clampMin(0, 0, 0);
  43175. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  43176. }
  43177. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  43178. // from the center tap face, then process the opposite face entirely for now.
  43179. //Note that the cases in which this happens, what usually happens is that
  43180. // more than one edge bleeds onto the opposite face, and the bounding box
  43181. // encompasses the entire cube map face.
  43182. if (bleedOverAmount[i] > srcSize) {
  43183. //determine opposite face
  43184. switch (faceIdx) {
  43185. case PMREMGenerator.CP_FACE_X_POS:
  43186. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43187. break;
  43188. case PMREMGenerator.CP_FACE_X_NEG:
  43189. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  43190. break;
  43191. case PMREMGenerator.CP_FACE_Y_POS:
  43192. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43193. break;
  43194. case PMREMGenerator.CP_FACE_Y_NEG:
  43195. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43196. break;
  43197. case PMREMGenerator.CP_FACE_Z_POS:
  43198. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43199. break;
  43200. case PMREMGenerator.CP_FACE_Z_NEG:
  43201. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43202. break;
  43203. default:
  43204. break;
  43205. }
  43206. //just encompass entire face for now
  43207. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  43208. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  43209. }
  43210. }
  43211. };
  43212. //--------------------------------------------------------------------------------------
  43213. //ProcessFilterExtents
  43214. // Process bounding box in each cube face
  43215. //
  43216. //--------------------------------------------------------------------------------------
  43217. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  43218. //accumulators are 64-bit floats in order to have the precision needed
  43219. // over a summation of a large number of pixels
  43220. var dstAccum = [0, 0, 0, 0];
  43221. var weightAccum = 0;
  43222. var k = 0;
  43223. var nSrcChannels = this.numChannels;
  43224. // norm cube map and srcCubeMap have same face width
  43225. var faceWidth = srcSize;
  43226. //amount to add to pointer to move to next scanline in images
  43227. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  43228. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  43229. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  43230. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  43231. // iterate over cubefaces
  43232. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  43233. //if bbox is non empty
  43234. if (!filterExtents[iFaceIdx].empty()) {
  43235. var uStart = filterExtents[iFaceIdx].min.x;
  43236. var vStart = filterExtents[iFaceIdx].min.y;
  43237. var uEnd = filterExtents[iFaceIdx].max.x;
  43238. var vEnd = filterExtents[iFaceIdx].max.y;
  43239. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  43240. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  43241. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  43242. for (var v = vStart; v <= vEnd; v++) {
  43243. var normCubeRowWalk = 0;
  43244. var srcCubeRowWalk = 0;
  43245. for (var u = uStart; u <= uEnd; u++) {
  43246. //pointer to direction in cube map associated with texel
  43247. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  43248. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  43249. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  43250. //check dot product to see if texel is within cone
  43251. var tapDotProd = texelVectX * centerTapDir.x +
  43252. texelVectY * centerTapDir.y +
  43253. texelVectZ * centerTapDir.z;
  43254. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  43255. //solid angle stored in 4th channel of normalizer/solid angle cube map
  43256. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  43257. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  43258. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  43259. // so just adding one to specularpower do the trick.
  43260. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  43261. //iterate over channels
  43262. for (k = 0; k < nSrcChannels; k++) {
  43263. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  43264. srcCubeRowWalk++;
  43265. }
  43266. weightAccum += weight; //accumulate weight
  43267. }
  43268. else {
  43269. //step across source pixel
  43270. srcCubeRowWalk += nSrcChannels;
  43271. }
  43272. normCubeRowWalk += 4; // 4 channels per norm cube map.
  43273. }
  43274. startIndexNormCubeMap += normCubePitch;
  43275. startIndexSrcCubeMap += srcCubePitch;
  43276. }
  43277. }
  43278. }
  43279. //divide through by weights if weight is non zero
  43280. if (weightAccum != 0.0) {
  43281. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  43282. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  43283. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  43284. if (this.numChannels > 3) {
  43285. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  43286. }
  43287. }
  43288. else {
  43289. // otherwise sample nearest
  43290. // get face idx and u, v texel coordinate in face
  43291. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  43292. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  43293. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  43294. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  43295. if (this.numChannels > 3) {
  43296. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  43297. }
  43298. }
  43299. return PMREMGenerator._vectorTemp;
  43300. };
  43301. //--------------------------------------------------------------------------------------
  43302. // Fixup cube edges
  43303. //
  43304. // average texels on cube map faces across the edges
  43305. // WARP/BENT Method Only.
  43306. //--------------------------------------------------------------------------------------
  43307. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  43308. var k;
  43309. var j;
  43310. var i;
  43311. var iFace;
  43312. var iCorner = 0;
  43313. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  43314. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  43315. // note that if functionality to filter across the three texels for each corner, then
  43316. //indexed by corner and face idx. the array contains the face the start points belongs to.
  43317. var cornerPtr = [
  43318. [[], [], []],
  43319. [[], [], []],
  43320. [[], [], []],
  43321. [[], [], []],
  43322. [[], [], []],
  43323. [[], [], []],
  43324. [[], [], []],
  43325. [[], [], []]
  43326. ];
  43327. //if there is no fixup, or fixup width = 0, do nothing
  43328. if (cubeMapSize < 1) {
  43329. return;
  43330. }
  43331. //special case 1x1 cubemap, average face colors
  43332. if (cubeMapSize == 1) {
  43333. //iterate over channels
  43334. for (k = 0; k < this.numChannels; k++) {
  43335. var accum = 0.0;
  43336. //iterate over faces to accumulate face colors
  43337. for (iFace = 0; iFace < 6; iFace++) {
  43338. accum += cubeMap[iFace][k];
  43339. }
  43340. //compute average over 6 face colors
  43341. accum /= 6.0;
  43342. //iterate over faces to distribute face colors
  43343. for (iFace = 0; iFace < 6; iFace++) {
  43344. cubeMap[iFace][k] = accum;
  43345. }
  43346. }
  43347. return;
  43348. }
  43349. //iterate over faces to collect list of corner texel pointers
  43350. for (iFace = 0; iFace < 6; iFace++) {
  43351. //the 4 corner pointers for this face
  43352. faceCornerStartIndicies[0] = [iFace, 0];
  43353. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  43354. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  43355. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  43356. //iterate over face corners to collect cube corner pointers
  43357. for (iCorner = 0; iCorner < 4; iCorner++) {
  43358. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  43359. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  43360. cornerNumPtrs[corner]++;
  43361. }
  43362. }
  43363. //iterate over corners to average across corner tap values
  43364. for (iCorner = 0; iCorner < 8; iCorner++) {
  43365. for (k = 0; k < this.numChannels; k++) {
  43366. var cornerTapAccum = 0.0;
  43367. //iterate over corner texels and average results
  43368. for (i = 0; i < 3; i++) {
  43369. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  43370. }
  43371. //divide by 3 to compute average of corner tap values
  43372. cornerTapAccum *= (1.0 / 3.0);
  43373. //iterate over corner texels and average results
  43374. for (i = 0; i < 3; i++) {
  43375. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  43376. }
  43377. }
  43378. }
  43379. //iterate over the twelve edges of the cube to average across edges
  43380. for (i = 0; i < 12; i++) {
  43381. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  43382. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  43383. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  43384. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  43385. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  43386. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  43387. var edgeWalk = 0;
  43388. var neighborEdgeWalk = 0;
  43389. //Determine walking pointers based on edge type
  43390. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  43391. switch (edge) {
  43392. case PMREMGenerator.CP_EDGE_LEFT:
  43393. // no change to faceEdgeStartPtr
  43394. edgeWalk = this.numChannels * cubeMapSize;
  43395. break;
  43396. case PMREMGenerator.CP_EDGE_RIGHT:
  43397. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43398. edgeWalk = this.numChannels * cubeMapSize;
  43399. break;
  43400. case PMREMGenerator.CP_EDGE_TOP:
  43401. // no change to faceEdgeStartPtr
  43402. edgeWalk = this.numChannels;
  43403. break;
  43404. case PMREMGenerator.CP_EDGE_BOTTOM:
  43405. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43406. edgeWalk = this.numChannels;
  43407. break;
  43408. }
  43409. //For certain types of edge abutments, the neighbor edge walk needs to
  43410. // be flipped: the cases are
  43411. // if a left edge mates with a left or bottom edge on the neighbor
  43412. // if a top edge mates with a top or right edge on the neighbor
  43413. // if a right edge mates with a right or top edge on the neighbor
  43414. // if a bottom edge mates with a bottom or left edge on the neighbor
  43415. //Seeing as the edges are enumerated as follows
  43416. // left =0
  43417. // right =1
  43418. // top =2
  43419. // bottom =3
  43420. //
  43421. //If the edge enums are the same, or the sum of the enums == 3,
  43422. // the neighbor edge walk needs to be flipped
  43423. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  43424. switch (neighborEdge) {
  43425. case PMREMGenerator.CP_EDGE_LEFT:
  43426. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  43427. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43428. break;
  43429. case PMREMGenerator.CP_EDGE_RIGHT:
  43430. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43431. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43432. break;
  43433. case PMREMGenerator.CP_EDGE_TOP:
  43434. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43435. neighborEdgeWalk = -this.numChannels;
  43436. break;
  43437. case PMREMGenerator.CP_EDGE_BOTTOM:
  43438. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43439. neighborEdgeWalk = -this.numChannels;
  43440. break;
  43441. }
  43442. }
  43443. else {
  43444. //swapped direction neighbor edge walk
  43445. switch (neighborEdge) {
  43446. case PMREMGenerator.CP_EDGE_LEFT:
  43447. //no change to neighborEdgeStartPtr for this case since it points
  43448. // to the upper left corner already
  43449. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43450. break;
  43451. case PMREMGenerator.CP_EDGE_RIGHT:
  43452. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43453. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43454. break;
  43455. case PMREMGenerator.CP_EDGE_TOP:
  43456. //no change to neighborEdgeStartPtr for this case since it points
  43457. // to the upper left corner already
  43458. neighborEdgeWalk = this.numChannels;
  43459. break;
  43460. case PMREMGenerator.CP_EDGE_BOTTOM:
  43461. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43462. neighborEdgeWalk = this.numChannels;
  43463. break;
  43464. }
  43465. }
  43466. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  43467. //nearby neighborhood
  43468. //step ahead one texel on edge
  43469. edgeStartIndex += edgeWalk;
  43470. neighborEdgeStartIndex += neighborEdgeWalk;
  43471. // note that this loop does not process the corner texels, since they have already been
  43472. // averaged across faces across earlier
  43473. for (j = 1; j < (cubeMapSize - 1); j++) {
  43474. //for each set of taps along edge, average them
  43475. // and rewrite the results into the edges
  43476. for (k = 0; k < this.numChannels; k++) {
  43477. var edgeTap = cubeMap[face][edgeStartIndex + k];
  43478. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  43479. //compute average of tap intensity values
  43480. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  43481. //propagate average of taps to edge taps
  43482. cubeMap[face][edgeStartIndex + k] = avgTap;
  43483. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  43484. }
  43485. edgeStartIndex += edgeWalk;
  43486. neighborEdgeStartIndex += neighborEdgeWalk;
  43487. }
  43488. }
  43489. };
  43490. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  43491. PMREMGenerator.CP_UDIR = 0;
  43492. PMREMGenerator.CP_VDIR = 1;
  43493. PMREMGenerator.CP_FACEAXIS = 2;
  43494. //used to index cube faces
  43495. PMREMGenerator.CP_FACE_X_POS = 0;
  43496. PMREMGenerator.CP_FACE_X_NEG = 1;
  43497. PMREMGenerator.CP_FACE_Y_POS = 2;
  43498. PMREMGenerator.CP_FACE_Y_NEG = 3;
  43499. PMREMGenerator.CP_FACE_Z_POS = 4;
  43500. PMREMGenerator.CP_FACE_Z_NEG = 5;
  43501. //used to index image edges
  43502. // NOTE.. the actual number corresponding to the edge is important
  43503. // do not change these, or the code will break
  43504. //
  43505. // CP_EDGE_LEFT is u = 0
  43506. // CP_EDGE_RIGHT is u = width-1
  43507. // CP_EDGE_TOP is v = 0
  43508. // CP_EDGE_BOTTOM is v = height-1
  43509. PMREMGenerator.CP_EDGE_LEFT = 0;
  43510. PMREMGenerator.CP_EDGE_RIGHT = 1;
  43511. PMREMGenerator.CP_EDGE_TOP = 2;
  43512. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  43513. //corners of CUBE map (P or N specifys if it corresponds to the
  43514. // positive or negative direction each of X, Y, and Z
  43515. PMREMGenerator.CP_CORNER_NNN = 0;
  43516. PMREMGenerator.CP_CORNER_NNP = 1;
  43517. PMREMGenerator.CP_CORNER_NPN = 2;
  43518. PMREMGenerator.CP_CORNER_NPP = 3;
  43519. PMREMGenerator.CP_CORNER_PNN = 4;
  43520. PMREMGenerator.CP_CORNER_PNP = 5;
  43521. PMREMGenerator.CP_CORNER_PPN = 6;
  43522. PMREMGenerator.CP_CORNER_PPP = 7;
  43523. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  43524. //3x2 matrices that map cube map indexing vectors in 3d
  43525. // (after face selection and divide through by the
  43526. // _ABSOLUTE VALUE_ of the max coord)
  43527. // into NVC space
  43528. //Note this currently assumes the D3D cube face ordering and orientation
  43529. PMREMGenerator._sgFace2DMapping = [
  43530. //XPOS face
  43531. [[0, 0, -1],
  43532. [0, -1, 0],
  43533. [1, 0, 0]],
  43534. //XNEG face
  43535. [[0, 0, 1],
  43536. [0, -1, 0],
  43537. [-1, 0, 0]],
  43538. //YPOS face
  43539. [[1, 0, 0],
  43540. [0, 0, 1],
  43541. [0, 1, 0]],
  43542. //YNEG face
  43543. [[1, 0, 0],
  43544. [0, 0, -1],
  43545. [0, -1, 0]],
  43546. //ZPOS face
  43547. [[1, 0, 0],
  43548. [0, -1, 0],
  43549. [0, 0, 1]],
  43550. //ZNEG face
  43551. [[-1, 0, 0],
  43552. [0, -1, 0],
  43553. [0, 0, -1]],
  43554. ];
  43555. //------------------------------------------------------------------------------
  43556. // D3D cube map face specification
  43557. // mapping from 3D x,y,z cube map lookup coordinates
  43558. // to 2D within face u,v coordinates
  43559. //
  43560. // --------------------> U direction
  43561. // | (within-face texture space)
  43562. // | _____
  43563. // | | |
  43564. // | | +Y |
  43565. // | _____|_____|_____ _____
  43566. // | | | | | |
  43567. // | | -X | +Z | +X | -Z |
  43568. // | |_____|_____|_____|_____|
  43569. // | | |
  43570. // | | -Y |
  43571. // | |_____|
  43572. // |
  43573. // v V direction
  43574. // (within-face texture space)
  43575. //------------------------------------------------------------------------------
  43576. //Information about neighbors and how texture coorrdinates change across faces
  43577. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  43578. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  43579. //Note this currently assumes the D3D cube face ordering and orientation
  43580. PMREMGenerator._sgCubeNgh = [
  43581. //XPOS face
  43582. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43583. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43584. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43585. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  43586. //XNEG face
  43587. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43588. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  43589. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  43590. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  43591. //YPOS face
  43592. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43593. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43594. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43595. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  43596. //YNEG face
  43597. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43598. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43599. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43600. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  43601. //ZPOS face
  43602. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43603. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43604. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43605. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  43606. //ZNEG face
  43607. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43608. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43609. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  43610. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  43611. ];
  43612. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  43613. // this table is used to average over the edges.
  43614. PMREMGenerator._sgCubeEdgeList = [
  43615. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43616. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43617. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43618. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43619. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43620. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43621. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43622. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43623. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  43624. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43625. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43626. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  43627. ];
  43628. //Information about which of the 8 cube corners are correspond to the
  43629. // the 4 corners in each cube face
  43630. // the order is upper left, upper right, lower left, lower right
  43631. PMREMGenerator._sgCubeCornerList = [
  43632. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  43633. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  43634. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  43635. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  43636. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  43637. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  43638. ];
  43639. return PMREMGenerator;
  43640. }());
  43641. Internals.PMREMGenerator = PMREMGenerator;
  43642. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43643. })(BABYLON || (BABYLON = {}));
  43644. var BABYLON;
  43645. (function (BABYLON) {
  43646. /**
  43647. * This represents a texture coming from an HDR input.
  43648. *
  43649. * The only supported format is currently panorama picture stored in RGBE format.
  43650. * Example of such files can be found on HDRLib: http://hdrlib.com/
  43651. */
  43652. var HDRCubeTexture = (function (_super) {
  43653. __extends(HDRCubeTexture, _super);
  43654. /**
  43655. * Instantiates an HDRTexture from the following parameters.
  43656. *
  43657. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  43658. * @param scene The scene the texture will be used in
  43659. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  43660. * @param noMipmap Forces to not generate the mipmap if true
  43661. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  43662. * @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)
  43663. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  43664. */
  43665. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  43666. if (noMipmap === void 0) { noMipmap = false; }
  43667. if (generateHarmonics === void 0) { generateHarmonics = true; }
  43668. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  43669. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  43670. _super.call(this, scene);
  43671. this._useInGammaSpace = false;
  43672. this._generateHarmonics = true;
  43673. /**
  43674. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  43675. */
  43676. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  43677. /**
  43678. * The spherical polynomial data extracted from the texture.
  43679. */
  43680. this.sphericalPolynomial = null;
  43681. /**
  43682. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  43683. * This is usefull at run time to apply the good shader.
  43684. */
  43685. this.isPMREM = false;
  43686. this.name = url;
  43687. this.url = url;
  43688. this._noMipmap = noMipmap;
  43689. this.hasAlpha = false;
  43690. this._size = size;
  43691. this._useInGammaSpace = useInGammaSpace;
  43692. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  43693. this.isPMREM = this._usePMREMGenerator;
  43694. if (!url) {
  43695. return;
  43696. }
  43697. this._texture = this._getFromCache(url, noMipmap);
  43698. if (!this._texture) {
  43699. if (!scene.useDelayedTextureLoading) {
  43700. this.loadTexture();
  43701. }
  43702. else {
  43703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43704. }
  43705. }
  43706. this.isCube = true;
  43707. this._textureMatrix = BABYLON.Matrix.Identity();
  43708. }
  43709. HDRCubeTexture.prototype.loadTexture = function () {
  43710. var _this = this;
  43711. var callback = function (buffer) {
  43712. // Extract the raw linear data.
  43713. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  43714. // Generate harmonics if needed.
  43715. if (_this._generateHarmonics) {
  43716. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  43717. }
  43718. var results = [];
  43719. var byteArray = null;
  43720. // Create uintarray fallback.
  43721. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  43722. // 3 channels of 1 bytes per pixel in bytes.
  43723. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  43724. byteArray = new Uint8Array(byteBuffer);
  43725. }
  43726. // Push each faces.
  43727. for (var j = 0; j < 6; j++) {
  43728. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  43729. // If special cases.
  43730. if (_this._useInGammaSpace || byteArray) {
  43731. for (var i = 0; i < _this._size * _this._size; i++) {
  43732. // Put in gamma space if requested.
  43733. if (_this._useInGammaSpace) {
  43734. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  43735. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  43736. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  43737. }
  43738. // Convert to int texture for fallback.
  43739. if (byteArray) {
  43740. // R
  43741. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  43742. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  43743. // G
  43744. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  43745. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  43746. // B
  43747. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  43748. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  43749. }
  43750. }
  43751. }
  43752. results.push(dataFace);
  43753. }
  43754. return results;
  43755. };
  43756. var mipmapGenerator = null;
  43757. if (!this._noMipmap && this._usePMREMGenerator) {
  43758. mipmapGenerator = function (data) {
  43759. // Custom setup of the generator matching with the PBR shader values.
  43760. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  43761. return generator.filterCubeMap();
  43762. };
  43763. }
  43764. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  43765. };
  43766. HDRCubeTexture.prototype.clone = function () {
  43767. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  43768. // Base texture
  43769. newTexture.level = this.level;
  43770. newTexture.wrapU = this.wrapU;
  43771. newTexture.wrapV = this.wrapV;
  43772. newTexture.coordinatesIndex = this.coordinatesIndex;
  43773. newTexture.coordinatesMode = this.coordinatesMode;
  43774. return newTexture;
  43775. };
  43776. // Methods
  43777. HDRCubeTexture.prototype.delayLoad = function () {
  43778. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43779. return;
  43780. }
  43781. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43782. this._texture = this._getFromCache(this.url, this._noMipmap);
  43783. if (!this._texture) {
  43784. this.loadTexture();
  43785. }
  43786. };
  43787. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  43788. return this._textureMatrix;
  43789. };
  43790. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43791. var texture = null;
  43792. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  43793. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  43794. texture.name = parsedTexture.name;
  43795. texture.hasAlpha = parsedTexture.hasAlpha;
  43796. texture.level = parsedTexture.level;
  43797. texture.coordinatesMode = parsedTexture.coordinatesMode;
  43798. }
  43799. return texture;
  43800. };
  43801. HDRCubeTexture.prototype.serialize = function () {
  43802. if (!this.name) {
  43803. return null;
  43804. }
  43805. var serializationObject = {};
  43806. serializationObject.name = this.name;
  43807. serializationObject.hasAlpha = this.hasAlpha;
  43808. serializationObject.isCube = true;
  43809. serializationObject.level = this.level;
  43810. serializationObject.size = this._size;
  43811. serializationObject.coordinatesMode = this.coordinatesMode;
  43812. serializationObject.useInGammaSpace = this._useInGammaSpace;
  43813. serializationObject.generateHarmonics = this._generateHarmonics;
  43814. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  43815. return serializationObject;
  43816. };
  43817. HDRCubeTexture._facesMapping = [
  43818. "right",
  43819. "up",
  43820. "front",
  43821. "left",
  43822. "down",
  43823. "back"
  43824. ];
  43825. return HDRCubeTexture;
  43826. }(BABYLON.BaseTexture));
  43827. BABYLON.HDRCubeTexture = HDRCubeTexture;
  43828. })(BABYLON || (BABYLON = {}));
  43829. var BABYLON;
  43830. (function (BABYLON) {
  43831. var Debug;
  43832. (function (Debug) {
  43833. /**
  43834. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  43835. */
  43836. var SkeletonViewer = (function () {
  43837. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  43838. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  43839. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  43840. this.skeleton = skeleton;
  43841. this.mesh = mesh;
  43842. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  43843. this.renderingGroupId = renderingGroupId;
  43844. this.color = BABYLON.Color3.White();
  43845. this._debugLines = [];
  43846. this._isEnabled = false;
  43847. this._scene = scene;
  43848. this.update();
  43849. this._renderFunction = this.update.bind(this);
  43850. }
  43851. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  43852. get: function () {
  43853. return this._isEnabled;
  43854. },
  43855. set: function (value) {
  43856. if (this._isEnabled === value) {
  43857. return;
  43858. }
  43859. this._isEnabled = value;
  43860. if (value) {
  43861. this._scene.registerBeforeRender(this._renderFunction);
  43862. }
  43863. else {
  43864. this._scene.unregisterBeforeRender(this._renderFunction);
  43865. }
  43866. },
  43867. enumerable: true,
  43868. configurable: true
  43869. });
  43870. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  43871. if (x === void 0) { x = 0; }
  43872. if (y === void 0) { y = 0; }
  43873. if (z === void 0) { z = 0; }
  43874. var tmat = BABYLON.Tmp.Matrix[0];
  43875. var parentBone = bone.getParent();
  43876. tmat.copyFrom(bone.getLocalMatrix());
  43877. if (x !== 0 || y !== 0 || z !== 0) {
  43878. var tmat2 = BABYLON.Tmp.Matrix[1];
  43879. BABYLON.Matrix.IdentityToRef(tmat2);
  43880. tmat2.m[12] = x;
  43881. tmat2.m[13] = y;
  43882. tmat2.m[14] = z;
  43883. tmat2.multiplyToRef(tmat, tmat);
  43884. }
  43885. if (parentBone) {
  43886. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  43887. }
  43888. tmat.multiplyToRef(meshMat, tmat);
  43889. position.x = tmat.m[12];
  43890. position.y = tmat.m[13];
  43891. position.z = tmat.m[14];
  43892. };
  43893. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  43894. var len = bones.length;
  43895. for (var i = 0; i < len; i++) {
  43896. var bone = bones[i];
  43897. var points = this._debugLines[i];
  43898. if (!points) {
  43899. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43900. this._debugLines[i] = points;
  43901. }
  43902. this._getBonePosition(points[0], bone, meshMat);
  43903. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  43904. }
  43905. };
  43906. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  43907. var len = bones.length;
  43908. var boneNum = 0;
  43909. for (var i = len - 1; i >= 0; i--) {
  43910. var childBone = bones[i];
  43911. var parentBone = childBone.getParent();
  43912. if (!parentBone) {
  43913. continue;
  43914. }
  43915. var points = this._debugLines[boneNum];
  43916. if (!points) {
  43917. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43918. this._debugLines[boneNum] = points;
  43919. }
  43920. this._getBonePosition(points[0], childBone, meshMat);
  43921. this._getBonePosition(points[1], parentBone, meshMat);
  43922. boneNum++;
  43923. }
  43924. };
  43925. SkeletonViewer.prototype.update = function () {
  43926. if (this.autoUpdateBonesMatrices) {
  43927. this._updateBoneMatrix(this.skeleton.bones[0]);
  43928. }
  43929. if (this.skeleton.bones[0].length === undefined) {
  43930. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43931. }
  43932. else {
  43933. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43934. }
  43935. if (!this._debugMesh) {
  43936. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  43937. this._debugMesh.renderingGroupId = this.renderingGroupId;
  43938. }
  43939. else {
  43940. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  43941. }
  43942. this._debugMesh.color = this.color;
  43943. };
  43944. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  43945. if (bone.getParent()) {
  43946. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  43947. }
  43948. var children = bone.children;
  43949. var len = children.length;
  43950. for (var i = 0; i < len; i++) {
  43951. this._updateBoneMatrix(children[i]);
  43952. }
  43953. };
  43954. SkeletonViewer.prototype.dispose = function () {
  43955. if (this._debugMesh) {
  43956. this.isEnabled = false;
  43957. this._debugMesh.dispose();
  43958. this._debugMesh = null;
  43959. }
  43960. };
  43961. return SkeletonViewer;
  43962. }());
  43963. Debug.SkeletonViewer = SkeletonViewer;
  43964. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43965. })(BABYLON || (BABYLON = {}));
  43966. var BABYLON;
  43967. (function (BABYLON) {
  43968. var maxSimultaneousLights = 4;
  43969. var PBRMaterialDefines = (function (_super) {
  43970. __extends(PBRMaterialDefines, _super);
  43971. function PBRMaterialDefines() {
  43972. _super.call(this);
  43973. this.ALBEDO = false;
  43974. this.AMBIENT = false;
  43975. this.OPACITY = false;
  43976. this.OPACITYRGB = false;
  43977. this.REFLECTION = false;
  43978. this.EMISSIVE = false;
  43979. this.REFLECTIVITY = false;
  43980. this.BUMP = false;
  43981. this.PARALLAX = false;
  43982. this.PARALLAXOCCLUSION = false;
  43983. this.SPECULAROVERALPHA = false;
  43984. this.CLIPPLANE = false;
  43985. this.ALPHATEST = false;
  43986. this.ALPHAFROMALBEDO = false;
  43987. this.POINTSIZE = false;
  43988. this.FOG = false;
  43989. this.LIGHT0 = false;
  43990. this.LIGHT1 = false;
  43991. this.LIGHT2 = false;
  43992. this.LIGHT3 = false;
  43993. this.SPOTLIGHT0 = false;
  43994. this.SPOTLIGHT1 = false;
  43995. this.SPOTLIGHT2 = false;
  43996. this.SPOTLIGHT3 = false;
  43997. this.HEMILIGHT0 = false;
  43998. this.HEMILIGHT1 = false;
  43999. this.HEMILIGHT2 = false;
  44000. this.HEMILIGHT3 = false;
  44001. this.POINTLIGHT0 = false;
  44002. this.POINTLIGHT1 = false;
  44003. this.POINTLIGHT2 = false;
  44004. this.POINTLIGHT3 = false;
  44005. this.DIRLIGHT0 = false;
  44006. this.DIRLIGHT1 = false;
  44007. this.DIRLIGHT2 = false;
  44008. this.DIRLIGHT3 = false;
  44009. this.SPECULARTERM = false;
  44010. this.SHADOW0 = false;
  44011. this.SHADOW1 = false;
  44012. this.SHADOW2 = false;
  44013. this.SHADOW3 = false;
  44014. this.SHADOWS = false;
  44015. this.SHADOWVSM0 = false;
  44016. this.SHADOWVSM1 = false;
  44017. this.SHADOWVSM2 = false;
  44018. this.SHADOWVSM3 = false;
  44019. this.SHADOWPCF0 = false;
  44020. this.SHADOWPCF1 = false;
  44021. this.SHADOWPCF2 = false;
  44022. this.SHADOWPCF3 = false;
  44023. this.OPACITYFRESNEL = false;
  44024. this.EMISSIVEFRESNEL = false;
  44025. this.FRESNEL = false;
  44026. this.NORMAL = false;
  44027. this.UV1 = false;
  44028. this.UV2 = false;
  44029. this.VERTEXCOLOR = false;
  44030. this.VERTEXALPHA = false;
  44031. this.NUM_BONE_INFLUENCERS = 0;
  44032. this.BonesPerMesh = 0;
  44033. this.INSTANCES = false;
  44034. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44035. this.MICROSURFACEAUTOMATIC = false;
  44036. this.EMISSIVEASILLUMINATION = false;
  44037. this.LINKEMISSIVEWITHALBEDO = false;
  44038. this.LIGHTMAP = false;
  44039. this.USELIGHTMAPASSHADOWMAP = false;
  44040. this.REFLECTIONMAP_3D = false;
  44041. this.REFLECTIONMAP_SPHERICAL = false;
  44042. this.REFLECTIONMAP_PLANAR = false;
  44043. this.REFLECTIONMAP_CUBIC = false;
  44044. this.REFLECTIONMAP_PROJECTION = false;
  44045. this.REFLECTIONMAP_SKYBOX = false;
  44046. this.REFLECTIONMAP_EXPLICIT = false;
  44047. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44048. this.INVERTCUBICMAP = false;
  44049. this.LOGARITHMICDEPTH = false;
  44050. this.CAMERATONEMAP = false;
  44051. this.CAMERACONTRAST = false;
  44052. this.OVERLOADEDVALUES = false;
  44053. this.OVERLOADEDSHADOWVALUES = false;
  44054. this.USESPHERICALFROMREFLECTIONMAP = false;
  44055. this.REFRACTION = false;
  44056. this.REFRACTIONMAP_3D = false;
  44057. this.LINKREFRACTIONTOTRANSPARENCY = false;
  44058. this.REFRACTIONMAPINLINEARSPACE = false;
  44059. this.LODBASEDMICROSFURACE = false;
  44060. this.USEPHYSICALLIGHTFALLOFF = false;
  44061. this.RADIANCEOVERALPHA = false;
  44062. this.USEPMREMREFLECTION = false;
  44063. this.USEPMREMREFRACTION = false;
  44064. this._keys = Object.keys(this);
  44065. }
  44066. return PBRMaterialDefines;
  44067. }(BABYLON.MaterialDefines));
  44068. /**
  44069. * The Physically based material of BJS.
  44070. *
  44071. * This offers the main features of a standard PBR material.
  44072. * For more information, please refer to the documentation :
  44073. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44074. */
  44075. var PBRMaterial = (function (_super) {
  44076. __extends(PBRMaterial, _super);
  44077. /**
  44078. * Instantiates a new PBRMaterial instance.
  44079. *
  44080. * @param name The material name
  44081. * @param scene The scene the material will be use in.
  44082. */
  44083. function PBRMaterial(name, scene) {
  44084. var _this = this;
  44085. _super.call(this, name, scene);
  44086. /**
  44087. * Intensity of the direct lights e.g. the four lights available in your scene.
  44088. * This impacts both the direct diffuse and specular highlights.
  44089. */
  44090. this.directIntensity = 1.0;
  44091. /**
  44092. * Intensity of the emissive part of the material.
  44093. * This helps controlling the emissive effect without modifying the emissive color.
  44094. */
  44095. this.emissiveIntensity = 1.0;
  44096. /**
  44097. * Intensity of the environment e.g. how much the environment will light the object
  44098. * either through harmonics for rough material or through the refelction for shiny ones.
  44099. */
  44100. this.environmentIntensity = 1.0;
  44101. /**
  44102. * This is a special control allowing the reduction of the specular highlights coming from the
  44103. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44104. */
  44105. this.specularIntensity = 1.0;
  44106. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  44107. /**
  44108. * Debug Control allowing disabling the bump map on this material.
  44109. */
  44110. this.disableBumpMap = false;
  44111. /**
  44112. * Debug Control helping enforcing or dropping the darkness of shadows.
  44113. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  44114. */
  44115. this.overloadedShadowIntensity = 1.0;
  44116. /**
  44117. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  44118. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  44119. */
  44120. this.overloadedShadeIntensity = 1.0;
  44121. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  44122. /**
  44123. * The camera exposure used on this material.
  44124. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44125. * This corresponds to a photographic exposure.
  44126. */
  44127. this.cameraExposure = 1.0;
  44128. /**
  44129. * The camera contrast used on this material.
  44130. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  44131. */
  44132. this.cameraContrast = 1.0;
  44133. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  44134. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  44135. /**
  44136. * Debug Control allowing to overload the ambient color.
  44137. * This as to be use with the overloadedAmbientIntensity parameter.
  44138. */
  44139. this.overloadedAmbient = BABYLON.Color3.White();
  44140. /**
  44141. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  44142. */
  44143. this.overloadedAmbientIntensity = 0.0;
  44144. /**
  44145. * Debug Control allowing to overload the albedo color.
  44146. * This as to be use with the overloadedAlbedoIntensity parameter.
  44147. */
  44148. this.overloadedAlbedo = BABYLON.Color3.White();
  44149. /**
  44150. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  44151. */
  44152. this.overloadedAlbedoIntensity = 0.0;
  44153. /**
  44154. * Debug Control allowing to overload the reflectivity color.
  44155. * This as to be use with the overloadedReflectivityIntensity parameter.
  44156. */
  44157. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  44158. /**
  44159. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  44160. */
  44161. this.overloadedReflectivityIntensity = 0.0;
  44162. /**
  44163. * Debug Control allowing to overload the emissive color.
  44164. * This as to be use with the overloadedEmissiveIntensity parameter.
  44165. */
  44166. this.overloadedEmissive = BABYLON.Color3.White();
  44167. /**
  44168. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  44169. */
  44170. this.overloadedEmissiveIntensity = 0.0;
  44171. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  44172. /**
  44173. * Debug Control allowing to overload the reflection color.
  44174. * This as to be use with the overloadedReflectionIntensity parameter.
  44175. */
  44176. this.overloadedReflection = BABYLON.Color3.White();
  44177. /**
  44178. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  44179. */
  44180. this.overloadedReflectionIntensity = 0.0;
  44181. /**
  44182. * Debug Control allowing to overload the microsurface.
  44183. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  44184. */
  44185. this.overloadedMicroSurface = 0.0;
  44186. /**
  44187. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  44188. */
  44189. this.overloadedMicroSurfaceIntensity = 0.0;
  44190. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  44191. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44192. /**
  44193. * AKA Diffuse Color in other nomenclature.
  44194. */
  44195. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44196. /**
  44197. * AKA Specular Color in other nomenclature.
  44198. */
  44199. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44200. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  44201. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44202. /**
  44203. * AKA Glossiness in other nomenclature.
  44204. */
  44205. this.microSurface = 0.9;
  44206. /**
  44207. * source material index of refraction (IOR)' / 'destination material IOR.
  44208. */
  44209. this.indexOfRefraction = 0.66;
  44210. /**
  44211. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44212. */
  44213. this.invertRefractionY = false;
  44214. /**
  44215. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44216. * Materials half opaque for instance using refraction could benefit from this control.
  44217. */
  44218. this.linkRefractionWithTransparency = false;
  44219. /**
  44220. * The emissive and albedo are linked to never be more than one (Energy conservation).
  44221. */
  44222. this.linkEmissiveWithAlbedo = false;
  44223. this.useLightmapAsShadowmap = false;
  44224. /**
  44225. * In this mode, the emissive informtaion will always be added to the lighting once.
  44226. * A light for instance can be thought as emissive.
  44227. */
  44228. this.useEmissiveAsIllumination = false;
  44229. /**
  44230. * Secifies that the alpha is coming form the albedo channel alpha channel.
  44231. */
  44232. this.useAlphaFromAlbedoTexture = false;
  44233. /**
  44234. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44235. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44236. */
  44237. this.useSpecularOverAlpha = true;
  44238. /**
  44239. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44240. */
  44241. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44242. /**
  44243. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44244. * The material will try to infer what glossiness each pixel should be.
  44245. */
  44246. this.useAutoMicroSurfaceFromReflectivityMap = false;
  44247. /**
  44248. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  44249. * the creation of the material.
  44250. */
  44251. this.useScalarInLinearSpace = false;
  44252. /**
  44253. * BJS is using an harcoded light falloff based on a manually sets up range.
  44254. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44255. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44256. */
  44257. this.usePhysicalLightFalloff = true;
  44258. /**
  44259. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44260. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44261. */
  44262. this.useRadianceOverAlpha = true;
  44263. /**
  44264. * Allows using the bump map in parallax mode.
  44265. */
  44266. this.useParallax = false;
  44267. /**
  44268. * Allows using the bump map in parallax occlusion mode.
  44269. */
  44270. this.useParallaxOcclusion = false;
  44271. /**
  44272. * Controls the scale bias of the parallax mode.
  44273. */
  44274. this.parallaxScaleBias = 0.05;
  44275. this.disableLighting = false;
  44276. this._renderTargets = new BABYLON.SmartArray(16);
  44277. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44278. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44279. this._tempColor = new BABYLON.Color3();
  44280. this._defines = new PBRMaterialDefines();
  44281. this._cachedDefines = new PBRMaterialDefines();
  44282. this._myScene = null;
  44283. this._myShadowGenerator = null;
  44284. this._cachedDefines.BonesPerMesh = -1;
  44285. this.getRenderTargetTextures = function () {
  44286. _this._renderTargets.reset();
  44287. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  44288. _this._renderTargets.push(_this.reflectionTexture);
  44289. }
  44290. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  44291. _this._renderTargets.push(_this.refractionTexture);
  44292. }
  44293. return _this._renderTargets;
  44294. };
  44295. }
  44296. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  44297. get: function () {
  44298. return this._useLogarithmicDepth;
  44299. },
  44300. set: function (value) {
  44301. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44302. },
  44303. enumerable: true,
  44304. configurable: true
  44305. });
  44306. PBRMaterial.prototype.needAlphaBlending = function () {
  44307. if (this.linkRefractionWithTransparency) {
  44308. return false;
  44309. }
  44310. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  44311. };
  44312. PBRMaterial.prototype.needAlphaTesting = function () {
  44313. if (this.linkRefractionWithTransparency) {
  44314. return false;
  44315. }
  44316. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  44317. };
  44318. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44319. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  44320. };
  44321. PBRMaterial.prototype.getAlphaTestTexture = function () {
  44322. return this.albedoTexture;
  44323. };
  44324. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44325. if (!mesh) {
  44326. return true;
  44327. }
  44328. if (this._defines.INSTANCES !== useInstances) {
  44329. return false;
  44330. }
  44331. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  44332. return true;
  44333. }
  44334. return false;
  44335. };
  44336. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  44337. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  44338. };
  44339. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  44340. if (!useScalarInLinear) {
  44341. color.toLinearSpaceToRef(ref);
  44342. }
  44343. else {
  44344. ref.r = color.r;
  44345. ref.g = color.g;
  44346. ref.b = color.b;
  44347. }
  44348. };
  44349. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  44350. var lightIndex = 0;
  44351. var depthValuesAlreadySet = false;
  44352. for (var index = 0; index < scene.lights.length; index++) {
  44353. var light = scene.lights[index];
  44354. if (!light.isEnabled()) {
  44355. continue;
  44356. }
  44357. if (!light.canAffectMesh(mesh)) {
  44358. continue;
  44359. }
  44360. this._lightRadiuses[lightIndex] = light.radius;
  44361. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  44362. // GAMMA CORRECTION.
  44363. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  44364. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  44365. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  44366. if (defines["SPECULARTERM"]) {
  44367. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  44368. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  44369. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  44370. }
  44371. // Shadows
  44372. if (scene.shadowsEnabled) {
  44373. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  44374. }
  44375. lightIndex++;
  44376. if (lightIndex === maxSimultaneousLights)
  44377. break;
  44378. }
  44379. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  44380. };
  44381. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  44382. if (this.checkReadyOnlyOnce) {
  44383. if (this._wasPreviouslyReady) {
  44384. return true;
  44385. }
  44386. }
  44387. var scene = this.getScene();
  44388. if (!this.checkReadyOnEveryCall) {
  44389. if (this._renderId === scene.getRenderId()) {
  44390. if (this._checkCache(scene, mesh, useInstances)) {
  44391. return true;
  44392. }
  44393. }
  44394. }
  44395. var engine = scene.getEngine();
  44396. var needNormals = false;
  44397. var needUVs = false;
  44398. this._defines.reset();
  44399. if (scene.texturesEnabled) {
  44400. // Textures
  44401. if (scene.texturesEnabled) {
  44402. if (scene.getEngine().getCaps().textureLOD) {
  44403. this._defines.LODBASEDMICROSFURACE = true;
  44404. }
  44405. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44406. if (!this.albedoTexture.isReady()) {
  44407. return false;
  44408. }
  44409. else {
  44410. needUVs = true;
  44411. this._defines.ALBEDO = true;
  44412. }
  44413. }
  44414. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44415. if (!this.ambientTexture.isReady()) {
  44416. return false;
  44417. }
  44418. else {
  44419. needUVs = true;
  44420. this._defines.AMBIENT = true;
  44421. }
  44422. }
  44423. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44424. if (!this.opacityTexture.isReady()) {
  44425. return false;
  44426. }
  44427. else {
  44428. needUVs = true;
  44429. this._defines.OPACITY = true;
  44430. if (this.opacityTexture.getAlphaFromRGB) {
  44431. this._defines.OPACITYRGB = true;
  44432. }
  44433. }
  44434. }
  44435. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44436. if (!this.reflectionTexture.isReady()) {
  44437. return false;
  44438. }
  44439. else {
  44440. needNormals = true;
  44441. this._defines.REFLECTION = true;
  44442. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44443. this._defines.INVERTCUBICMAP = true;
  44444. }
  44445. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  44446. switch (this.reflectionTexture.coordinatesMode) {
  44447. case BABYLON.Texture.CUBIC_MODE:
  44448. case BABYLON.Texture.INVCUBIC_MODE:
  44449. this._defines.REFLECTIONMAP_CUBIC = true;
  44450. break;
  44451. case BABYLON.Texture.EXPLICIT_MODE:
  44452. this._defines.REFLECTIONMAP_EXPLICIT = true;
  44453. break;
  44454. case BABYLON.Texture.PLANAR_MODE:
  44455. this._defines.REFLECTIONMAP_PLANAR = true;
  44456. break;
  44457. case BABYLON.Texture.PROJECTION_MODE:
  44458. this._defines.REFLECTIONMAP_PROJECTION = true;
  44459. break;
  44460. case BABYLON.Texture.SKYBOX_MODE:
  44461. this._defines.REFLECTIONMAP_SKYBOX = true;
  44462. break;
  44463. case BABYLON.Texture.SPHERICAL_MODE:
  44464. this._defines.REFLECTIONMAP_SPHERICAL = true;
  44465. break;
  44466. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44467. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44468. break;
  44469. }
  44470. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  44471. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  44472. needNormals = true;
  44473. if (this.reflectionTexture.isPMREM) {
  44474. this._defines.USEPMREMREFLECTION = true;
  44475. }
  44476. }
  44477. }
  44478. }
  44479. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44480. if (!this.lightmapTexture.isReady()) {
  44481. return false;
  44482. }
  44483. else {
  44484. needUVs = true;
  44485. this._defines.LIGHTMAP = true;
  44486. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  44487. }
  44488. }
  44489. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44490. if (!this.emissiveTexture.isReady()) {
  44491. return false;
  44492. }
  44493. else {
  44494. needUVs = true;
  44495. this._defines.EMISSIVE = true;
  44496. }
  44497. }
  44498. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44499. if (!this.reflectivityTexture.isReady()) {
  44500. return false;
  44501. }
  44502. else {
  44503. needUVs = true;
  44504. this._defines.REFLECTIVITY = true;
  44505. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  44506. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  44507. }
  44508. }
  44509. }
  44510. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44511. if (!this.bumpTexture.isReady()) {
  44512. return false;
  44513. }
  44514. else {
  44515. needUVs = true;
  44516. this._defines.BUMP = true;
  44517. if (this.useParallax) {
  44518. this._defines.PARALLAX = true;
  44519. if (this.useParallaxOcclusion) {
  44520. this._defines.PARALLAXOCCLUSION = true;
  44521. }
  44522. }
  44523. }
  44524. }
  44525. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44526. if (!this.refractionTexture.isReady()) {
  44527. return false;
  44528. }
  44529. else {
  44530. needUVs = true;
  44531. this._defines.REFRACTION = true;
  44532. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  44533. if (this.linkRefractionWithTransparency) {
  44534. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44535. }
  44536. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  44537. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  44538. if (this.refractionTexture.isPMREM) {
  44539. this._defines.USEPMREMREFRACTION = true;
  44540. }
  44541. }
  44542. }
  44543. }
  44544. }
  44545. // Effect
  44546. if (scene.clipPlane) {
  44547. this._defines.CLIPPLANE = true;
  44548. }
  44549. if (engine.getAlphaTesting()) {
  44550. this._defines.ALPHATEST = true;
  44551. }
  44552. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44553. this._defines.ALPHAFROMALBEDO = true;
  44554. }
  44555. if (this.useEmissiveAsIllumination) {
  44556. this._defines.EMISSIVEASILLUMINATION = true;
  44557. }
  44558. if (this.linkEmissiveWithAlbedo) {
  44559. this._defines.LINKEMISSIVEWITHALBEDO = true;
  44560. }
  44561. if (this.useLogarithmicDepth) {
  44562. this._defines.LOGARITHMICDEPTH = true;
  44563. }
  44564. if (this.cameraContrast != 1) {
  44565. this._defines.CAMERACONTRAST = true;
  44566. }
  44567. if (this.cameraExposure != 1) {
  44568. this._defines.CAMERATONEMAP = true;
  44569. }
  44570. if (this.overloadedShadeIntensity != 1 ||
  44571. this.overloadedShadowIntensity != 1) {
  44572. this._defines.OVERLOADEDSHADOWVALUES = true;
  44573. }
  44574. if (this.overloadedMicroSurfaceIntensity > 0 ||
  44575. this.overloadedEmissiveIntensity > 0 ||
  44576. this.overloadedReflectivityIntensity > 0 ||
  44577. this.overloadedAlbedoIntensity > 0 ||
  44578. this.overloadedAmbientIntensity > 0 ||
  44579. this.overloadedReflectionIntensity > 0) {
  44580. this._defines.OVERLOADEDVALUES = true;
  44581. }
  44582. // Point size
  44583. if (this.pointsCloud || scene.forcePointsCloud) {
  44584. this._defines.POINTSIZE = true;
  44585. }
  44586. // Fog
  44587. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44588. this._defines.FOG = true;
  44589. }
  44590. if (scene.lightsEnabled && !this.disableLighting) {
  44591. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  44592. }
  44593. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44594. // Fresnel
  44595. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  44596. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44597. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44598. this._defines.OPACITYFRESNEL = true;
  44599. }
  44600. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44601. this._defines.EMISSIVEFRESNEL = true;
  44602. }
  44603. needNormals = true;
  44604. this._defines.FRESNEL = true;
  44605. }
  44606. }
  44607. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  44608. this._defines.SPECULAROVERALPHA = true;
  44609. }
  44610. if (this.usePhysicalLightFalloff) {
  44611. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  44612. }
  44613. if (this.useRadianceOverAlpha) {
  44614. this._defines.RADIANCEOVERALPHA = true;
  44615. }
  44616. // Attribs
  44617. if (mesh) {
  44618. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44619. this._defines.NORMAL = true;
  44620. }
  44621. if (needUVs) {
  44622. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44623. this._defines.UV1 = true;
  44624. }
  44625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44626. this._defines.UV2 = true;
  44627. }
  44628. }
  44629. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  44630. this._defines.VERTEXCOLOR = true;
  44631. if (mesh.hasVertexAlpha) {
  44632. this._defines.VERTEXALPHA = true;
  44633. }
  44634. }
  44635. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44636. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  44637. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  44638. }
  44639. // Instances
  44640. if (useInstances) {
  44641. this._defines.INSTANCES = true;
  44642. }
  44643. }
  44644. // Get correct effect
  44645. if (!this._defines.isEqual(this._cachedDefines)) {
  44646. this._defines.cloneTo(this._cachedDefines);
  44647. scene.resetCachedMaterial();
  44648. // Fallbacks
  44649. var fallbacks = new BABYLON.EffectFallbacks();
  44650. if (this._defines.REFLECTION) {
  44651. fallbacks.addFallback(0, "REFLECTION");
  44652. }
  44653. if (this._defines.REFRACTION) {
  44654. fallbacks.addFallback(0, "REFRACTION");
  44655. }
  44656. if (this._defines.REFLECTIVITY) {
  44657. fallbacks.addFallback(0, "REFLECTIVITY");
  44658. }
  44659. if (this._defines.BUMP) {
  44660. fallbacks.addFallback(0, "BUMP");
  44661. }
  44662. if (this._defines.PARALLAX) {
  44663. fallbacks.addFallback(1, "PARALLAX");
  44664. }
  44665. if (this._defines.PARALLAXOCCLUSION) {
  44666. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44667. }
  44668. if (this._defines.SPECULAROVERALPHA) {
  44669. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44670. }
  44671. if (this._defines.FOG) {
  44672. fallbacks.addFallback(1, "FOG");
  44673. }
  44674. if (this._defines.POINTSIZE) {
  44675. fallbacks.addFallback(0, "POINTSIZE");
  44676. }
  44677. if (this._defines.LOGARITHMICDEPTH) {
  44678. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44679. }
  44680. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  44681. if (this._defines.SPECULARTERM) {
  44682. fallbacks.addFallback(0, "SPECULARTERM");
  44683. }
  44684. if (this._defines.OPACITYFRESNEL) {
  44685. fallbacks.addFallback(1, "OPACITYFRESNEL");
  44686. }
  44687. if (this._defines.EMISSIVEFRESNEL) {
  44688. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  44689. }
  44690. if (this._defines.FRESNEL) {
  44691. fallbacks.addFallback(3, "FRESNEL");
  44692. }
  44693. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  44694. fallbacks.addCPUSkinningFallback(0, mesh);
  44695. }
  44696. //Attributes
  44697. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44698. if (this._defines.NORMAL) {
  44699. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44700. }
  44701. if (this._defines.UV1) {
  44702. attribs.push(BABYLON.VertexBuffer.UVKind);
  44703. }
  44704. if (this._defines.UV2) {
  44705. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44706. }
  44707. if (this._defines.VERTEXCOLOR) {
  44708. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44709. }
  44710. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  44711. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  44712. // Legacy browser patch
  44713. var shaderName = "pbr";
  44714. if (!scene.getEngine().getCaps().standardDerivatives) {
  44715. shaderName = "legacypbr";
  44716. }
  44717. var join = this._defines.toString();
  44718. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44719. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  44720. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  44721. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  44722. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  44723. "vFogInfos", "vFogColor", "pointSize",
  44724. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44725. "mBones",
  44726. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44727. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  44728. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  44729. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  44730. "logarithmicDepthConstant",
  44731. "vSphericalX", "vSphericalY", "vSphericalZ",
  44732. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44733. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44734. "vMicrosurfaceTextureLods", "vLightRadiuses"
  44735. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  44736. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  44737. ], join, fallbacks, this.onCompiled, this.onError);
  44738. }
  44739. if (!this._effect.isReady()) {
  44740. return false;
  44741. }
  44742. this._renderId = scene.getRenderId();
  44743. this._wasPreviouslyReady = true;
  44744. if (mesh) {
  44745. if (!mesh._materialDefines) {
  44746. mesh._materialDefines = new PBRMaterialDefines();
  44747. }
  44748. this._defines.cloneTo(mesh._materialDefines);
  44749. }
  44750. return true;
  44751. };
  44752. PBRMaterial.prototype.unbind = function () {
  44753. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  44754. this._effect.setTexture("reflection2DSampler", null);
  44755. }
  44756. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  44757. this._effect.setTexture("refraction2DSampler", null);
  44758. }
  44759. _super.prototype.unbind.call(this);
  44760. };
  44761. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  44762. this._effect.setMatrix("world", world);
  44763. };
  44764. PBRMaterial.prototype.bind = function (world, mesh) {
  44765. this._myScene = this.getScene();
  44766. // Matrices
  44767. this.bindOnlyWorldMatrix(world);
  44768. // Bones
  44769. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  44770. if (this._myScene.getCachedMaterial() !== this) {
  44771. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  44772. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44773. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44774. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44775. }
  44776. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44777. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44778. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44779. }
  44780. }
  44781. // Textures
  44782. if (this._myScene.texturesEnabled) {
  44783. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44784. this._effect.setTexture("albedoSampler", this.albedoTexture);
  44785. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  44786. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  44787. }
  44788. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44789. this._effect.setTexture("ambientSampler", this.ambientTexture);
  44790. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  44791. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  44792. }
  44793. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44794. this._effect.setTexture("opacitySampler", this.opacityTexture);
  44795. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  44796. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  44797. }
  44798. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44799. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  44800. if (this.reflectionTexture.isCube) {
  44801. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  44802. }
  44803. else {
  44804. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  44805. }
  44806. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  44807. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  44808. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  44809. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  44810. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  44811. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  44812. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  44813. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  44814. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  44815. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  44816. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  44817. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  44818. }
  44819. }
  44820. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44821. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  44822. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  44823. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  44824. }
  44825. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44826. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  44827. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  44828. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  44829. }
  44830. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44831. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  44832. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  44833. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  44834. }
  44835. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44836. this._effect.setTexture("bumpSampler", this.bumpTexture);
  44837. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  44838. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  44839. }
  44840. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44841. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  44842. var depth = 1.0;
  44843. if (this.refractionTexture.isCube) {
  44844. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  44845. }
  44846. else {
  44847. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  44848. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  44849. if (this.refractionTexture.depth) {
  44850. depth = this.refractionTexture.depth;
  44851. }
  44852. }
  44853. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44854. }
  44855. if ((this.reflectionTexture || this.refractionTexture)) {
  44856. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  44857. }
  44858. }
  44859. // Clip plane
  44860. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  44861. // Point size
  44862. if (this.pointsCloud) {
  44863. this._effect.setFloat("pointSize", this.pointSize);
  44864. }
  44865. // Colors
  44866. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44867. // GAMMA CORRECTION.
  44868. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  44869. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  44870. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44871. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  44872. // GAMMA CORRECTION.
  44873. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  44874. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  44875. // GAMMA CORRECTION.
  44876. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  44877. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  44878. }
  44879. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  44880. // GAMMA CORRECTION.
  44881. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  44882. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  44883. // Lights
  44884. if (this._myScene.lightsEnabled && !this.disableLighting) {
  44885. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  44886. }
  44887. // View
  44888. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  44889. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  44890. }
  44891. // Fog
  44892. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  44893. this._lightingInfos.x = this.directIntensity;
  44894. this._lightingInfos.y = this.emissiveIntensity;
  44895. this._lightingInfos.z = this.environmentIntensity;
  44896. this._lightingInfos.w = this.specularIntensity;
  44897. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  44898. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  44899. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  44900. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  44901. this._cameraInfos.x = this.cameraExposure;
  44902. this._cameraInfos.y = this.cameraContrast;
  44903. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  44904. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  44905. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  44906. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  44907. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  44908. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  44909. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  44910. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  44911. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  44912. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  44913. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  44914. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  44915. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  44916. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  44917. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  44918. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  44919. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  44920. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  44921. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  44922. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  44923. // Log. depth
  44924. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  44925. }
  44926. _super.prototype.bind.call(this, world, mesh);
  44927. this._myScene = null;
  44928. };
  44929. PBRMaterial.prototype.getAnimatables = function () {
  44930. var results = [];
  44931. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  44932. results.push(this.albedoTexture);
  44933. }
  44934. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  44935. results.push(this.ambientTexture);
  44936. }
  44937. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  44938. results.push(this.opacityTexture);
  44939. }
  44940. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  44941. results.push(this.reflectionTexture);
  44942. }
  44943. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  44944. results.push(this.emissiveTexture);
  44945. }
  44946. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  44947. results.push(this.reflectivityTexture);
  44948. }
  44949. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  44950. results.push(this.bumpTexture);
  44951. }
  44952. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  44953. results.push(this.lightmapTexture);
  44954. }
  44955. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  44956. results.push(this.refractionTexture);
  44957. }
  44958. return results;
  44959. };
  44960. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  44961. if (this.albedoTexture) {
  44962. this.albedoTexture.dispose();
  44963. }
  44964. if (this.ambientTexture) {
  44965. this.ambientTexture.dispose();
  44966. }
  44967. if (this.opacityTexture) {
  44968. this.opacityTexture.dispose();
  44969. }
  44970. if (this.reflectionTexture) {
  44971. this.reflectionTexture.dispose();
  44972. }
  44973. if (this.emissiveTexture) {
  44974. this.emissiveTexture.dispose();
  44975. }
  44976. if (this.reflectivityTexture) {
  44977. this.reflectivityTexture.dispose();
  44978. }
  44979. if (this.bumpTexture) {
  44980. this.bumpTexture.dispose();
  44981. }
  44982. if (this.lightmapTexture) {
  44983. this.lightmapTexture.dispose();
  44984. }
  44985. if (this.refractionTexture) {
  44986. this.refractionTexture.dispose();
  44987. }
  44988. _super.prototype.dispose.call(this, forceDisposeEffect);
  44989. };
  44990. PBRMaterial.prototype.clone = function (name) {
  44991. var _this = this;
  44992. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  44993. };
  44994. PBRMaterial.prototype.serialize = function () {
  44995. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44996. serializationObject.customType = "BABYLON.PBRMaterial";
  44997. return serializationObject;
  44998. };
  44999. // Statics
  45000. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45001. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45002. };
  45003. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  45004. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  45005. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  45006. PBRMaterial._scaledReflection = new BABYLON.Color3();
  45007. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  45008. __decorate([
  45009. BABYLON.serialize()
  45010. ], PBRMaterial.prototype, "directIntensity", void 0);
  45011. __decorate([
  45012. BABYLON.serialize()
  45013. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45014. __decorate([
  45015. BABYLON.serialize()
  45016. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45017. __decorate([
  45018. BABYLON.serialize()
  45019. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45020. __decorate([
  45021. BABYLON.serialize()
  45022. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45023. __decorate([
  45024. BABYLON.serialize()
  45025. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  45026. __decorate([
  45027. BABYLON.serialize()
  45028. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  45029. __decorate([
  45030. BABYLON.serialize()
  45031. ], PBRMaterial.prototype, "cameraExposure", void 0);
  45032. __decorate([
  45033. BABYLON.serialize()
  45034. ], PBRMaterial.prototype, "cameraContrast", void 0);
  45035. __decorate([
  45036. BABYLON.serializeAsColor3()
  45037. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  45038. __decorate([
  45039. BABYLON.serialize()
  45040. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  45041. __decorate([
  45042. BABYLON.serializeAsColor3()
  45043. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  45044. __decorate([
  45045. BABYLON.serialize()
  45046. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  45047. __decorate([
  45048. BABYLON.serializeAsColor3()
  45049. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  45050. __decorate([
  45051. BABYLON.serialize()
  45052. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  45053. __decorate([
  45054. BABYLON.serializeAsColor3()
  45055. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  45056. __decorate([
  45057. BABYLON.serialize()
  45058. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  45059. __decorate([
  45060. BABYLON.serializeAsColor3()
  45061. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  45062. __decorate([
  45063. BABYLON.serialize()
  45064. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  45065. __decorate([
  45066. BABYLON.serialize()
  45067. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  45068. __decorate([
  45069. BABYLON.serialize()
  45070. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  45071. __decorate([
  45072. BABYLON.serializeAsTexture()
  45073. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45074. __decorate([
  45075. BABYLON.serializeAsTexture()
  45076. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45077. __decorate([
  45078. BABYLON.serializeAsTexture()
  45079. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45080. __decorate([
  45081. BABYLON.serializeAsTexture()
  45082. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45083. __decorate([
  45084. BABYLON.serializeAsTexture()
  45085. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45086. __decorate([
  45087. BABYLON.serializeAsTexture()
  45088. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45089. __decorate([
  45090. BABYLON.serializeAsTexture()
  45091. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45092. __decorate([
  45093. BABYLON.serializeAsTexture()
  45094. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45095. __decorate([
  45096. BABYLON.serializeAsTexture()
  45097. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45098. __decorate([
  45099. BABYLON.serializeAsColor3("ambient")
  45100. ], PBRMaterial.prototype, "ambientColor", void 0);
  45101. __decorate([
  45102. BABYLON.serializeAsColor3("albedo")
  45103. ], PBRMaterial.prototype, "albedoColor", void 0);
  45104. __decorate([
  45105. BABYLON.serializeAsColor3("reflectivity")
  45106. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45107. __decorate([
  45108. BABYLON.serializeAsColor3("reflection")
  45109. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45110. __decorate([
  45111. BABYLON.serializeAsColor3("emissivie")
  45112. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45113. __decorate([
  45114. BABYLON.serialize()
  45115. ], PBRMaterial.prototype, "microSurface", void 0);
  45116. __decorate([
  45117. BABYLON.serialize()
  45118. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45119. __decorate([
  45120. BABYLON.serialize()
  45121. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45122. __decorate([
  45123. BABYLON.serializeAsFresnelParameters()
  45124. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  45125. __decorate([
  45126. BABYLON.serializeAsFresnelParameters()
  45127. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  45128. __decorate([
  45129. BABYLON.serialize()
  45130. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45131. __decorate([
  45132. BABYLON.serialize()
  45133. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  45134. __decorate([
  45135. BABYLON.serialize()
  45136. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45137. __decorate([
  45138. BABYLON.serialize()
  45139. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45140. __decorate([
  45141. BABYLON.serialize()
  45142. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45143. __decorate([
  45144. BABYLON.serialize()
  45145. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45146. __decorate([
  45147. BABYLON.serialize()
  45148. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45149. __decorate([
  45150. BABYLON.serialize()
  45151. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45152. __decorate([
  45153. BABYLON.serialize()
  45154. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  45155. __decorate([
  45156. BABYLON.serialize()
  45157. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45158. __decorate([
  45159. BABYLON.serialize()
  45160. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45161. __decorate([
  45162. BABYLON.serialize()
  45163. ], PBRMaterial.prototype, "useParallax", void 0);
  45164. __decorate([
  45165. BABYLON.serialize()
  45166. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45167. __decorate([
  45168. BABYLON.serialize()
  45169. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45170. __decorate([
  45171. BABYLON.serialize()
  45172. ], PBRMaterial.prototype, "disableLighting", void 0);
  45173. __decorate([
  45174. BABYLON.serialize()
  45175. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  45176. return PBRMaterial;
  45177. }(BABYLON.Material));
  45178. BABYLON.PBRMaterial = PBRMaterial;
  45179. })(BABYLON || (BABYLON = {}));
  45180. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0 ,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0 ,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  45181. 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"};
  45182. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new h(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*F+s*P+e*I,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*F+z*P+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),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);\ni.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=a.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=u;var m=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  45183. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  45184. module.exports = BABYLON;
  45185. };