babylon.max.js 2.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870
  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. var Database = (function () {
  3078. function Database(urlToScene, callbackManifestChecked) {
  3079. // Handling various flavors of prefixed version of IndexedDB
  3080. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3081. this.callbackManifestChecked = callbackManifestChecked;
  3082. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3083. this.db = null;
  3084. this.enableSceneOffline = false;
  3085. this.enableTexturesOffline = false;
  3086. this.manifestVersionFound = 0;
  3087. this.mustUpdateRessources = false;
  3088. this.hasReachedQuota = false;
  3089. if (!Database.IDBStorageEnabled) {
  3090. this.callbackManifestChecked(true);
  3091. }
  3092. else {
  3093. this.checkManifestFile();
  3094. }
  3095. }
  3096. Database.prototype.checkManifestFile = function () {
  3097. var _this = this;
  3098. function noManifestFile() {
  3099. that.enableSceneOffline = false;
  3100. that.enableTexturesOffline = false;
  3101. that.callbackManifestChecked(false);
  3102. }
  3103. var that = this;
  3104. var timeStampUsed = false;
  3105. var manifestURL = this.currentSceneUrl + ".manifest";
  3106. var xhr = new XMLHttpRequest();
  3107. if (navigator.onLine) {
  3108. // Adding a timestamp to by-pass browsers' cache
  3109. timeStampUsed = true;
  3110. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3111. }
  3112. xhr.open("GET", manifestURL, true);
  3113. xhr.addEventListener("load", function () {
  3114. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3115. try {
  3116. var manifestFile = JSON.parse(xhr.response);
  3117. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3118. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3119. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3120. _this.manifestVersionFound = manifestFile.version;
  3121. }
  3122. if (_this.callbackManifestChecked) {
  3123. _this.callbackManifestChecked(true);
  3124. }
  3125. }
  3126. catch (ex) {
  3127. noManifestFile();
  3128. }
  3129. }
  3130. else {
  3131. noManifestFile();
  3132. }
  3133. }, false);
  3134. xhr.addEventListener("error", function (event) {
  3135. if (timeStampUsed) {
  3136. timeStampUsed = false;
  3137. // Let's retry without the timeStamp
  3138. // It could fail when coupled with HTML5 Offline API
  3139. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3140. xhr.open("GET", retryManifestURL, true);
  3141. xhr.send();
  3142. }
  3143. else {
  3144. noManifestFile();
  3145. }
  3146. }, false);
  3147. try {
  3148. xhr.send();
  3149. }
  3150. catch (ex) {
  3151. BABYLON.Tools.Error("Error on XHR send request.");
  3152. that.callbackManifestChecked(false);
  3153. }
  3154. };
  3155. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3156. var _this = this;
  3157. function handleError() {
  3158. that.isSupported = false;
  3159. if (errorCallback)
  3160. errorCallback();
  3161. }
  3162. var that = this;
  3163. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3164. // Your browser doesn't support IndexedDB
  3165. this.isSupported = false;
  3166. if (errorCallback)
  3167. errorCallback();
  3168. }
  3169. else {
  3170. // If the DB hasn't been opened or created yet
  3171. if (!this.db) {
  3172. this.hasReachedQuota = false;
  3173. this.isSupported = true;
  3174. var request = this.idbFactory.open("babylonjs", 1);
  3175. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3176. request.onerror = function (event) {
  3177. handleError();
  3178. };
  3179. // executes when a version change transaction cannot complete due to other active transactions
  3180. request.onblocked = function (event) {
  3181. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3182. handleError();
  3183. };
  3184. // DB has been opened successfully
  3185. request.onsuccess = function (event) {
  3186. _this.db = request.result;
  3187. successCallback();
  3188. };
  3189. // Initialization of the DB. Creating Scenes & Textures stores
  3190. request.onupgradeneeded = function (event) {
  3191. _this.db = (event.target).result;
  3192. try {
  3193. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3194. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3195. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3196. }
  3197. catch (ex) {
  3198. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3199. handleError();
  3200. }
  3201. };
  3202. }
  3203. else {
  3204. if (successCallback)
  3205. successCallback();
  3206. }
  3207. }
  3208. };
  3209. Database.prototype.loadImageFromDB = function (url, image) {
  3210. var _this = this;
  3211. var completeURL = Database.ReturnFullUrlLocation(url);
  3212. var saveAndLoadImage = function () {
  3213. if (!_this.hasReachedQuota && _this.db !== null) {
  3214. // the texture is not yet in the DB, let's try to save it
  3215. _this._saveImageIntoDBAsync(completeURL, image);
  3216. }
  3217. else {
  3218. image.src = url;
  3219. }
  3220. };
  3221. if (!this.mustUpdateRessources) {
  3222. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3223. }
  3224. else {
  3225. saveAndLoadImage();
  3226. }
  3227. };
  3228. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3229. if (this.isSupported && this.db !== null) {
  3230. var texture;
  3231. var transaction = this.db.transaction(["textures"]);
  3232. transaction.onabort = function (event) {
  3233. image.src = url;
  3234. };
  3235. transaction.oncomplete = function (event) {
  3236. var blobTextureURL;
  3237. if (texture) {
  3238. var URL = window.URL || window.webkitURL;
  3239. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3240. image.onerror = function () {
  3241. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3242. image.src = url;
  3243. };
  3244. image.src = blobTextureURL;
  3245. }
  3246. else {
  3247. notInDBCallback();
  3248. }
  3249. };
  3250. var getRequest = transaction.objectStore("textures").get(url);
  3251. getRequest.onsuccess = function (event) {
  3252. texture = (event.target).result;
  3253. };
  3254. getRequest.onerror = function (event) {
  3255. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3256. image.src = url;
  3257. };
  3258. }
  3259. else {
  3260. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3261. image.src = url;
  3262. }
  3263. };
  3264. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3265. var _this = this;
  3266. if (this.isSupported) {
  3267. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3268. var generateBlobUrl = function () {
  3269. var blobTextureURL;
  3270. if (blob) {
  3271. var URL = window.URL || window.webkitURL;
  3272. try {
  3273. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3274. }
  3275. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3276. catch (ex) {
  3277. blobTextureURL = URL.createObjectURL(blob);
  3278. }
  3279. }
  3280. image.src = blobTextureURL;
  3281. };
  3282. if (Database.IsUASupportingBlobStorage) {
  3283. var xhr = new XMLHttpRequest(), blob;
  3284. xhr.open("GET", url, true);
  3285. xhr.responseType = "blob";
  3286. xhr.addEventListener("load", function () {
  3287. if (xhr.status === 200) {
  3288. // Blob as response (XHR2)
  3289. blob = xhr.response;
  3290. var transaction = _this.db.transaction(["textures"], "readwrite");
  3291. // the transaction could abort because of a QuotaExceededError error
  3292. transaction.onabort = function (event) {
  3293. try {
  3294. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3295. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3296. this.hasReachedQuota = true;
  3297. }
  3298. }
  3299. catch (ex) { }
  3300. generateBlobUrl();
  3301. };
  3302. transaction.oncomplete = function (event) {
  3303. generateBlobUrl();
  3304. };
  3305. var newTexture = { textureUrl: url, data: blob };
  3306. try {
  3307. // Put the blob into the dabase
  3308. var addRequest = transaction.objectStore("textures").put(newTexture);
  3309. addRequest.onsuccess = function (event) {
  3310. };
  3311. addRequest.onerror = function (event) {
  3312. generateBlobUrl();
  3313. };
  3314. }
  3315. catch (ex) {
  3316. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3317. if (ex.code === 25) {
  3318. Database.IsUASupportingBlobStorage = false;
  3319. }
  3320. image.src = url;
  3321. }
  3322. }
  3323. else {
  3324. image.src = url;
  3325. }
  3326. }, false);
  3327. xhr.addEventListener("error", function (event) {
  3328. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3329. image.src = url;
  3330. }, false);
  3331. xhr.send();
  3332. }
  3333. else {
  3334. image.src = url;
  3335. }
  3336. }
  3337. else {
  3338. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3339. image.src = url;
  3340. }
  3341. };
  3342. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3343. var _this = this;
  3344. var updateVersion = function (event) {
  3345. // the version is not yet in the DB or we need to update it
  3346. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3347. };
  3348. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3349. };
  3350. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3351. var _this = this;
  3352. if (this.isSupported) {
  3353. var version;
  3354. try {
  3355. var transaction = this.db.transaction(["versions"]);
  3356. transaction.oncomplete = function (event) {
  3357. if (version) {
  3358. // If the version in the JSON file is > than the version in DB
  3359. if (_this.manifestVersionFound > version.data) {
  3360. _this.mustUpdateRessources = true;
  3361. updateInDBCallback();
  3362. }
  3363. else {
  3364. callback(version.data);
  3365. }
  3366. }
  3367. else {
  3368. _this.mustUpdateRessources = true;
  3369. updateInDBCallback();
  3370. }
  3371. };
  3372. transaction.onabort = function (event) {
  3373. callback(-1);
  3374. };
  3375. var getRequest = transaction.objectStore("versions").get(url);
  3376. getRequest.onsuccess = function (event) {
  3377. version = (event.target).result;
  3378. };
  3379. getRequest.onerror = function (event) {
  3380. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3381. callback(-1);
  3382. };
  3383. }
  3384. catch (ex) {
  3385. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3386. callback(-1);
  3387. }
  3388. }
  3389. else {
  3390. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3391. callback(-1);
  3392. }
  3393. };
  3394. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3395. var _this = this;
  3396. if (this.isSupported && !this.hasReachedQuota) {
  3397. try {
  3398. // Open a transaction to the database
  3399. var transaction = this.db.transaction(["versions"], "readwrite");
  3400. // the transaction could abort because of a QuotaExceededError error
  3401. transaction.onabort = function (event) {
  3402. try {
  3403. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3404. _this.hasReachedQuota = true;
  3405. }
  3406. }
  3407. catch (ex) { }
  3408. callback(-1);
  3409. };
  3410. transaction.oncomplete = function (event) {
  3411. callback(_this.manifestVersionFound);
  3412. };
  3413. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3414. // Put the scene into the database
  3415. var addRequest = transaction.objectStore("versions").put(newVersion);
  3416. addRequest.onsuccess = function (event) {
  3417. };
  3418. addRequest.onerror = function (event) {
  3419. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3420. };
  3421. }
  3422. catch (ex) {
  3423. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3424. callback(-1);
  3425. }
  3426. }
  3427. else {
  3428. callback(-1);
  3429. }
  3430. };
  3431. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3432. var _this = this;
  3433. var completeUrl = Database.ReturnFullUrlLocation(url);
  3434. var saveAndLoadFile = function (event) {
  3435. // the scene is not yet in the DB, let's try to save it
  3436. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3437. };
  3438. this._checkVersionFromDB(completeUrl, function (version) {
  3439. if (version !== -1) {
  3440. if (!_this.mustUpdateRessources) {
  3441. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3442. }
  3443. else {
  3444. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3445. }
  3446. }
  3447. else {
  3448. errorCallback();
  3449. }
  3450. });
  3451. };
  3452. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3453. if (this.isSupported) {
  3454. var targetStore;
  3455. if (url.indexOf(".babylon") !== -1) {
  3456. targetStore = "scenes";
  3457. }
  3458. else {
  3459. targetStore = "textures";
  3460. }
  3461. var file;
  3462. var transaction = this.db.transaction([targetStore]);
  3463. transaction.oncomplete = function (event) {
  3464. if (file) {
  3465. callback(file.data);
  3466. }
  3467. else {
  3468. notInDBCallback();
  3469. }
  3470. };
  3471. transaction.onabort = function (event) {
  3472. notInDBCallback();
  3473. };
  3474. var getRequest = transaction.objectStore(targetStore).get(url);
  3475. getRequest.onsuccess = function (event) {
  3476. file = (event.target).result;
  3477. };
  3478. getRequest.onerror = function (event) {
  3479. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3480. notInDBCallback();
  3481. };
  3482. }
  3483. else {
  3484. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3485. callback();
  3486. }
  3487. };
  3488. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3489. var _this = this;
  3490. if (this.isSupported) {
  3491. var targetStore;
  3492. if (url.indexOf(".babylon") !== -1) {
  3493. targetStore = "scenes";
  3494. }
  3495. else {
  3496. targetStore = "textures";
  3497. }
  3498. // Create XHR
  3499. var xhr = new XMLHttpRequest(), fileData;
  3500. xhr.open("GET", url, true);
  3501. if (useArrayBuffer) {
  3502. xhr.responseType = "arraybuffer";
  3503. }
  3504. xhr.onprogress = progressCallback;
  3505. xhr.addEventListener("load", function () {
  3506. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3507. // Blob as response (XHR2)
  3508. //fileData = xhr.responseText;
  3509. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3510. if (!_this.hasReachedQuota) {
  3511. // Open a transaction to the database
  3512. var transaction = _this.db.transaction([targetStore], "readwrite");
  3513. // the transaction could abort because of a QuotaExceededError error
  3514. transaction.onabort = function (event) {
  3515. try {
  3516. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3517. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3518. this.hasReachedQuota = true;
  3519. }
  3520. }
  3521. catch (ex) { }
  3522. callback(fileData);
  3523. };
  3524. transaction.oncomplete = function (event) {
  3525. callback(fileData);
  3526. };
  3527. var newFile;
  3528. if (targetStore === "scenes") {
  3529. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3530. }
  3531. else {
  3532. newFile = { textureUrl: url, data: fileData };
  3533. }
  3534. try {
  3535. // Put the scene into the database
  3536. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3537. addRequest.onsuccess = function (event) {
  3538. };
  3539. addRequest.onerror = function (event) {
  3540. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3541. };
  3542. }
  3543. catch (ex) {
  3544. callback(fileData);
  3545. }
  3546. }
  3547. else {
  3548. callback(fileData);
  3549. }
  3550. }
  3551. else {
  3552. callback();
  3553. }
  3554. }, false);
  3555. xhr.addEventListener("error", function (event) {
  3556. BABYLON.Tools.Error("error on XHR request.");
  3557. callback();
  3558. }, false);
  3559. xhr.send();
  3560. }
  3561. else {
  3562. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3563. callback();
  3564. }
  3565. };
  3566. Database.IsUASupportingBlobStorage = true;
  3567. Database.IDBStorageEnabled = true;
  3568. Database.parseURL = function (url) {
  3569. var a = document.createElement('a');
  3570. a.href = url;
  3571. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3572. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3573. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3574. return absLocation;
  3575. };
  3576. Database.ReturnFullUrlLocation = function (url) {
  3577. if (url.indexOf("http:/") === -1) {
  3578. return (Database.parseURL(window.location.href) + url);
  3579. }
  3580. else {
  3581. return url;
  3582. }
  3583. };
  3584. return Database;
  3585. })();
  3586. BABYLON.Database = Database;
  3587. })(BABYLON || (BABYLON = {}));
  3588. var BABYLON;
  3589. (function (BABYLON) {
  3590. var Internals;
  3591. (function (Internals) {
  3592. /*
  3593. * Based on jsTGALoader - Javascript loader for TGA file
  3594. * By Vincent Thibault
  3595. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3596. */
  3597. var TGATools = (function () {
  3598. function TGATools() {
  3599. }
  3600. TGATools.GetTGAHeader = function (data) {
  3601. var offset = 0;
  3602. var header = {
  3603. id_length: data[offset++],
  3604. colormap_type: data[offset++],
  3605. image_type: data[offset++],
  3606. colormap_index: data[offset++] | data[offset++] << 8,
  3607. colormap_length: data[offset++] | data[offset++] << 8,
  3608. colormap_size: data[offset++],
  3609. origin: [
  3610. data[offset++] | data[offset++] << 8,
  3611. data[offset++] | data[offset++] << 8
  3612. ],
  3613. width: data[offset++] | data[offset++] << 8,
  3614. height: data[offset++] | data[offset++] << 8,
  3615. pixel_size: data[offset++],
  3616. flags: data[offset++]
  3617. };
  3618. return header;
  3619. };
  3620. TGATools.UploadContent = function (gl, data) {
  3621. // Not enough data to contain header ?
  3622. if (data.length < 19) {
  3623. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3624. return;
  3625. }
  3626. // Read Header
  3627. var offset = 18;
  3628. var header = TGATools.GetTGAHeader(data);
  3629. // Assume it's a valid Targa file.
  3630. if (header.id_length + offset > data.length) {
  3631. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3632. return;
  3633. }
  3634. // Skip not needed data
  3635. offset += header.id_length;
  3636. var use_rle = false;
  3637. var use_pal = false;
  3638. var use_rgb = false;
  3639. var use_grey = false;
  3640. // Get some informations.
  3641. switch (header.image_type) {
  3642. case TGATools._TYPE_RLE_INDEXED:
  3643. use_rle = true;
  3644. case TGATools._TYPE_INDEXED:
  3645. use_pal = true;
  3646. break;
  3647. case TGATools._TYPE_RLE_RGB:
  3648. use_rle = true;
  3649. case TGATools._TYPE_RGB:
  3650. use_rgb = true;
  3651. break;
  3652. case TGATools._TYPE_RLE_GREY:
  3653. use_rle = true;
  3654. case TGATools._TYPE_GREY:
  3655. use_grey = true;
  3656. break;
  3657. }
  3658. var pixel_data;
  3659. var numAlphaBits = header.flags & 0xf;
  3660. var pixel_size = header.pixel_size >> 3;
  3661. var pixel_total = header.width * header.height * pixel_size;
  3662. // Read palettes
  3663. var palettes;
  3664. if (use_pal) {
  3665. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3666. }
  3667. // Read LRE
  3668. if (use_rle) {
  3669. pixel_data = new Uint8Array(pixel_total);
  3670. var c, count, i;
  3671. var localOffset = 0;
  3672. var pixels = new Uint8Array(pixel_size);
  3673. while (offset < pixel_total && localOffset < pixel_total) {
  3674. c = data[offset++];
  3675. count = (c & 0x7f) + 1;
  3676. // RLE pixels
  3677. if (c & 0x80) {
  3678. // Bind pixel tmp array
  3679. for (i = 0; i < pixel_size; ++i) {
  3680. pixels[i] = data[offset++];
  3681. }
  3682. // Copy pixel array
  3683. for (i = 0; i < count; ++i) {
  3684. pixel_data.set(pixels, localOffset + i * pixel_size);
  3685. }
  3686. localOffset += pixel_size * count;
  3687. }
  3688. else {
  3689. count *= pixel_size;
  3690. for (i = 0; i < count; ++i) {
  3691. pixel_data[localOffset + i] = data[offset++];
  3692. }
  3693. localOffset += count;
  3694. }
  3695. }
  3696. }
  3697. else {
  3698. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3699. }
  3700. // Load to texture
  3701. var x_start, y_start, x_step, y_step, y_end, x_end;
  3702. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3703. default:
  3704. case TGATools._ORIGIN_UL:
  3705. x_start = 0;
  3706. x_step = 1;
  3707. x_end = header.width;
  3708. y_start = 0;
  3709. y_step = 1;
  3710. y_end = header.height;
  3711. break;
  3712. case TGATools._ORIGIN_BL:
  3713. x_start = 0;
  3714. x_step = 1;
  3715. x_end = header.width;
  3716. y_start = header.height - 1;
  3717. y_step = -1;
  3718. y_end = -1;
  3719. break;
  3720. case TGATools._ORIGIN_UR:
  3721. x_start = header.width - 1;
  3722. x_step = -1;
  3723. x_end = -1;
  3724. y_start = 0;
  3725. y_step = 1;
  3726. y_end = header.height;
  3727. break;
  3728. case TGATools._ORIGIN_BR:
  3729. x_start = header.width - 1;
  3730. x_step = -1;
  3731. x_end = -1;
  3732. y_start = header.height - 1;
  3733. y_step = -1;
  3734. y_end = -1;
  3735. break;
  3736. }
  3737. // Load the specify method
  3738. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3739. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3740. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3741. };
  3742. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3743. var image = pixel_data, colormap = palettes;
  3744. var width = header.width, height = header.height;
  3745. var color, i = 0, x, y;
  3746. var imageData = new Uint8Array(width * height * 4);
  3747. for (y = y_start; y !== y_end; y += y_step) {
  3748. for (x = x_start; x !== x_end; x += x_step, i++) {
  3749. color = image[i];
  3750. imageData[(x + width * y) * 4 + 3] = 255;
  3751. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3752. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3753. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3754. }
  3755. }
  3756. return imageData;
  3757. };
  3758. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3759. var image = pixel_data;
  3760. var width = header.width, height = header.height;
  3761. var color, i = 0, x, y;
  3762. var imageData = new Uint8Array(width * height * 4);
  3763. for (y = y_start; y !== y_end; y += y_step) {
  3764. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3765. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3766. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3767. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3768. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3769. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3770. }
  3771. }
  3772. return imageData;
  3773. };
  3774. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3775. var image = pixel_data;
  3776. var width = header.width, height = header.height;
  3777. var i = 0, x, y;
  3778. var imageData = new Uint8Array(width * height * 4);
  3779. for (y = y_start; y !== y_end; y += y_step) {
  3780. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3781. imageData[(x + width * y) * 4 + 3] = 255;
  3782. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3783. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3784. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3785. }
  3786. }
  3787. return imageData;
  3788. };
  3789. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3790. var image = pixel_data;
  3791. var width = header.width, height = header.height;
  3792. var i = 0, x, y;
  3793. var imageData = new Uint8Array(width * height * 4);
  3794. for (y = y_start; y !== y_end; y += y_step) {
  3795. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3796. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3797. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3798. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3799. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3800. }
  3801. }
  3802. return imageData;
  3803. };
  3804. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3805. var image = pixel_data;
  3806. var width = header.width, height = header.height;
  3807. var color, i = 0, x, y;
  3808. var imageData = new Uint8Array(width * height * 4);
  3809. for (y = y_start; y !== y_end; y += y_step) {
  3810. for (x = x_start; x !== x_end; x += x_step, i++) {
  3811. color = image[i];
  3812. imageData[(x + width * y) * 4 + 0] = color;
  3813. imageData[(x + width * y) * 4 + 1] = color;
  3814. imageData[(x + width * y) * 4 + 2] = color;
  3815. imageData[(x + width * y) * 4 + 3] = 255;
  3816. }
  3817. }
  3818. return imageData;
  3819. };
  3820. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3821. var image = pixel_data;
  3822. var width = header.width, height = header.height;
  3823. var i = 0, x, y;
  3824. var imageData = new Uint8Array(width * height * 4);
  3825. for (y = y_start; y !== y_end; y += y_step) {
  3826. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3827. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3828. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3829. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3830. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3831. }
  3832. }
  3833. return imageData;
  3834. };
  3835. TGATools._TYPE_NO_DATA = 0;
  3836. TGATools._TYPE_INDEXED = 1;
  3837. TGATools._TYPE_RGB = 2;
  3838. TGATools._TYPE_GREY = 3;
  3839. TGATools._TYPE_RLE_INDEXED = 9;
  3840. TGATools._TYPE_RLE_RGB = 10;
  3841. TGATools._TYPE_RLE_GREY = 11;
  3842. TGATools._ORIGIN_MASK = 0x30;
  3843. TGATools._ORIGIN_SHIFT = 0x04;
  3844. TGATools._ORIGIN_BL = 0x00;
  3845. TGATools._ORIGIN_BR = 0x01;
  3846. TGATools._ORIGIN_UL = 0x02;
  3847. TGATools._ORIGIN_UR = 0x03;
  3848. return TGATools;
  3849. })();
  3850. Internals.TGATools = TGATools;
  3851. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3852. })(BABYLON || (BABYLON = {}));
  3853. var BABYLON;
  3854. (function (BABYLON) {
  3855. var SmartArray = (function () {
  3856. function SmartArray(capacity) {
  3857. this.length = 0;
  3858. this._duplicateId = 0;
  3859. this.data = new Array(capacity);
  3860. this._id = SmartArray._GlobalId++;
  3861. }
  3862. SmartArray.prototype.push = function (value) {
  3863. this.data[this.length++] = value;
  3864. if (this.length > this.data.length) {
  3865. this.data.length *= 2;
  3866. }
  3867. if (!value.__smartArrayFlags) {
  3868. value.__smartArrayFlags = {};
  3869. }
  3870. value.__smartArrayFlags[this._id] = this._duplicateId;
  3871. };
  3872. SmartArray.prototype.pushNoDuplicate = function (value) {
  3873. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3874. return;
  3875. }
  3876. this.push(value);
  3877. };
  3878. SmartArray.prototype.sort = function (compareFn) {
  3879. this.data.sort(compareFn);
  3880. };
  3881. SmartArray.prototype.reset = function () {
  3882. this.length = 0;
  3883. this._duplicateId++;
  3884. };
  3885. SmartArray.prototype.concat = function (array) {
  3886. if (array.length === 0) {
  3887. return;
  3888. }
  3889. if (this.length + array.length > this.data.length) {
  3890. this.data.length = (this.length + array.length) * 2;
  3891. }
  3892. for (var index = 0; index < array.length; index++) {
  3893. this.data[this.length++] = (array.data || array)[index];
  3894. }
  3895. };
  3896. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3897. if (array.length === 0) {
  3898. return;
  3899. }
  3900. if (this.length + array.length > this.data.length) {
  3901. this.data.length = (this.length + array.length) * 2;
  3902. }
  3903. for (var index = 0; index < array.length; index++) {
  3904. var item = (array.data || array)[index];
  3905. this.pushNoDuplicate(item);
  3906. }
  3907. };
  3908. SmartArray.prototype.indexOf = function (value) {
  3909. var position = this.data.indexOf(value);
  3910. if (position >= this.length) {
  3911. return -1;
  3912. }
  3913. return position;
  3914. };
  3915. // Statics
  3916. SmartArray._GlobalId = 0;
  3917. return SmartArray;
  3918. })();
  3919. BABYLON.SmartArray = SmartArray;
  3920. })(BABYLON || (BABYLON = {}));
  3921. var BABYLON;
  3922. (function (BABYLON) {
  3923. var SmartCollection = (function () {
  3924. function SmartCollection(capacity) {
  3925. if (capacity === void 0) { capacity = 10; }
  3926. this.count = 0;
  3927. this._initialCapacity = capacity;
  3928. this.items = {};
  3929. this._keys = new Array(this._initialCapacity);
  3930. }
  3931. SmartCollection.prototype.add = function (key, item) {
  3932. if (this.items[key] != undefined) {
  3933. return -1;
  3934. }
  3935. this.items[key] = item;
  3936. //literal keys are always strings, but we keep source type of key in _keys array
  3937. this._keys[this.count++] = key;
  3938. if (this.count > this._keys.length) {
  3939. this._keys.length *= 2;
  3940. }
  3941. return this.count;
  3942. };
  3943. SmartCollection.prototype.remove = function (key) {
  3944. if (this.items[key] == undefined) {
  3945. return -1;
  3946. }
  3947. return this.removeItemOfIndex(this.indexOf(key));
  3948. };
  3949. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3950. if (index < this.count && index > -1) {
  3951. delete this.items[this._keys[index]];
  3952. //here, shifting by hand is better optimised than .splice
  3953. while (index < this.count) {
  3954. this._keys[index] = this._keys[index + 1];
  3955. index++;
  3956. }
  3957. }
  3958. else {
  3959. return -1;
  3960. }
  3961. return --this.count;
  3962. };
  3963. SmartCollection.prototype.indexOf = function (key) {
  3964. for (var i = 0; i !== this.count; i++) {
  3965. if (this._keys[i] === key) {
  3966. return i;
  3967. }
  3968. }
  3969. return -1;
  3970. };
  3971. SmartCollection.prototype.item = function (key) {
  3972. return this.items[key];
  3973. };
  3974. SmartCollection.prototype.getAllKeys = function () {
  3975. if (this.count > 0) {
  3976. var keys = new Array(this.count);
  3977. for (var i = 0; i < this.count; i++) {
  3978. keys[i] = this._keys[i];
  3979. }
  3980. return keys;
  3981. }
  3982. else {
  3983. return undefined;
  3984. }
  3985. };
  3986. SmartCollection.prototype.getKeyByIndex = function (index) {
  3987. if (index < this.count && index > -1) {
  3988. return this._keys[index];
  3989. }
  3990. else {
  3991. return undefined;
  3992. }
  3993. };
  3994. SmartCollection.prototype.getItemByIndex = function (index) {
  3995. if (index < this.count && index > -1) {
  3996. return this.items[this._keys[index]];
  3997. }
  3998. else {
  3999. return undefined;
  4000. }
  4001. };
  4002. SmartCollection.prototype.empty = function () {
  4003. if (this.count > 0) {
  4004. this.count = 0;
  4005. this.items = {};
  4006. this._keys = new Array(this._initialCapacity);
  4007. }
  4008. };
  4009. SmartCollection.prototype.forEach = function (block) {
  4010. var key;
  4011. for (key in this.items) {
  4012. if (this.items.hasOwnProperty(key)) {
  4013. block(this.items[key]);
  4014. }
  4015. }
  4016. };
  4017. return SmartCollection;
  4018. })();
  4019. BABYLON.SmartCollection = SmartCollection;
  4020. })(BABYLON || (BABYLON = {}));
  4021. var BABYLON;
  4022. (function (BABYLON) {
  4023. // Screenshots
  4024. var screenshotCanvas;
  4025. var cloneValue = function (source, destinationObject) {
  4026. if (!source)
  4027. return null;
  4028. if (source instanceof BABYLON.Mesh) {
  4029. return null;
  4030. }
  4031. if (source instanceof BABYLON.SubMesh) {
  4032. return source.clone(destinationObject);
  4033. }
  4034. else if (source.clone) {
  4035. return source.clone();
  4036. }
  4037. return null;
  4038. };
  4039. var Tools = (function () {
  4040. function Tools() {
  4041. }
  4042. Tools.Instantiate = function (className) {
  4043. var arr = className.split(".");
  4044. var fn = (window || this);
  4045. for (var i = 0, len = arr.length; i < len; i++) {
  4046. fn = fn[arr[i]];
  4047. }
  4048. if (typeof fn !== "function") {
  4049. return null;
  4050. }
  4051. return fn;
  4052. };
  4053. Tools.SetImmediate = function (action) {
  4054. if (window.setImmediate) {
  4055. window.setImmediate(action);
  4056. }
  4057. else {
  4058. setTimeout(action, 1);
  4059. }
  4060. };
  4061. Tools.IsExponentOfTwo = function (value) {
  4062. var count = 1;
  4063. do {
  4064. count *= 2;
  4065. } while (count < value);
  4066. return count === value;
  4067. };
  4068. Tools.GetExponentOfTwo = function (value, max) {
  4069. var count = 1;
  4070. do {
  4071. count *= 2;
  4072. } while (count < value);
  4073. if (count > max)
  4074. count = max;
  4075. return count;
  4076. };
  4077. Tools.GetFilename = function (path) {
  4078. var index = path.lastIndexOf("/");
  4079. if (index < 0)
  4080. return path;
  4081. return path.substring(index + 1);
  4082. };
  4083. Tools.GetDOMTextContent = function (element) {
  4084. var result = "";
  4085. var child = element.firstChild;
  4086. while (child) {
  4087. if (child.nodeType === 3) {
  4088. result += child.textContent;
  4089. }
  4090. child = child.nextSibling;
  4091. }
  4092. return result;
  4093. };
  4094. Tools.ToDegrees = function (angle) {
  4095. return angle * 180 / Math.PI;
  4096. };
  4097. Tools.ToRadians = function (angle) {
  4098. return angle * Math.PI / 180;
  4099. };
  4100. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4101. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4102. var output = "";
  4103. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4104. var i = 0;
  4105. var bytes = new Uint8Array(buffer);
  4106. while (i < bytes.length) {
  4107. chr1 = bytes[i++];
  4108. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4109. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4110. enc1 = chr1 >> 2;
  4111. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4112. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4113. enc4 = chr3 & 63;
  4114. if (isNaN(chr2)) {
  4115. enc3 = enc4 = 64;
  4116. }
  4117. else if (isNaN(chr3)) {
  4118. enc4 = 64;
  4119. }
  4120. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4121. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4122. }
  4123. return "data:image/png;base64," + output;
  4124. };
  4125. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4126. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4127. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4128. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4129. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4130. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4131. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4132. }
  4133. return {
  4134. minimum: minimum,
  4135. maximum: maximum
  4136. };
  4137. };
  4138. Tools.ExtractMinAndMax = function (positions, start, count) {
  4139. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4140. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4141. for (var index = start; index < start + count; index++) {
  4142. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4143. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4144. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4145. }
  4146. return {
  4147. minimum: minimum,
  4148. maximum: maximum
  4149. };
  4150. };
  4151. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4152. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4153. return undefined;
  4154. return Array.isArray(obj) ? obj : [obj];
  4155. };
  4156. // Misc.
  4157. Tools.GetPointerPrefix = function () {
  4158. var eventPrefix = "pointer";
  4159. // Check if pointer events are supported
  4160. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4161. eventPrefix = "mouse";
  4162. }
  4163. return eventPrefix;
  4164. };
  4165. Tools.QueueNewFrame = function (func) {
  4166. if (window.requestAnimationFrame)
  4167. window.requestAnimationFrame(func);
  4168. else if (window.msRequestAnimationFrame)
  4169. window.msRequestAnimationFrame(func);
  4170. else if (window.webkitRequestAnimationFrame)
  4171. window.webkitRequestAnimationFrame(func);
  4172. else if (window.mozRequestAnimationFrame)
  4173. window.mozRequestAnimationFrame(func);
  4174. else if (window.oRequestAnimationFrame)
  4175. window.oRequestAnimationFrame(func);
  4176. else {
  4177. window.setTimeout(func, 16);
  4178. }
  4179. };
  4180. Tools.RequestFullscreen = function (element) {
  4181. if (element.requestFullscreen)
  4182. element.requestFullscreen();
  4183. else if (element.msRequestFullscreen)
  4184. element.msRequestFullscreen();
  4185. else if (element.webkitRequestFullscreen)
  4186. element.webkitRequestFullscreen();
  4187. else if (element.mozRequestFullScreen)
  4188. element.mozRequestFullScreen();
  4189. };
  4190. Tools.ExitFullscreen = function () {
  4191. if (document.exitFullscreen) {
  4192. document.exitFullscreen();
  4193. }
  4194. else if (document.mozCancelFullScreen) {
  4195. document.mozCancelFullScreen();
  4196. }
  4197. else if (document.webkitCancelFullScreen) {
  4198. document.webkitCancelFullScreen();
  4199. }
  4200. else if (document.msCancelFullScreen) {
  4201. document.msCancelFullScreen();
  4202. }
  4203. };
  4204. // External files
  4205. Tools.CleanUrl = function (url) {
  4206. url = url.replace(/#/mg, "%23");
  4207. return url;
  4208. };
  4209. Tools.LoadImage = function (url, onload, onerror, database) {
  4210. if (url instanceof ArrayBuffer) {
  4211. url = Tools.EncodeArrayBufferTobase64(url);
  4212. }
  4213. url = Tools.CleanUrl(url);
  4214. var img = new Image();
  4215. if (url.substr(0, 5) !== "data:") {
  4216. if (Tools.CorsBehavior) {
  4217. switch (typeof (Tools.CorsBehavior)) {
  4218. case "function":
  4219. var result = Tools.CorsBehavior(url);
  4220. if (result) {
  4221. img.crossOrigin = result;
  4222. }
  4223. break;
  4224. case "string":
  4225. default:
  4226. img.crossOrigin = Tools.CorsBehavior;
  4227. break;
  4228. }
  4229. }
  4230. }
  4231. img.onload = function () {
  4232. onload(img);
  4233. };
  4234. img.onerror = function (err) {
  4235. Tools.Error("Error while trying to load texture: " + url);
  4236. if (Tools.UseFallbackTexture) {
  4237. 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";
  4238. onload(img);
  4239. }
  4240. else {
  4241. onerror();
  4242. }
  4243. };
  4244. var noIndexedDB = function () {
  4245. img.src = url;
  4246. };
  4247. var loadFromIndexedDB = function () {
  4248. database.loadImageFromDB(url, img);
  4249. };
  4250. //ANY database to do!
  4251. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4252. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4253. }
  4254. else {
  4255. if (url.indexOf("file:") === -1) {
  4256. noIndexedDB();
  4257. }
  4258. else {
  4259. try {
  4260. var textureName = url.substring(5);
  4261. var blobURL;
  4262. try {
  4263. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4264. }
  4265. catch (ex) {
  4266. // Chrome doesn't support oneTimeOnly parameter
  4267. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4268. }
  4269. img.src = blobURL;
  4270. }
  4271. catch (e) {
  4272. img.src = null;
  4273. }
  4274. }
  4275. }
  4276. return img;
  4277. };
  4278. //ANY
  4279. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4280. url = Tools.CleanUrl(url);
  4281. var noIndexedDB = function () {
  4282. var request = new XMLHttpRequest();
  4283. var loadUrl = Tools.BaseUrl + url;
  4284. request.open('GET', loadUrl, true);
  4285. if (useArrayBuffer) {
  4286. request.responseType = "arraybuffer";
  4287. }
  4288. request.onprogress = progressCallBack;
  4289. request.onreadystatechange = function () {
  4290. if (request.readyState === 4) {
  4291. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4292. callback(!useArrayBuffer ? request.responseText : request.response);
  4293. }
  4294. else {
  4295. if (onError) {
  4296. onError();
  4297. }
  4298. else {
  4299. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4300. }
  4301. }
  4302. }
  4303. };
  4304. request.send(null);
  4305. };
  4306. var loadFromIndexedDB = function () {
  4307. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4308. };
  4309. if (url.indexOf("file:") !== -1) {
  4310. var fileName = url.substring(5);
  4311. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4312. }
  4313. else {
  4314. // Caching all files
  4315. if (database && database.enableSceneOffline) {
  4316. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4317. }
  4318. else {
  4319. noIndexedDB();
  4320. }
  4321. }
  4322. };
  4323. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4324. var reader = new FileReader();
  4325. reader.onload = function (e) {
  4326. //target doesn't have result from ts 1.3
  4327. callback(e.target['result']);
  4328. };
  4329. reader.onprogress = progressCallback;
  4330. reader.readAsDataURL(fileToLoad);
  4331. };
  4332. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4333. var reader = new FileReader();
  4334. reader.onerror = function (e) {
  4335. Tools.Log("Error while reading file: " + fileToLoad.name);
  4336. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4337. };
  4338. reader.onload = function (e) {
  4339. //target doesn't have result from ts 1.3
  4340. callback(e.target['result']);
  4341. };
  4342. reader.onprogress = progressCallBack;
  4343. if (!useArrayBuffer) {
  4344. // Asynchronous read
  4345. reader.readAsText(fileToLoad);
  4346. }
  4347. else {
  4348. reader.readAsArrayBuffer(fileToLoad);
  4349. }
  4350. };
  4351. //returns a downloadable url to a file content.
  4352. Tools.FileAsURL = function (content) {
  4353. var fileBlob = new Blob([content]);
  4354. var url = window.URL || window.webkitURL;
  4355. var link = url.createObjectURL(fileBlob);
  4356. return link;
  4357. };
  4358. // Misc.
  4359. Tools.Format = function (value, decimals) {
  4360. if (decimals === void 0) { decimals = 2; }
  4361. return value.toFixed(decimals);
  4362. };
  4363. Tools.CheckExtends = function (v, min, max) {
  4364. if (v.x < min.x)
  4365. min.x = v.x;
  4366. if (v.y < min.y)
  4367. min.y = v.y;
  4368. if (v.z < min.z)
  4369. min.z = v.z;
  4370. if (v.x > max.x)
  4371. max.x = v.x;
  4372. if (v.y > max.y)
  4373. max.y = v.y;
  4374. if (v.z > max.z)
  4375. max.z = v.z;
  4376. };
  4377. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4378. for (var prop in source) {
  4379. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4380. continue;
  4381. }
  4382. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4383. continue;
  4384. }
  4385. var sourceValue = source[prop];
  4386. var typeOfSourceValue = typeof sourceValue;
  4387. if (typeOfSourceValue === "function") {
  4388. continue;
  4389. }
  4390. if (typeOfSourceValue === "object") {
  4391. if (sourceValue instanceof Array) {
  4392. destination[prop] = [];
  4393. if (sourceValue.length > 0) {
  4394. if (typeof sourceValue[0] == "object") {
  4395. for (var index = 0; index < sourceValue.length; index++) {
  4396. var clonedValue = cloneValue(sourceValue[index], destination);
  4397. if (destination[prop].indexOf(clonedValue) === -1) {
  4398. destination[prop].push(clonedValue);
  4399. }
  4400. }
  4401. }
  4402. else {
  4403. destination[prop] = sourceValue.slice(0);
  4404. }
  4405. }
  4406. }
  4407. else {
  4408. destination[prop] = cloneValue(sourceValue, destination);
  4409. }
  4410. }
  4411. else {
  4412. destination[prop] = sourceValue;
  4413. }
  4414. }
  4415. };
  4416. Tools.IsEmpty = function (obj) {
  4417. for (var i in obj) {
  4418. return false;
  4419. }
  4420. return true;
  4421. };
  4422. Tools.RegisterTopRootEvents = function (events) {
  4423. for (var index = 0; index < events.length; index++) {
  4424. var event = events[index];
  4425. window.addEventListener(event.name, event.handler, false);
  4426. try {
  4427. if (window.parent) {
  4428. window.parent.addEventListener(event.name, event.handler, false);
  4429. }
  4430. }
  4431. catch (e) {
  4432. }
  4433. }
  4434. };
  4435. Tools.UnregisterTopRootEvents = function (events) {
  4436. for (var index = 0; index < events.length; index++) {
  4437. var event = events[index];
  4438. window.removeEventListener(event.name, event.handler);
  4439. try {
  4440. if (window.parent) {
  4441. window.parent.removeEventListener(event.name, event.handler);
  4442. }
  4443. }
  4444. catch (e) {
  4445. }
  4446. }
  4447. };
  4448. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4449. // Read the contents of the framebuffer
  4450. var numberOfChannelsByLine = width * 4;
  4451. var halfHeight = height / 2;
  4452. //Reading datas from WebGL
  4453. var data = engine.readPixels(0, 0, width, height);
  4454. //To flip image on Y axis.
  4455. for (var i = 0; i < halfHeight; i++) {
  4456. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4457. var currentCell = j + i * numberOfChannelsByLine;
  4458. var targetLine = height - i - 1;
  4459. var targetCell = j + targetLine * numberOfChannelsByLine;
  4460. var temp = data[currentCell];
  4461. data[currentCell] = data[targetCell];
  4462. data[targetCell] = temp;
  4463. }
  4464. }
  4465. // Create a 2D canvas to store the result
  4466. if (!screenshotCanvas) {
  4467. screenshotCanvas = document.createElement('canvas');
  4468. }
  4469. screenshotCanvas.width = width;
  4470. screenshotCanvas.height = height;
  4471. var context = screenshotCanvas.getContext('2d');
  4472. // Copy the pixels to a 2D canvas
  4473. var imageData = context.createImageData(width, height);
  4474. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4475. var castData = imageData.data;
  4476. castData.set(data);
  4477. context.putImageData(imageData, 0, 0);
  4478. var base64Image = screenshotCanvas.toDataURL();
  4479. if (successCallback) {
  4480. successCallback(base64Image);
  4481. }
  4482. else {
  4483. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4484. if (("download" in document.createElement("a"))) {
  4485. var a = window.document.createElement("a");
  4486. a.href = base64Image;
  4487. var date = new Date();
  4488. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4489. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4490. window.document.body.appendChild(a);
  4491. a.addEventListener("click", function () {
  4492. a.parentElement.removeChild(a);
  4493. });
  4494. a.click();
  4495. }
  4496. else {
  4497. var newWindow = window.open("");
  4498. var img = newWindow.document.createElement("img");
  4499. img.src = base64Image;
  4500. newWindow.document.body.appendChild(img);
  4501. }
  4502. }
  4503. };
  4504. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4505. var width;
  4506. var height;
  4507. //If a precision value is specified
  4508. if (size.precision) {
  4509. width = Math.round(engine.getRenderWidth() * size.precision);
  4510. height = Math.round(width / engine.getAspectRatio(camera));
  4511. size = { width: width, height: height };
  4512. }
  4513. else if (size.width && size.height) {
  4514. width = size.width;
  4515. height = size.height;
  4516. }
  4517. else if (size.width && !size.height) {
  4518. width = size.width;
  4519. height = Math.round(width / engine.getAspectRatio(camera));
  4520. size = { width: width, height: height };
  4521. }
  4522. else if (size.height && !size.width) {
  4523. height = size.height;
  4524. width = Math.round(height * engine.getAspectRatio(camera));
  4525. size = { width: width, height: height };
  4526. }
  4527. else if (!isNaN(size)) {
  4528. height = size;
  4529. width = size;
  4530. }
  4531. else {
  4532. Tools.Error("Invalid 'size' parameter !");
  4533. return;
  4534. }
  4535. var scene = camera.getScene();
  4536. var previousCamera = null;
  4537. if (scene.activeCamera !== camera) {
  4538. previousCamera = scene.activeCamera;
  4539. scene.activeCamera = camera;
  4540. }
  4541. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4542. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4543. texture.renderList = scene.meshes;
  4544. texture.onAfterRender = function () {
  4545. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4546. };
  4547. scene.incrementRenderId();
  4548. texture.render(true);
  4549. texture.dispose();
  4550. if (previousCamera) {
  4551. scene.activeCamera = previousCamera;
  4552. }
  4553. camera.getProjectionMatrix(true); // Force cache refresh;
  4554. };
  4555. // XHR response validator for local file scenario
  4556. Tools.ValidateXHRData = function (xhr, dataType) {
  4557. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4558. if (dataType === void 0) { dataType = 7; }
  4559. try {
  4560. if (dataType & 1) {
  4561. if (xhr.responseText && xhr.responseText.length > 0) {
  4562. return true;
  4563. }
  4564. else if (dataType === 1) {
  4565. return false;
  4566. }
  4567. }
  4568. if (dataType & 2) {
  4569. // Check header width and height since there is no "TGA" magic number
  4570. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4571. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4572. return true;
  4573. }
  4574. else if (dataType === 2) {
  4575. return false;
  4576. }
  4577. }
  4578. if (dataType & 4) {
  4579. // Check for the "DDS" magic number
  4580. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4581. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4582. return true;
  4583. }
  4584. else {
  4585. return false;
  4586. }
  4587. }
  4588. }
  4589. catch (e) {
  4590. }
  4591. return false;
  4592. };
  4593. Object.defineProperty(Tools, "NoneLogLevel", {
  4594. get: function () {
  4595. return Tools._NoneLogLevel;
  4596. },
  4597. enumerable: true,
  4598. configurable: true
  4599. });
  4600. Object.defineProperty(Tools, "MessageLogLevel", {
  4601. get: function () {
  4602. return Tools._MessageLogLevel;
  4603. },
  4604. enumerable: true,
  4605. configurable: true
  4606. });
  4607. Object.defineProperty(Tools, "WarningLogLevel", {
  4608. get: function () {
  4609. return Tools._WarningLogLevel;
  4610. },
  4611. enumerable: true,
  4612. configurable: true
  4613. });
  4614. Object.defineProperty(Tools, "ErrorLogLevel", {
  4615. get: function () {
  4616. return Tools._ErrorLogLevel;
  4617. },
  4618. enumerable: true,
  4619. configurable: true
  4620. });
  4621. Object.defineProperty(Tools, "AllLogLevel", {
  4622. get: function () {
  4623. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4624. },
  4625. enumerable: true,
  4626. configurable: true
  4627. });
  4628. Tools._AddLogEntry = function (entry) {
  4629. Tools._LogCache = entry + Tools._LogCache;
  4630. if (Tools.OnNewCacheEntry) {
  4631. Tools.OnNewCacheEntry(entry);
  4632. }
  4633. };
  4634. Tools._FormatMessage = function (message) {
  4635. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4636. var date = new Date();
  4637. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4638. };
  4639. Tools._LogDisabled = function (message) {
  4640. // nothing to do
  4641. };
  4642. Tools._LogEnabled = function (message) {
  4643. var formattedMessage = Tools._FormatMessage(message);
  4644. console.log("BJS - " + formattedMessage);
  4645. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4646. Tools._AddLogEntry(entry);
  4647. };
  4648. Tools._WarnDisabled = function (message) {
  4649. // nothing to do
  4650. };
  4651. Tools._WarnEnabled = function (message) {
  4652. var formattedMessage = Tools._FormatMessage(message);
  4653. console.warn("BJS - " + formattedMessage);
  4654. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4655. Tools._AddLogEntry(entry);
  4656. };
  4657. Tools._ErrorDisabled = function (message) {
  4658. // nothing to do
  4659. };
  4660. Tools._ErrorEnabled = function (message) {
  4661. Tools.errorsCount++;
  4662. var formattedMessage = Tools._FormatMessage(message);
  4663. console.error("BJS - " + formattedMessage);
  4664. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4665. Tools._AddLogEntry(entry);
  4666. };
  4667. Object.defineProperty(Tools, "LogCache", {
  4668. get: function () {
  4669. return Tools._LogCache;
  4670. },
  4671. enumerable: true,
  4672. configurable: true
  4673. });
  4674. Tools.ClearLogCache = function () {
  4675. Tools._LogCache = "";
  4676. Tools.errorsCount = 0;
  4677. };
  4678. Object.defineProperty(Tools, "LogLevels", {
  4679. set: function (level) {
  4680. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4681. Tools.Log = Tools._LogEnabled;
  4682. }
  4683. else {
  4684. Tools.Log = Tools._LogDisabled;
  4685. }
  4686. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4687. Tools.Warn = Tools._WarnEnabled;
  4688. }
  4689. else {
  4690. Tools.Warn = Tools._WarnDisabled;
  4691. }
  4692. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4693. Tools.Error = Tools._ErrorEnabled;
  4694. }
  4695. else {
  4696. Tools.Error = Tools._ErrorDisabled;
  4697. }
  4698. },
  4699. enumerable: true,
  4700. configurable: true
  4701. });
  4702. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4703. get: function () {
  4704. return Tools._PerformanceNoneLogLevel;
  4705. },
  4706. enumerable: true,
  4707. configurable: true
  4708. });
  4709. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4710. get: function () {
  4711. return Tools._PerformanceUserMarkLogLevel;
  4712. },
  4713. enumerable: true,
  4714. configurable: true
  4715. });
  4716. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4717. get: function () {
  4718. return Tools._PerformanceConsoleLogLevel;
  4719. },
  4720. enumerable: true,
  4721. configurable: true
  4722. });
  4723. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4724. set: function (level) {
  4725. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4726. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4727. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4728. return;
  4729. }
  4730. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4731. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4732. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4733. return;
  4734. }
  4735. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4736. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4737. },
  4738. enumerable: true,
  4739. configurable: true
  4740. });
  4741. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4742. };
  4743. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4744. };
  4745. Tools._StartUserMark = function (counterName, condition) {
  4746. if (condition === void 0) { condition = true; }
  4747. if (!condition || !Tools._performance.mark) {
  4748. return;
  4749. }
  4750. Tools._performance.mark(counterName + "-Begin");
  4751. };
  4752. Tools._EndUserMark = function (counterName, condition) {
  4753. if (condition === void 0) { condition = true; }
  4754. if (!condition || !Tools._performance.mark) {
  4755. return;
  4756. }
  4757. Tools._performance.mark(counterName + "-End");
  4758. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4759. };
  4760. Tools._StartPerformanceConsole = function (counterName, condition) {
  4761. if (condition === void 0) { condition = true; }
  4762. if (!condition) {
  4763. return;
  4764. }
  4765. Tools._StartUserMark(counterName, condition);
  4766. if (console.time) {
  4767. console.time(counterName);
  4768. }
  4769. };
  4770. Tools._EndPerformanceConsole = function (counterName, condition) {
  4771. if (condition === void 0) { condition = true; }
  4772. if (!condition) {
  4773. return;
  4774. }
  4775. Tools._EndUserMark(counterName, condition);
  4776. if (console.time) {
  4777. console.timeEnd(counterName);
  4778. }
  4779. };
  4780. Object.defineProperty(Tools, "Now", {
  4781. get: function () {
  4782. if (window.performance && window.performance.now) {
  4783. return window.performance.now();
  4784. }
  4785. return new Date().getTime();
  4786. },
  4787. enumerable: true,
  4788. configurable: true
  4789. });
  4790. Tools.BaseUrl = "";
  4791. Tools.CorsBehavior = "anonymous";
  4792. Tools.UseFallbackTexture = true;
  4793. // Logs
  4794. Tools._NoneLogLevel = 0;
  4795. Tools._MessageLogLevel = 1;
  4796. Tools._WarningLogLevel = 2;
  4797. Tools._ErrorLogLevel = 4;
  4798. Tools._LogCache = "";
  4799. Tools.errorsCount = 0;
  4800. Tools.Log = Tools._LogEnabled;
  4801. Tools.Warn = Tools._WarnEnabled;
  4802. Tools.Error = Tools._ErrorEnabled;
  4803. // Performances
  4804. Tools._PerformanceNoneLogLevel = 0;
  4805. Tools._PerformanceUserMarkLogLevel = 1;
  4806. Tools._PerformanceConsoleLogLevel = 2;
  4807. Tools._performance = window.performance;
  4808. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4809. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4810. return Tools;
  4811. })();
  4812. BABYLON.Tools = Tools;
  4813. /**
  4814. * An implementation of a loop for asynchronous functions.
  4815. */
  4816. var AsyncLoop = (function () {
  4817. /**
  4818. * Constroctor.
  4819. * @param iterations the number of iterations.
  4820. * @param _fn the function to run each iteration
  4821. * @param _successCallback the callback that will be called upon succesful execution
  4822. * @param offset starting offset.
  4823. */
  4824. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4825. if (offset === void 0) { offset = 0; }
  4826. this.iterations = iterations;
  4827. this._fn = _fn;
  4828. this._successCallback = _successCallback;
  4829. this.index = offset - 1;
  4830. this._done = false;
  4831. }
  4832. /**
  4833. * Execute the next iteration. Must be called after the last iteration was finished.
  4834. */
  4835. AsyncLoop.prototype.executeNext = function () {
  4836. if (!this._done) {
  4837. if (this.index + 1 < this.iterations) {
  4838. ++this.index;
  4839. this._fn(this);
  4840. }
  4841. else {
  4842. this.breakLoop();
  4843. }
  4844. }
  4845. };
  4846. /**
  4847. * Break the loop and run the success callback.
  4848. */
  4849. AsyncLoop.prototype.breakLoop = function () {
  4850. this._done = true;
  4851. this._successCallback();
  4852. };
  4853. /**
  4854. * Helper function
  4855. */
  4856. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4857. if (offset === void 0) { offset = 0; }
  4858. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4859. loop.executeNext();
  4860. return loop;
  4861. };
  4862. /**
  4863. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4864. * @param iterations total number of iterations
  4865. * @param syncedIterations number of synchronous iterations in each async iteration.
  4866. * @param fn the function to call each iteration.
  4867. * @param callback a success call back that will be called when iterating stops.
  4868. * @param breakFunction a break condition (optional)
  4869. * @param timeout timeout settings for the setTimeout function. default - 0.
  4870. * @constructor
  4871. */
  4872. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4873. if (timeout === void 0) { timeout = 0; }
  4874. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4875. if (breakFunction && breakFunction())
  4876. loop.breakLoop();
  4877. else {
  4878. setTimeout(function () {
  4879. for (var i = 0; i < syncedIterations; ++i) {
  4880. var iteration = (loop.index * syncedIterations) + i;
  4881. if (iteration >= iterations)
  4882. break;
  4883. fn(iteration);
  4884. if (breakFunction && breakFunction()) {
  4885. loop.breakLoop();
  4886. break;
  4887. }
  4888. }
  4889. loop.executeNext();
  4890. }, timeout);
  4891. }
  4892. }, callback);
  4893. };
  4894. return AsyncLoop;
  4895. })();
  4896. BABYLON.AsyncLoop = AsyncLoop;
  4897. })(BABYLON || (BABYLON = {}));
  4898. var BABYLON;
  4899. (function (BABYLON) {
  4900. var Internals;
  4901. (function (Internals) {
  4902. var _AlphaState = (function () {
  4903. function _AlphaState() {
  4904. this._isAlphaBlendDirty = false;
  4905. this._isBlendFunctionParametersDirty = false;
  4906. this._alphaBlend = false;
  4907. this._blendFunctionParameters = new Array(4);
  4908. }
  4909. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4910. get: function () {
  4911. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4912. },
  4913. enumerable: true,
  4914. configurable: true
  4915. });
  4916. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4917. get: function () {
  4918. return this._alphaBlend;
  4919. },
  4920. set: function (value) {
  4921. if (this._alphaBlend === value) {
  4922. return;
  4923. }
  4924. this._alphaBlend = value;
  4925. this._isAlphaBlendDirty = true;
  4926. },
  4927. enumerable: true,
  4928. configurable: true
  4929. });
  4930. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4931. if (this._blendFunctionParameters[0] === value0 &&
  4932. this._blendFunctionParameters[1] === value1 &&
  4933. this._blendFunctionParameters[2] === value2 &&
  4934. this._blendFunctionParameters[3] === value3) {
  4935. return;
  4936. }
  4937. this._blendFunctionParameters[0] = value0;
  4938. this._blendFunctionParameters[1] = value1;
  4939. this._blendFunctionParameters[2] = value2;
  4940. this._blendFunctionParameters[3] = value3;
  4941. this._isBlendFunctionParametersDirty = true;
  4942. };
  4943. _AlphaState.prototype.reset = function () {
  4944. this._alphaBlend = false;
  4945. this._blendFunctionParameters[0] = null;
  4946. this._blendFunctionParameters[1] = null;
  4947. this._blendFunctionParameters[2] = null;
  4948. this._blendFunctionParameters[3] = null;
  4949. this._isAlphaBlendDirty = true;
  4950. this._isBlendFunctionParametersDirty = false;
  4951. };
  4952. _AlphaState.prototype.apply = function (gl) {
  4953. if (!this.isDirty) {
  4954. return;
  4955. }
  4956. // Alpha blend
  4957. if (this._isAlphaBlendDirty) {
  4958. if (this._alphaBlend) {
  4959. gl.enable(gl.BLEND);
  4960. }
  4961. else {
  4962. gl.disable(gl.BLEND);
  4963. }
  4964. this._isAlphaBlendDirty = false;
  4965. }
  4966. // Alpha function
  4967. if (this._isBlendFunctionParametersDirty) {
  4968. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4969. this._isBlendFunctionParametersDirty = false;
  4970. }
  4971. };
  4972. return _AlphaState;
  4973. })();
  4974. Internals._AlphaState = _AlphaState;
  4975. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4976. })(BABYLON || (BABYLON = {}));
  4977. var BABYLON;
  4978. (function (BABYLON) {
  4979. var Internals;
  4980. (function (Internals) {
  4981. var _DepthCullingState = (function () {
  4982. function _DepthCullingState() {
  4983. this._isDepthTestDirty = false;
  4984. this._isDepthMaskDirty = false;
  4985. this._isDepthFuncDirty = false;
  4986. this._isCullFaceDirty = false;
  4987. this._isCullDirty = false;
  4988. this._isZOffsetDirty = false;
  4989. }
  4990. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4991. get: function () {
  4992. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4993. },
  4994. enumerable: true,
  4995. configurable: true
  4996. });
  4997. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4998. get: function () {
  4999. return this._zOffset;
  5000. },
  5001. set: function (value) {
  5002. if (this._zOffset === value) {
  5003. return;
  5004. }
  5005. this._zOffset = value;
  5006. this._isZOffsetDirty = true;
  5007. },
  5008. enumerable: true,
  5009. configurable: true
  5010. });
  5011. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5012. get: function () {
  5013. return this._cullFace;
  5014. },
  5015. set: function (value) {
  5016. if (this._cullFace === value) {
  5017. return;
  5018. }
  5019. this._cullFace = value;
  5020. this._isCullFaceDirty = true;
  5021. },
  5022. enumerable: true,
  5023. configurable: true
  5024. });
  5025. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5026. get: function () {
  5027. return this._cull;
  5028. },
  5029. set: function (value) {
  5030. if (this._cull === value) {
  5031. return;
  5032. }
  5033. this._cull = value;
  5034. this._isCullDirty = true;
  5035. },
  5036. enumerable: true,
  5037. configurable: true
  5038. });
  5039. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5040. get: function () {
  5041. return this._depthFunc;
  5042. },
  5043. set: function (value) {
  5044. if (this._depthFunc === value) {
  5045. return;
  5046. }
  5047. this._depthFunc = value;
  5048. this._isDepthFuncDirty = true;
  5049. },
  5050. enumerable: true,
  5051. configurable: true
  5052. });
  5053. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5054. get: function () {
  5055. return this._depthMask;
  5056. },
  5057. set: function (value) {
  5058. if (this._depthMask === value) {
  5059. return;
  5060. }
  5061. this._depthMask = value;
  5062. this._isDepthMaskDirty = true;
  5063. },
  5064. enumerable: true,
  5065. configurable: true
  5066. });
  5067. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5068. get: function () {
  5069. return this._depthTest;
  5070. },
  5071. set: function (value) {
  5072. if (this._depthTest === value) {
  5073. return;
  5074. }
  5075. this._depthTest = value;
  5076. this._isDepthTestDirty = true;
  5077. },
  5078. enumerable: true,
  5079. configurable: true
  5080. });
  5081. _DepthCullingState.prototype.reset = function () {
  5082. this._depthMask = true;
  5083. this._depthTest = true;
  5084. this._depthFunc = null;
  5085. this._cull = null;
  5086. this._cullFace = null;
  5087. this._zOffset = 0;
  5088. this._isDepthTestDirty = true;
  5089. this._isDepthMaskDirty = true;
  5090. this._isDepthFuncDirty = false;
  5091. this._isCullFaceDirty = false;
  5092. this._isCullDirty = false;
  5093. this._isZOffsetDirty = false;
  5094. };
  5095. _DepthCullingState.prototype.apply = function (gl) {
  5096. if (!this.isDirty) {
  5097. return;
  5098. }
  5099. // Cull
  5100. if (this._isCullDirty) {
  5101. if (this.cull) {
  5102. gl.enable(gl.CULL_FACE);
  5103. }
  5104. else {
  5105. gl.disable(gl.CULL_FACE);
  5106. }
  5107. this._isCullDirty = false;
  5108. }
  5109. // Cull face
  5110. if (this._isCullFaceDirty) {
  5111. gl.cullFace(this.cullFace);
  5112. this._isCullFaceDirty = false;
  5113. }
  5114. // Depth mask
  5115. if (this._isDepthMaskDirty) {
  5116. gl.depthMask(this.depthMask);
  5117. this._isDepthMaskDirty = false;
  5118. }
  5119. // Depth test
  5120. if (this._isDepthTestDirty) {
  5121. if (this.depthTest) {
  5122. gl.enable(gl.DEPTH_TEST);
  5123. }
  5124. else {
  5125. gl.disable(gl.DEPTH_TEST);
  5126. }
  5127. this._isDepthTestDirty = false;
  5128. }
  5129. // Depth func
  5130. if (this._isDepthFuncDirty) {
  5131. gl.depthFunc(this.depthFunc);
  5132. this._isDepthFuncDirty = false;
  5133. }
  5134. // zOffset
  5135. if (this._isZOffsetDirty) {
  5136. if (this.zOffset) {
  5137. gl.enable(gl.POLYGON_OFFSET_FILL);
  5138. gl.polygonOffset(this.zOffset, 0);
  5139. }
  5140. else {
  5141. gl.disable(gl.POLYGON_OFFSET_FILL);
  5142. }
  5143. this._isZOffsetDirty = false;
  5144. }
  5145. };
  5146. return _DepthCullingState;
  5147. })();
  5148. Internals._DepthCullingState = _DepthCullingState;
  5149. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5150. })(BABYLON || (BABYLON = {}));
  5151. var BABYLON;
  5152. (function (BABYLON) {
  5153. var compileShader = function (gl, source, type, defines) {
  5154. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5155. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5156. gl.compileShader(shader);
  5157. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5158. throw new Error(gl.getShaderInfoLog(shader));
  5159. }
  5160. return shader;
  5161. };
  5162. var getWebGLTextureType = function (gl, type) {
  5163. var textureType = gl.UNSIGNED_BYTE;
  5164. if (type === Engine.TEXTURETYPE_FLOAT)
  5165. textureType = gl.FLOAT;
  5166. return textureType;
  5167. };
  5168. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5169. var magFilter = gl.NEAREST;
  5170. var minFilter = gl.NEAREST;
  5171. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5172. magFilter = gl.LINEAR;
  5173. if (generateMipMaps) {
  5174. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5175. }
  5176. else {
  5177. minFilter = gl.LINEAR;
  5178. }
  5179. }
  5180. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5181. magFilter = gl.LINEAR;
  5182. if (generateMipMaps) {
  5183. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5184. }
  5185. else {
  5186. minFilter = gl.LINEAR;
  5187. }
  5188. }
  5189. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5190. magFilter = gl.NEAREST;
  5191. if (generateMipMaps) {
  5192. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5193. }
  5194. else {
  5195. minFilter = gl.NEAREST;
  5196. }
  5197. }
  5198. return {
  5199. min: minFilter,
  5200. mag: magFilter
  5201. };
  5202. };
  5203. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5205. var engine = scene.getEngine();
  5206. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5207. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5208. gl.bindTexture(gl.TEXTURE_2D, texture);
  5209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5210. texture._baseWidth = width;
  5211. texture._baseHeight = height;
  5212. texture._width = potWidth;
  5213. texture._height = potHeight;
  5214. texture.isReady = true;
  5215. processFunction(potWidth, potHeight);
  5216. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5219. if (!noMipmap && !isCompressed) {
  5220. gl.generateMipmap(gl.TEXTURE_2D);
  5221. }
  5222. gl.bindTexture(gl.TEXTURE_2D, null);
  5223. engine.resetTextureCache();
  5224. scene._removePendingData(texture);
  5225. if (onLoad) {
  5226. onLoad();
  5227. }
  5228. };
  5229. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5230. var img;
  5231. var onload = function () {
  5232. loadedImages[index] = img;
  5233. loadedImages._internalCount++;
  5234. scene._removePendingData(img);
  5235. if (loadedImages._internalCount === 6) {
  5236. onfinish(loadedImages);
  5237. }
  5238. };
  5239. var onerror = function () {
  5240. scene._removePendingData(img);
  5241. };
  5242. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5243. scene._addPendingData(img);
  5244. };
  5245. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5246. var loadedImages = [];
  5247. loadedImages._internalCount = 0;
  5248. for (var index = 0; index < 6; index++) {
  5249. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5250. }
  5251. };
  5252. var EngineCapabilities = (function () {
  5253. function EngineCapabilities() {
  5254. }
  5255. return EngineCapabilities;
  5256. })();
  5257. BABYLON.EngineCapabilities = EngineCapabilities;
  5258. /**
  5259. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5260. */
  5261. var Engine = (function () {
  5262. /**
  5263. * @constructor
  5264. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5265. * @param {boolean} [antialias] - enable antialias
  5266. * @param options - further options to be sent to the getContext function
  5267. */
  5268. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5269. var _this = this;
  5270. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5271. // Public members
  5272. this.isFullscreen = false;
  5273. this.isPointerLock = false;
  5274. this.cullBackFaces = true;
  5275. this.renderEvenInBackground = true;
  5276. // To enable/disable IDB support and avoid XHR on .manifest
  5277. this.enableOfflineSupport = true;
  5278. this.scenes = new Array();
  5279. this._windowIsBackground = false;
  5280. this._webGLVersion = "1.0";
  5281. this._drawCalls = 0;
  5282. this._renderingQueueLaunched = false;
  5283. this._activeRenderLoops = [];
  5284. // FPS
  5285. this.fpsRange = 60;
  5286. this.previousFramesDuration = [];
  5287. this.fps = 60;
  5288. this.deltaTime = 0;
  5289. // States
  5290. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5291. this._alphaState = new BABYLON.Internals._AlphaState();
  5292. this._alphaMode = Engine.ALPHA_DISABLE;
  5293. // Cache
  5294. this._loadedTexturesCache = new Array();
  5295. this._maxTextureChannels = 16;
  5296. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5297. this._compiledEffects = {};
  5298. this._uintIndicesCurrentlySet = false;
  5299. this._renderingCanvas = canvas;
  5300. options = options || {};
  5301. options.antialias = antialias;
  5302. if (options.preserveDrawingBuffer === undefined) {
  5303. options.preserveDrawingBuffer = false;
  5304. }
  5305. // GL
  5306. //try {
  5307. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5308. // if (this._gl) {
  5309. // this._webGLVersion = "2.0";
  5310. // }
  5311. //} catch (e) {
  5312. // // Do nothing
  5313. //}
  5314. if (!this._gl) {
  5315. try {
  5316. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5317. }
  5318. catch (e) {
  5319. throw new Error("WebGL not supported");
  5320. }
  5321. }
  5322. if (!this._gl) {
  5323. throw new Error("WebGL not supported");
  5324. }
  5325. this._onBlur = function () {
  5326. _this._windowIsBackground = true;
  5327. };
  5328. this._onFocus = function () {
  5329. _this._windowIsBackground = false;
  5330. };
  5331. window.addEventListener("blur", this._onBlur);
  5332. window.addEventListener("focus", this._onFocus);
  5333. // Viewport
  5334. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5335. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5336. this.resize();
  5337. // Caps
  5338. this._caps = new EngineCapabilities();
  5339. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5340. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5341. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5342. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5343. // Infos
  5344. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5345. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5346. if (rendererInfo != null) {
  5347. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5348. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5349. }
  5350. if (!this._glVendor) {
  5351. this._glVendor = "Unknown vendor";
  5352. }
  5353. if (!this._glRenderer) {
  5354. this._glRenderer = "Unknown renderer";
  5355. }
  5356. // Extensions
  5357. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5358. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5359. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5360. 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');
  5361. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5362. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5363. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5364. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5365. this._caps.highPrecisionShaderSupported = true;
  5366. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5367. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5368. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5369. if (this._gl.getShaderPrecisionFormat) {
  5370. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5371. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5372. }
  5373. // Depth buffer
  5374. this.setDepthBuffer(true);
  5375. this.setDepthFunctionToLessOrEqual();
  5376. this.setDepthWrite(true);
  5377. // Fullscreen
  5378. this._onFullscreenChange = function () {
  5379. if (document.fullscreen !== undefined) {
  5380. _this.isFullscreen = document.fullscreen;
  5381. }
  5382. else if (document.mozFullScreen !== undefined) {
  5383. _this.isFullscreen = document.mozFullScreen;
  5384. }
  5385. else if (document.webkitIsFullScreen !== undefined) {
  5386. _this.isFullscreen = document.webkitIsFullScreen;
  5387. }
  5388. else if (document.msIsFullScreen !== undefined) {
  5389. _this.isFullscreen = document.msIsFullScreen;
  5390. }
  5391. // Pointer lock
  5392. if (_this.isFullscreen && _this._pointerLockRequested) {
  5393. canvas.requestPointerLock = canvas.requestPointerLock ||
  5394. canvas.msRequestPointerLock ||
  5395. canvas.mozRequestPointerLock ||
  5396. canvas.webkitRequestPointerLock;
  5397. if (canvas.requestPointerLock) {
  5398. canvas.requestPointerLock();
  5399. }
  5400. }
  5401. };
  5402. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5403. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5404. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5405. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5406. // Pointer lock
  5407. this._onPointerLockChange = function () {
  5408. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5409. document.webkitPointerLockElement === canvas ||
  5410. document.msPointerLockElement === canvas ||
  5411. document.pointerLockElement === canvas);
  5412. };
  5413. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5414. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5415. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5416. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5417. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5418. Engine.audioEngine = new BABYLON.AudioEngine();
  5419. }
  5420. //default loading screen
  5421. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5422. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5423. }
  5424. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5425. get: function () {
  5426. return Engine._ALPHA_DISABLE;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5432. get: function () {
  5433. return Engine._ALPHA_ONEONE;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(Engine, "ALPHA_ADD", {
  5439. get: function () {
  5440. return Engine._ALPHA_ADD;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5446. get: function () {
  5447. return Engine._ALPHA_COMBINE;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5453. get: function () {
  5454. return Engine._ALPHA_SUBTRACT;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5460. get: function () {
  5461. return Engine._ALPHA_MULTIPLY;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5467. get: function () {
  5468. return Engine._ALPHA_MAXIMIZED;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5474. get: function () {
  5475. return Engine._DELAYLOADSTATE_NONE;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5481. get: function () {
  5482. return Engine._DELAYLOADSTATE_LOADED;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5488. get: function () {
  5489. return Engine._DELAYLOADSTATE_LOADING;
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5495. get: function () {
  5496. return Engine._DELAYLOADSTATE_NOTLOADED;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5502. get: function () {
  5503. return Engine._TEXTUREFORMAT_ALPHA;
  5504. },
  5505. enumerable: true,
  5506. configurable: true
  5507. });
  5508. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5509. get: function () {
  5510. return Engine._TEXTUREFORMAT_LUMINANCE;
  5511. },
  5512. enumerable: true,
  5513. configurable: true
  5514. });
  5515. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5516. get: function () {
  5517. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5518. },
  5519. enumerable: true,
  5520. configurable: true
  5521. });
  5522. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5523. get: function () {
  5524. return Engine._TEXTUREFORMAT_RGB;
  5525. },
  5526. enumerable: true,
  5527. configurable: true
  5528. });
  5529. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5530. get: function () {
  5531. return Engine._TEXTUREFORMAT_RGBA;
  5532. },
  5533. enumerable: true,
  5534. configurable: true
  5535. });
  5536. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5537. get: function () {
  5538. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5539. },
  5540. enumerable: true,
  5541. configurable: true
  5542. });
  5543. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5544. get: function () {
  5545. return Engine._TEXTURETYPE_FLOAT;
  5546. },
  5547. enumerable: true,
  5548. configurable: true
  5549. });
  5550. Object.defineProperty(Engine, "Version", {
  5551. get: function () {
  5552. return "2.4.0-alpha";
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5558. get: function () {
  5559. return this._webGLVersion;
  5560. },
  5561. enumerable: true,
  5562. configurable: true
  5563. });
  5564. Engine.prototype._prepareWorkingCanvas = function () {
  5565. if (this._workingCanvas) {
  5566. return;
  5567. }
  5568. this._workingCanvas = document.createElement("canvas");
  5569. this._workingContext = this._workingCanvas.getContext("2d");
  5570. };
  5571. Engine.prototype.resetTextureCache = function () {
  5572. for (var index = 0; index < this._maxTextureChannels; index++) {
  5573. this._activeTexturesCache[index] = null;
  5574. }
  5575. };
  5576. Engine.prototype.getGlInfo = function () {
  5577. return {
  5578. vendor: this._glVendor,
  5579. renderer: this._glRenderer,
  5580. version: this._glVersion
  5581. };
  5582. };
  5583. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5584. if (useScreen === void 0) { useScreen = false; }
  5585. var viewport = camera.viewport;
  5586. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5587. };
  5588. Engine.prototype.getRenderWidth = function (useScreen) {
  5589. if (useScreen === void 0) { useScreen = false; }
  5590. if (!useScreen && this._currentRenderTarget) {
  5591. return this._currentRenderTarget._width;
  5592. }
  5593. return this._renderingCanvas.width;
  5594. };
  5595. Engine.prototype.getRenderHeight = function (useScreen) {
  5596. if (useScreen === void 0) { useScreen = false; }
  5597. if (!useScreen && this._currentRenderTarget) {
  5598. return this._currentRenderTarget._height;
  5599. }
  5600. return this._renderingCanvas.height;
  5601. };
  5602. Engine.prototype.getRenderingCanvas = function () {
  5603. return this._renderingCanvas;
  5604. };
  5605. Engine.prototype.getRenderingCanvasClientRect = function () {
  5606. return this._renderingCanvas.getBoundingClientRect();
  5607. };
  5608. Engine.prototype.setHardwareScalingLevel = function (level) {
  5609. this._hardwareScalingLevel = level;
  5610. this.resize();
  5611. };
  5612. Engine.prototype.getHardwareScalingLevel = function () {
  5613. return this._hardwareScalingLevel;
  5614. };
  5615. Engine.prototype.getLoadedTexturesCache = function () {
  5616. return this._loadedTexturesCache;
  5617. };
  5618. Engine.prototype.getCaps = function () {
  5619. return this._caps;
  5620. };
  5621. Object.defineProperty(Engine.prototype, "drawCalls", {
  5622. get: function () {
  5623. return this._drawCalls;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. // Methods
  5629. Engine.prototype.resetDrawCalls = function () {
  5630. this._drawCalls = 0;
  5631. };
  5632. Engine.prototype.setDepthFunctionToGreater = function () {
  5633. this._depthCullingState.depthFunc = this._gl.GREATER;
  5634. };
  5635. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5636. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5637. };
  5638. Engine.prototype.setDepthFunctionToLess = function () {
  5639. this._depthCullingState.depthFunc = this._gl.LESS;
  5640. };
  5641. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5642. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5643. };
  5644. /**
  5645. * stop executing a render loop function and remove it from the execution array
  5646. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5647. */
  5648. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5649. if (!renderFunction) {
  5650. this._activeRenderLoops = [];
  5651. return;
  5652. }
  5653. var index = this._activeRenderLoops.indexOf(renderFunction);
  5654. if (index >= 0) {
  5655. this._activeRenderLoops.splice(index, 1);
  5656. }
  5657. };
  5658. Engine.prototype._renderLoop = function () {
  5659. var shouldRender = true;
  5660. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5661. shouldRender = false;
  5662. }
  5663. if (shouldRender) {
  5664. // Start new frame
  5665. this.beginFrame();
  5666. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5667. var renderFunction = this._activeRenderLoops[index];
  5668. renderFunction();
  5669. }
  5670. // Present
  5671. this.endFrame();
  5672. }
  5673. if (this._activeRenderLoops.length > 0) {
  5674. // Register new frame
  5675. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5676. }
  5677. else {
  5678. this._renderingQueueLaunched = false;
  5679. }
  5680. };
  5681. /**
  5682. * Register and execute a render loop. The engine can have more than one render function.
  5683. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5684. * @example
  5685. * engine.runRenderLoop(function () {
  5686. * scene.render()
  5687. * })
  5688. */
  5689. Engine.prototype.runRenderLoop = function (renderFunction) {
  5690. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5691. return;
  5692. }
  5693. this._activeRenderLoops.push(renderFunction);
  5694. if (!this._renderingQueueLaunched) {
  5695. this._renderingQueueLaunched = true;
  5696. this._bindedRenderFunction = this._renderLoop.bind(this);
  5697. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5698. }
  5699. };
  5700. /**
  5701. * Toggle full screen mode.
  5702. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5703. */
  5704. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5705. if (this.isFullscreen) {
  5706. BABYLON.Tools.ExitFullscreen();
  5707. }
  5708. else {
  5709. this._pointerLockRequested = requestPointerLock;
  5710. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5711. }
  5712. };
  5713. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5714. this.applyStates();
  5715. if (backBuffer) {
  5716. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5717. }
  5718. if (depthStencil && this._depthCullingState.depthMask) {
  5719. this._gl.clearDepth(1.0);
  5720. }
  5721. var mode = 0;
  5722. if (backBuffer) {
  5723. mode |= this._gl.COLOR_BUFFER_BIT;
  5724. }
  5725. if (depthStencil && this._depthCullingState.depthMask) {
  5726. mode |= this._gl.DEPTH_BUFFER_BIT;
  5727. }
  5728. this._gl.clear(mode);
  5729. };
  5730. /**
  5731. * Set the WebGL's viewport
  5732. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5733. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5734. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5735. */
  5736. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5737. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5738. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5739. var x = viewport.x || 0;
  5740. var y = viewport.y || 0;
  5741. this._cachedViewport = viewport;
  5742. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5743. };
  5744. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5745. this._cachedViewport = null;
  5746. this._gl.viewport(x, y, width, height);
  5747. };
  5748. Engine.prototype.beginFrame = function () {
  5749. this._measureFps();
  5750. };
  5751. Engine.prototype.endFrame = function () {
  5752. //this.flushFramebuffer();
  5753. };
  5754. /**
  5755. * resize the view according to the canvas' size.
  5756. * @example
  5757. * window.addEventListener("resize", function () {
  5758. * engine.resize();
  5759. * });
  5760. */
  5761. Engine.prototype.resize = function () {
  5762. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5763. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5764. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5765. for (var index = 0; index < this.scenes.length; index++) {
  5766. var scene = this.scenes[index];
  5767. if (scene.debugLayer.isVisible()) {
  5768. scene.debugLayer._syncPositions();
  5769. }
  5770. }
  5771. };
  5772. /**
  5773. * force a specific size of the canvas
  5774. * @param {number} width - the new canvas' width
  5775. * @param {number} height - the new canvas' height
  5776. */
  5777. Engine.prototype.setSize = function (width, height) {
  5778. this._renderingCanvas.width = width;
  5779. this._renderingCanvas.height = height;
  5780. for (var index = 0; index < this.scenes.length; index++) {
  5781. var scene = this.scenes[index];
  5782. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5783. var cam = scene.cameras[camIndex];
  5784. cam._currentRenderId = 0;
  5785. }
  5786. }
  5787. };
  5788. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5789. this._currentRenderTarget = texture;
  5790. var gl = this._gl;
  5791. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5792. if (texture.isCube) {
  5793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5794. }
  5795. else {
  5796. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5797. }
  5798. this._gl.viewport(0, 0, texture._width, texture._height);
  5799. this.wipeCaches();
  5800. };
  5801. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5802. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5803. this._currentRenderTarget = null;
  5804. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5805. var gl = this._gl;
  5806. gl.bindTexture(gl.TEXTURE_2D, texture);
  5807. gl.generateMipmap(gl.TEXTURE_2D);
  5808. gl.bindTexture(gl.TEXTURE_2D, null);
  5809. }
  5810. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5811. };
  5812. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5813. if (texture.generateMipMaps) {
  5814. var gl = this._gl;
  5815. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5816. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5817. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5818. }
  5819. };
  5820. Engine.prototype.flushFramebuffer = function () {
  5821. this._gl.flush();
  5822. };
  5823. Engine.prototype.restoreDefaultFramebuffer = function () {
  5824. this._currentRenderTarget = null;
  5825. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5826. this.setViewport(this._cachedViewport);
  5827. this.wipeCaches();
  5828. };
  5829. // VBOs
  5830. Engine.prototype._resetVertexBufferBinding = function () {
  5831. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5832. this._cachedVertexBuffers = null;
  5833. };
  5834. Engine.prototype.createVertexBuffer = function (vertices) {
  5835. var vbo = this._gl.createBuffer();
  5836. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5837. if (vertices instanceof Float32Array) {
  5838. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5839. }
  5840. else {
  5841. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5842. }
  5843. this._resetVertexBufferBinding();
  5844. vbo.references = 1;
  5845. return vbo;
  5846. };
  5847. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5848. var vbo = this._gl.createBuffer();
  5849. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5850. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5851. this._resetVertexBufferBinding();
  5852. vbo.references = 1;
  5853. return vbo;
  5854. };
  5855. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5856. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5857. if (offset === undefined) {
  5858. offset = 0;
  5859. }
  5860. if (vertices instanceof Float32Array) {
  5861. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5862. }
  5863. else {
  5864. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5865. }
  5866. this._resetVertexBufferBinding();
  5867. };
  5868. Engine.prototype._resetIndexBufferBinding = function () {
  5869. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5870. this._cachedIndexBuffer = null;
  5871. };
  5872. Engine.prototype.createIndexBuffer = function (indices) {
  5873. var vbo = this._gl.createBuffer();
  5874. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5875. // Check for 32 bits indices
  5876. var arrayBuffer;
  5877. var need32Bits = false;
  5878. if (this._caps.uintIndices) {
  5879. for (var index = 0; index < indices.length; index++) {
  5880. if (indices[index] > 65535) {
  5881. need32Bits = true;
  5882. break;
  5883. }
  5884. }
  5885. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5886. }
  5887. else {
  5888. arrayBuffer = new Uint16Array(indices);
  5889. }
  5890. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5891. this._resetIndexBufferBinding();
  5892. vbo.references = 1;
  5893. vbo.is32Bits = need32Bits;
  5894. return vbo;
  5895. };
  5896. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5897. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5898. this._cachedVertexBuffers = vertexBuffer;
  5899. this._cachedEffectForVertexBuffers = effect;
  5900. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5901. var offset = 0;
  5902. for (var index = 0; index < vertexDeclaration.length; index++) {
  5903. var order = effect.getAttributeLocation(index);
  5904. if (order >= 0) {
  5905. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5906. }
  5907. offset += vertexDeclaration[index] * 4;
  5908. }
  5909. }
  5910. if (this._cachedIndexBuffer !== indexBuffer) {
  5911. this._cachedIndexBuffer = indexBuffer;
  5912. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5913. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5914. }
  5915. };
  5916. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5917. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5918. this._cachedVertexBuffers = vertexBuffers;
  5919. this._cachedEffectForVertexBuffers = effect;
  5920. var attributes = effect.getAttributesNames();
  5921. for (var index = 0; index < attributes.length; index++) {
  5922. var order = effect.getAttributeLocation(index);
  5923. if (order >= 0) {
  5924. var vertexBuffer = vertexBuffers[attributes[index]];
  5925. if (!vertexBuffer) {
  5926. continue;
  5927. }
  5928. var stride = vertexBuffer.getStrideSize();
  5929. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5930. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5931. }
  5932. }
  5933. }
  5934. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5935. this._cachedIndexBuffer = indexBuffer;
  5936. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5937. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5938. }
  5939. };
  5940. Engine.prototype._releaseBuffer = function (buffer) {
  5941. buffer.references--;
  5942. if (buffer.references === 0) {
  5943. this._gl.deleteBuffer(buffer);
  5944. return true;
  5945. }
  5946. return false;
  5947. };
  5948. Engine.prototype.createInstancesBuffer = function (capacity) {
  5949. var buffer = this._gl.createBuffer();
  5950. buffer.capacity = capacity;
  5951. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5952. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5953. return buffer;
  5954. };
  5955. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5956. this._gl.deleteBuffer(buffer);
  5957. };
  5958. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5959. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5960. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5961. for (var index = 0; index < 4; index++) {
  5962. var offsetLocation = offsetLocations[index];
  5963. this._gl.enableVertexAttribArray(offsetLocation);
  5964. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5965. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5966. }
  5967. };
  5968. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5969. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5970. for (var index = 0; index < 4; index++) {
  5971. var offsetLocation = offsetLocations[index];
  5972. this._gl.disableVertexAttribArray(offsetLocation);
  5973. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5974. }
  5975. };
  5976. Engine.prototype.applyStates = function () {
  5977. this._depthCullingState.apply(this._gl);
  5978. this._alphaState.apply(this._gl);
  5979. };
  5980. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5981. // Apply states
  5982. this.applyStates();
  5983. this._drawCalls++;
  5984. // Render
  5985. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5986. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5987. if (instancesCount) {
  5988. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5989. return;
  5990. }
  5991. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5992. };
  5993. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5994. // Apply states
  5995. this.applyStates();
  5996. this._drawCalls++;
  5997. if (instancesCount) {
  5998. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5999. return;
  6000. }
  6001. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6002. };
  6003. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6004. // Apply states
  6005. this.applyStates();
  6006. this._drawCalls++;
  6007. if (instancesCount) {
  6008. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6009. return;
  6010. }
  6011. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6012. };
  6013. // Shaders
  6014. Engine.prototype._releaseEffect = function (effect) {
  6015. if (this._compiledEffects[effect._key]) {
  6016. delete this._compiledEffects[effect._key];
  6017. if (effect.getProgram()) {
  6018. this._gl.deleteProgram(effect.getProgram());
  6019. }
  6020. }
  6021. };
  6022. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6023. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6024. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6025. var name = vertex + "+" + fragment + "@" + defines;
  6026. if (this._compiledEffects[name]) {
  6027. return this._compiledEffects[name];
  6028. }
  6029. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6030. effect._key = name;
  6031. this._compiledEffects[name] = effect;
  6032. return effect;
  6033. };
  6034. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6035. if (uniformsNames === void 0) { uniformsNames = []; }
  6036. if (samplers === void 0) { samplers = []; }
  6037. if (defines === void 0) { defines = ""; }
  6038. return this.createEffect({
  6039. vertex: "particles",
  6040. fragmentElement: fragmentName
  6041. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6042. };
  6043. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6044. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6045. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6046. var shaderProgram = this._gl.createProgram();
  6047. this._gl.attachShader(shaderProgram, vertexShader);
  6048. this._gl.attachShader(shaderProgram, fragmentShader);
  6049. this._gl.linkProgram(shaderProgram);
  6050. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6051. if (!linked) {
  6052. var error = this._gl.getProgramInfoLog(shaderProgram);
  6053. if (error) {
  6054. throw new Error(error);
  6055. }
  6056. }
  6057. this._gl.deleteShader(vertexShader);
  6058. this._gl.deleteShader(fragmentShader);
  6059. return shaderProgram;
  6060. };
  6061. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6062. var results = [];
  6063. for (var index = 0; index < uniformsNames.length; index++) {
  6064. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6065. }
  6066. return results;
  6067. };
  6068. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6069. var results = [];
  6070. for (var index = 0; index < attributesNames.length; index++) {
  6071. try {
  6072. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6073. }
  6074. catch (e) {
  6075. results.push(-1);
  6076. }
  6077. }
  6078. return results;
  6079. };
  6080. Engine.prototype.enableEffect = function (effect) {
  6081. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6082. if (effect && effect.onBind) {
  6083. effect.onBind(effect);
  6084. }
  6085. return;
  6086. }
  6087. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6088. // Use program
  6089. this._gl.useProgram(effect.getProgram());
  6090. for (var i in this._vertexAttribArrays) {
  6091. //make sure this is a number)
  6092. var iAsNumber = +i;
  6093. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6094. continue;
  6095. }
  6096. this._vertexAttribArrays[iAsNumber] = false;
  6097. this._gl.disableVertexAttribArray(iAsNumber);
  6098. }
  6099. var attributesCount = effect.getAttributesCount();
  6100. for (var index = 0; index < attributesCount; index++) {
  6101. // Attributes
  6102. var order = effect.getAttributeLocation(index);
  6103. if (order >= 0) {
  6104. this._vertexAttribArrays[order] = true;
  6105. this._gl.enableVertexAttribArray(order);
  6106. }
  6107. }
  6108. this._currentEffect = effect;
  6109. if (effect.onBind) {
  6110. effect.onBind(effect);
  6111. }
  6112. };
  6113. Engine.prototype.setArray = function (uniform, array) {
  6114. if (!uniform)
  6115. return;
  6116. this._gl.uniform1fv(uniform, array);
  6117. };
  6118. Engine.prototype.setArray2 = function (uniform, array) {
  6119. if (!uniform || array.length % 2 !== 0)
  6120. return;
  6121. this._gl.uniform2fv(uniform, array);
  6122. };
  6123. Engine.prototype.setArray3 = function (uniform, array) {
  6124. if (!uniform || array.length % 3 !== 0)
  6125. return;
  6126. this._gl.uniform3fv(uniform, array);
  6127. };
  6128. Engine.prototype.setArray4 = function (uniform, array) {
  6129. if (!uniform || array.length % 4 !== 0)
  6130. return;
  6131. this._gl.uniform4fv(uniform, array);
  6132. };
  6133. Engine.prototype.setMatrices = function (uniform, matrices) {
  6134. if (!uniform)
  6135. return;
  6136. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6137. };
  6138. Engine.prototype.setMatrix = function (uniform, matrix) {
  6139. if (!uniform)
  6140. return;
  6141. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6142. };
  6143. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6144. if (!uniform)
  6145. return;
  6146. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6147. };
  6148. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6149. if (!uniform)
  6150. return;
  6151. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6152. };
  6153. Engine.prototype.setFloat = function (uniform, value) {
  6154. if (!uniform)
  6155. return;
  6156. this._gl.uniform1f(uniform, value);
  6157. };
  6158. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6159. if (!uniform)
  6160. return;
  6161. this._gl.uniform2f(uniform, x, y);
  6162. };
  6163. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6164. if (!uniform)
  6165. return;
  6166. this._gl.uniform3f(uniform, x, y, z);
  6167. };
  6168. Engine.prototype.setBool = function (uniform, bool) {
  6169. if (!uniform)
  6170. return;
  6171. this._gl.uniform1i(uniform, bool);
  6172. };
  6173. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6174. if (!uniform)
  6175. return;
  6176. this._gl.uniform4f(uniform, x, y, z, w);
  6177. };
  6178. Engine.prototype.setColor3 = function (uniform, color3) {
  6179. if (!uniform)
  6180. return;
  6181. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6182. };
  6183. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6184. if (!uniform)
  6185. return;
  6186. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6187. };
  6188. // States
  6189. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6190. if (zOffset === void 0) { zOffset = 0; }
  6191. if (reverseSide === void 0) { reverseSide = false; }
  6192. // Culling
  6193. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6194. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6195. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6196. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6197. if (culling) {
  6198. this._depthCullingState.cullFace = cullFace;
  6199. this._depthCullingState.cull = true;
  6200. }
  6201. else {
  6202. this._depthCullingState.cull = false;
  6203. }
  6204. }
  6205. // Z offset
  6206. this._depthCullingState.zOffset = zOffset;
  6207. };
  6208. Engine.prototype.setDepthBuffer = function (enable) {
  6209. this._depthCullingState.depthTest = enable;
  6210. };
  6211. Engine.prototype.getDepthWrite = function () {
  6212. return this._depthCullingState.depthMask;
  6213. };
  6214. Engine.prototype.setDepthWrite = function (enable) {
  6215. this._depthCullingState.depthMask = enable;
  6216. };
  6217. Engine.prototype.setColorWrite = function (enable) {
  6218. this._gl.colorMask(enable, enable, enable, enable);
  6219. };
  6220. Engine.prototype.setAlphaMode = function (mode) {
  6221. if (this._alphaMode === mode) {
  6222. return;
  6223. }
  6224. switch (mode) {
  6225. case Engine.ALPHA_DISABLE:
  6226. this.setDepthWrite(true);
  6227. this._alphaState.alphaBlend = false;
  6228. break;
  6229. case Engine.ALPHA_COMBINE:
  6230. this.setDepthWrite(false);
  6231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6232. this._alphaState.alphaBlend = true;
  6233. break;
  6234. case Engine.ALPHA_ONEONE:
  6235. this.setDepthWrite(false);
  6236. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6237. this._alphaState.alphaBlend = true;
  6238. break;
  6239. case Engine.ALPHA_ADD:
  6240. this.setDepthWrite(false);
  6241. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6242. this._alphaState.alphaBlend = true;
  6243. break;
  6244. case Engine.ALPHA_SUBTRACT:
  6245. this.setDepthWrite(false);
  6246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6247. this._alphaState.alphaBlend = true;
  6248. break;
  6249. case Engine.ALPHA_MULTIPLY:
  6250. this.setDepthWrite(false);
  6251. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6252. this._alphaState.alphaBlend = true;
  6253. break;
  6254. case Engine.ALPHA_MAXIMIZED:
  6255. this.setDepthWrite(false);
  6256. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6257. this._alphaState.alphaBlend = true;
  6258. break;
  6259. }
  6260. this._alphaMode = mode;
  6261. };
  6262. Engine.prototype.getAlphaMode = function () {
  6263. return this._alphaMode;
  6264. };
  6265. Engine.prototype.setAlphaTesting = function (enable) {
  6266. this._alphaTest = enable;
  6267. };
  6268. Engine.prototype.getAlphaTesting = function () {
  6269. return this._alphaTest;
  6270. };
  6271. // Textures
  6272. Engine.prototype.wipeCaches = function () {
  6273. this.resetTextureCache();
  6274. this._currentEffect = null;
  6275. this._depthCullingState.reset();
  6276. this._alphaState.reset();
  6277. this._cachedVertexBuffers = null;
  6278. this._cachedIndexBuffer = null;
  6279. this._cachedEffectForVertexBuffers = null;
  6280. };
  6281. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6282. var gl = this._gl;
  6283. gl.bindTexture(gl.TEXTURE_2D, texture);
  6284. var magFilter = gl.NEAREST;
  6285. var minFilter = gl.NEAREST;
  6286. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6287. magFilter = gl.LINEAR;
  6288. minFilter = gl.LINEAR;
  6289. }
  6290. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6291. magFilter = gl.LINEAR;
  6292. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6293. }
  6294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6296. gl.bindTexture(gl.TEXTURE_2D, null);
  6297. texture.samplingMode = samplingMode;
  6298. };
  6299. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6300. var _this = this;
  6301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6302. if (onLoad === void 0) { onLoad = null; }
  6303. if (onError === void 0) { onError = null; }
  6304. if (buffer === void 0) { buffer = null; }
  6305. var texture = this._gl.createTexture();
  6306. var extension;
  6307. var fromData = false;
  6308. if (url.substr(0, 5) === "data:") {
  6309. fromData = true;
  6310. }
  6311. if (!fromData)
  6312. extension = url.substr(url.length - 4, 4).toLowerCase();
  6313. else {
  6314. var oldUrl = url;
  6315. fromData = oldUrl.split(':');
  6316. url = oldUrl;
  6317. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6318. }
  6319. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6320. var isTGA = (extension === ".tga");
  6321. scene._addPendingData(texture);
  6322. texture.url = url;
  6323. texture.noMipmap = noMipmap;
  6324. texture.references = 1;
  6325. texture.samplingMode = samplingMode;
  6326. this._loadedTexturesCache.push(texture);
  6327. var onerror = function () {
  6328. scene._removePendingData(texture);
  6329. if (onError) {
  6330. onError();
  6331. }
  6332. };
  6333. var callback;
  6334. if (isTGA) {
  6335. callback = function (arrayBuffer) {
  6336. var data = new Uint8Array(arrayBuffer);
  6337. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6338. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6339. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6340. }, onLoad, samplingMode);
  6341. };
  6342. if (!(fromData instanceof Array))
  6343. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6344. callback(arrayBuffer);
  6345. }, onerror, scene.database, true);
  6346. else
  6347. callback(buffer);
  6348. }
  6349. else if (isDDS) {
  6350. callback = function (data) {
  6351. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6352. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6353. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6354. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6355. }, onLoad, samplingMode);
  6356. };
  6357. if (!(fromData instanceof Array))
  6358. BABYLON.Tools.LoadFile(url, function (data) {
  6359. callback(data);
  6360. }, onerror, scene.database, true);
  6361. else
  6362. callback(buffer);
  6363. }
  6364. else {
  6365. var onload = function (img) {
  6366. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6367. var isPot = (img.width === potWidth && img.height === potHeight);
  6368. if (!isPot) {
  6369. _this._prepareWorkingCanvas();
  6370. _this._workingCanvas.width = potWidth;
  6371. _this._workingCanvas.height = potHeight;
  6372. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6373. _this._workingContext.imageSmoothingEnabled = false;
  6374. _this._workingContext.mozImageSmoothingEnabled = false;
  6375. _this._workingContext.oImageSmoothingEnabled = false;
  6376. _this._workingContext.webkitImageSmoothingEnabled = false;
  6377. _this._workingContext.msImageSmoothingEnabled = false;
  6378. }
  6379. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6380. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6381. _this._workingContext.imageSmoothingEnabled = true;
  6382. _this._workingContext.mozImageSmoothingEnabled = true;
  6383. _this._workingContext.oImageSmoothingEnabled = true;
  6384. _this._workingContext.webkitImageSmoothingEnabled = true;
  6385. _this._workingContext.msImageSmoothingEnabled = true;
  6386. }
  6387. }
  6388. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6389. }, onLoad, samplingMode);
  6390. };
  6391. if (!(fromData instanceof Array))
  6392. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6393. else
  6394. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6395. }
  6396. return texture;
  6397. };
  6398. Engine.prototype._getInternalFormat = function (format) {
  6399. var internalFormat = this._gl.RGBA;
  6400. switch (format) {
  6401. case Engine.TEXTUREFORMAT_ALPHA:
  6402. internalFormat = this._gl.ALPHA;
  6403. break;
  6404. case Engine.TEXTUREFORMAT_LUMINANCE:
  6405. internalFormat = this._gl.LUMINANCE;
  6406. break;
  6407. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6408. internalFormat = this._gl.LUMINANCE_ALPHA;
  6409. break;
  6410. case Engine.TEXTUREFORMAT_RGB:
  6411. internalFormat = this._gl.RGB;
  6412. break;
  6413. case Engine.TEXTUREFORMAT_RGBA:
  6414. internalFormat = this._gl.RGBA;
  6415. break;
  6416. }
  6417. return internalFormat;
  6418. };
  6419. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6420. if (compression === void 0) { compression = null; }
  6421. var internalFormat = this._getInternalFormat(format);
  6422. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6423. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6424. if (compression) {
  6425. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6426. }
  6427. else {
  6428. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6429. }
  6430. if (texture.generateMipMaps) {
  6431. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6432. }
  6433. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6434. this.resetTextureCache();
  6435. texture.isReady = true;
  6436. };
  6437. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6438. if (compression === void 0) { compression = null; }
  6439. var texture = this._gl.createTexture();
  6440. texture._baseWidth = width;
  6441. texture._baseHeight = height;
  6442. texture._width = width;
  6443. texture._height = height;
  6444. texture.references = 1;
  6445. this.updateRawTexture(texture, data, format, invertY, compression);
  6446. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6447. // Filters
  6448. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6449. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6450. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6451. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6452. texture.samplingMode = samplingMode;
  6453. this._loadedTexturesCache.push(texture);
  6454. return texture;
  6455. };
  6456. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6457. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6458. var texture = this._gl.createTexture();
  6459. texture._baseWidth = width;
  6460. texture._baseHeight = height;
  6461. if (forceExponantOfTwo) {
  6462. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6463. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6464. }
  6465. this.resetTextureCache();
  6466. texture._width = width;
  6467. texture._height = height;
  6468. texture.isReady = false;
  6469. texture.generateMipMaps = generateMipMaps;
  6470. texture.references = 1;
  6471. texture.samplingMode = samplingMode;
  6472. this.updateTextureSamplingMode(samplingMode, texture);
  6473. this._loadedTexturesCache.push(texture);
  6474. return texture;
  6475. };
  6476. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6477. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6478. if (texture.isCube) {
  6479. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6480. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6481. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6482. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6483. }
  6484. else {
  6485. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6486. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6487. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6488. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6489. }
  6490. };
  6491. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6492. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6493. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6494. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6495. if (texture.generateMipMaps) {
  6496. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6497. }
  6498. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6499. this.resetTextureCache();
  6500. texture.isReady = true;
  6501. };
  6502. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6503. if (texture._isDisabled) {
  6504. return;
  6505. }
  6506. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6507. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6508. try {
  6509. // Testing video texture support
  6510. if (this._videoTextureSupported === undefined) {
  6511. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6512. if (this._gl.getError() !== 0) {
  6513. this._videoTextureSupported = false;
  6514. }
  6515. else {
  6516. this._videoTextureSupported = true;
  6517. }
  6518. }
  6519. // Copy video through the current working canvas if video texture is not supported
  6520. if (!this._videoTextureSupported) {
  6521. if (!texture._workingCanvas) {
  6522. texture._workingCanvas = document.createElement("canvas");
  6523. texture._workingContext = texture._workingCanvas.getContext("2d");
  6524. texture._workingCanvas.width = texture._width;
  6525. texture._workingCanvas.height = texture._height;
  6526. }
  6527. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6528. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6529. }
  6530. else {
  6531. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6532. }
  6533. if (texture.generateMipMaps) {
  6534. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6535. }
  6536. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6537. this.resetTextureCache();
  6538. texture.isReady = true;
  6539. }
  6540. catch (ex) {
  6541. // Something unexpected
  6542. // Let's disable the texture
  6543. texture._isDisabled = true;
  6544. }
  6545. };
  6546. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6547. // old version had a "generateMipMaps" arg instead of options.
  6548. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6549. // in the same way, generateDepthBuffer is defaulted to true
  6550. var generateMipMaps = false;
  6551. var generateDepthBuffer = true;
  6552. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6553. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6554. if (options !== undefined) {
  6555. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6556. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6557. type = options.type === undefined ? type : options.type;
  6558. if (options.samplingMode !== undefined) {
  6559. samplingMode = options.samplingMode;
  6560. }
  6561. if (type === Engine.TEXTURETYPE_FLOAT) {
  6562. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6563. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6564. }
  6565. }
  6566. var gl = this._gl;
  6567. var texture = gl.createTexture();
  6568. gl.bindTexture(gl.TEXTURE_2D, texture);
  6569. var width = size.width || size;
  6570. var height = size.height || size;
  6571. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6572. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6573. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6574. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6575. }
  6576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6580. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6581. var depthBuffer;
  6582. // Create the depth buffer
  6583. if (generateDepthBuffer) {
  6584. depthBuffer = gl.createRenderbuffer();
  6585. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6586. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6587. }
  6588. // Create the framebuffer
  6589. var framebuffer = gl.createFramebuffer();
  6590. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6591. if (generateDepthBuffer) {
  6592. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6593. }
  6594. if (generateMipMaps) {
  6595. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6596. }
  6597. // Unbind
  6598. gl.bindTexture(gl.TEXTURE_2D, null);
  6599. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6600. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6601. texture._framebuffer = framebuffer;
  6602. if (generateDepthBuffer) {
  6603. texture._depthBuffer = depthBuffer;
  6604. }
  6605. texture._width = width;
  6606. texture._height = height;
  6607. texture.isReady = true;
  6608. texture.generateMipMaps = generateMipMaps;
  6609. texture.references = 1;
  6610. texture.samplingMode = samplingMode;
  6611. this.resetTextureCache();
  6612. this._loadedTexturesCache.push(texture);
  6613. return texture;
  6614. };
  6615. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6616. var gl = this._gl;
  6617. var texture = gl.createTexture();
  6618. var generateMipMaps = true;
  6619. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6620. if (options !== undefined) {
  6621. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6622. if (options.samplingMode !== undefined) {
  6623. samplingMode = options.samplingMode;
  6624. }
  6625. }
  6626. texture.isCube = true;
  6627. texture.references = 1;
  6628. texture.generateMipMaps = generateMipMaps;
  6629. texture.references = 1;
  6630. texture.samplingMode = samplingMode;
  6631. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6632. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6633. for (var face = 0; face < 6; face++) {
  6634. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6635. }
  6636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6640. // Create the depth buffer
  6641. var depthBuffer = gl.createRenderbuffer();
  6642. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6643. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6644. // Create the framebuffer
  6645. var framebuffer = gl.createFramebuffer();
  6646. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6647. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6648. // Mipmaps
  6649. if (texture.generateMipMaps) {
  6650. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6651. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6652. }
  6653. // Unbind
  6654. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6655. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6656. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6657. texture._framebuffer = framebuffer;
  6658. texture._depthBuffer = depthBuffer;
  6659. this.resetTextureCache();
  6660. texture._width = size;
  6661. texture._height = size;
  6662. texture.isReady = true;
  6663. return texture;
  6664. };
  6665. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6666. var _this = this;
  6667. var gl = this._gl;
  6668. var texture = gl.createTexture();
  6669. texture.isCube = true;
  6670. texture.url = rootUrl;
  6671. texture.references = 1;
  6672. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6673. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6674. if (isDDS) {
  6675. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6676. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6677. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6678. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6679. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6680. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6681. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6682. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6683. }
  6684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6688. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6689. _this.resetTextureCache();
  6690. texture._width = info.width;
  6691. texture._height = info.height;
  6692. texture.isReady = true;
  6693. }, null, null, true);
  6694. }
  6695. else {
  6696. cascadeLoad(rootUrl, scene, function (imgs) {
  6697. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6698. var height = width;
  6699. _this._prepareWorkingCanvas();
  6700. _this._workingCanvas.width = width;
  6701. _this._workingCanvas.height = height;
  6702. var faces = [
  6703. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6704. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6705. ];
  6706. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6707. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6708. for (var index = 0; index < faces.length; index++) {
  6709. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6710. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6711. }
  6712. if (!noMipmap) {
  6713. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6714. }
  6715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6719. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6720. _this.resetTextureCache();
  6721. texture._width = width;
  6722. texture._height = height;
  6723. texture.isReady = true;
  6724. }, files);
  6725. }
  6726. return texture;
  6727. };
  6728. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6729. var _this = this;
  6730. var gl = this._gl;
  6731. var texture = gl.createTexture();
  6732. scene._addPendingData(texture);
  6733. texture.isCube = true;
  6734. texture.references = 1;
  6735. texture.url = url;
  6736. var internalFormat = this._getInternalFormat(format);
  6737. var textureType = gl.UNSIGNED_BYTE;
  6738. if (type === Engine.TEXTURETYPE_FLOAT) {
  6739. textureType = gl.FLOAT;
  6740. }
  6741. var width = size;
  6742. var height = width;
  6743. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6744. texture._width = width;
  6745. texture._height = height;
  6746. var onerror = function () {
  6747. scene._removePendingData(texture);
  6748. };
  6749. var internalCallback = function (data) {
  6750. var rgbeDataArrays = callback(data);
  6751. var facesIndex = [
  6752. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6753. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6754. ];
  6755. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6756. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6757. if (!noMipmap && isPot) {
  6758. if (mipmmapGenerator) {
  6759. var arrayTemp = [];
  6760. // Data are known to be in +X +Y +Z -X -Y -Z
  6761. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6762. arrayTemp.push(rgbeDataArrays[0]); // +X
  6763. arrayTemp.push(rgbeDataArrays[3]); // -X
  6764. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6765. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6766. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6767. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6768. var mipData = mipmmapGenerator(arrayTemp);
  6769. for (var level = 0; level < mipData.length; level++) {
  6770. var mipSize = width >> level;
  6771. // mipData is order in +X -X +Y -Y +Z -Z
  6772. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6773. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6774. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6775. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6776. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6777. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6778. }
  6779. }
  6780. else {
  6781. // Data are known to be in +X +Y +Z -X -Y -Z
  6782. for (var index = 0; index < facesIndex.length; index++) {
  6783. var faceData = rgbeDataArrays[index];
  6784. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6785. }
  6786. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6787. }
  6788. }
  6789. else {
  6790. noMipmap = true;
  6791. }
  6792. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6795. }
  6796. else {
  6797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6799. }
  6800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6802. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6803. texture.isReady = true;
  6804. _this.resetTextureCache();
  6805. scene._removePendingData(texture);
  6806. };
  6807. BABYLON.Tools.LoadFile(url, function (data) {
  6808. internalCallback(data);
  6809. }, onerror, scene.database, true);
  6810. return texture;
  6811. };
  6812. ;
  6813. Engine.prototype._releaseTexture = function (texture) {
  6814. var gl = this._gl;
  6815. if (texture._framebuffer) {
  6816. gl.deleteFramebuffer(texture._framebuffer);
  6817. }
  6818. if (texture._depthBuffer) {
  6819. gl.deleteRenderbuffer(texture._depthBuffer);
  6820. }
  6821. gl.deleteTexture(texture);
  6822. // Unbind channels
  6823. this.unbindAllTextures();
  6824. var index = this._loadedTexturesCache.indexOf(texture);
  6825. if (index !== -1) {
  6826. this._loadedTexturesCache.splice(index, 1);
  6827. }
  6828. };
  6829. Engine.prototype.bindSamplers = function (effect) {
  6830. this._gl.useProgram(effect.getProgram());
  6831. var samplers = effect.getSamplers();
  6832. for (var index = 0; index < samplers.length; index++) {
  6833. var uniform = effect.getUniform(samplers[index]);
  6834. this._gl.uniform1i(uniform, index);
  6835. }
  6836. this._currentEffect = null;
  6837. };
  6838. Engine.prototype._bindTexture = function (channel, texture) {
  6839. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6840. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6841. this._activeTexturesCache[channel] = null;
  6842. };
  6843. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6844. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6845. };
  6846. Engine.prototype.unbindAllTextures = function () {
  6847. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6848. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6849. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6850. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6851. this._activeTexturesCache[channel] = null;
  6852. }
  6853. };
  6854. Engine.prototype.setTexture = function (channel, texture) {
  6855. if (channel < 0) {
  6856. return;
  6857. }
  6858. // Not ready?
  6859. if (!texture || !texture.isReady()) {
  6860. if (this._activeTexturesCache[channel] != null) {
  6861. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6862. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6863. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6864. this._activeTexturesCache[channel] = null;
  6865. }
  6866. return;
  6867. }
  6868. // Video
  6869. var alreadyActivated = false;
  6870. if (texture instanceof BABYLON.VideoTexture) {
  6871. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6872. alreadyActivated = true;
  6873. texture.update();
  6874. }
  6875. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6876. texture.delayLoad();
  6877. return;
  6878. }
  6879. if (this._activeTexturesCache[channel] === texture) {
  6880. return;
  6881. }
  6882. this._activeTexturesCache[channel] = texture;
  6883. var internalTexture = texture.getInternalTexture();
  6884. if (!alreadyActivated) {
  6885. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6886. }
  6887. if (internalTexture.isCube) {
  6888. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6889. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6890. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6891. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6892. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6893. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6894. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6895. }
  6896. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6897. }
  6898. else {
  6899. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6900. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6901. internalTexture._cachedWrapU = texture.wrapU;
  6902. switch (texture.wrapU) {
  6903. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6904. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6905. break;
  6906. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6907. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6908. break;
  6909. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6911. break;
  6912. }
  6913. }
  6914. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6915. internalTexture._cachedWrapV = texture.wrapV;
  6916. switch (texture.wrapV) {
  6917. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6919. break;
  6920. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6921. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6922. break;
  6923. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6924. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6925. break;
  6926. }
  6927. }
  6928. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6929. }
  6930. };
  6931. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6932. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6933. var value = texture.anisotropicFilteringLevel;
  6934. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6935. value = 1;
  6936. }
  6937. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6938. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6939. texture._cachedAnisotropicFilteringLevel = value;
  6940. }
  6941. };
  6942. Engine.prototype.readPixels = function (x, y, width, height) {
  6943. var data = new Uint8Array(height * width * 4);
  6944. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6945. return data;
  6946. };
  6947. Engine.prototype.releaseInternalTexture = function (texture) {
  6948. if (!texture) {
  6949. return;
  6950. }
  6951. texture.references--;
  6952. // Final reference ?
  6953. if (texture.references === 0) {
  6954. var texturesCache = this.getLoadedTexturesCache();
  6955. var index = texturesCache.indexOf(texture);
  6956. if (index > -1) {
  6957. texturesCache.splice(index, 1);
  6958. }
  6959. this._releaseTexture(texture);
  6960. }
  6961. };
  6962. // Dispose
  6963. Engine.prototype.dispose = function () {
  6964. this.hideLoadingUI();
  6965. this.stopRenderLoop();
  6966. // Release scenes
  6967. while (this.scenes.length) {
  6968. this.scenes[0].dispose();
  6969. }
  6970. // Release audio engine
  6971. Engine.audioEngine.dispose();
  6972. // Release effects
  6973. for (var name in this._compiledEffects) {
  6974. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6975. }
  6976. // Unbind
  6977. for (var i in this._vertexAttribArrays) {
  6978. //making sure this is a string
  6979. var iAsNumber = +i;
  6980. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6981. continue;
  6982. }
  6983. this._gl.disableVertexAttribArray(iAsNumber);
  6984. }
  6985. this._gl = null;
  6986. // Events
  6987. window.removeEventListener("blur", this._onBlur);
  6988. window.removeEventListener("focus", this._onFocus);
  6989. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6990. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6991. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6992. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6993. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6994. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6995. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6996. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6997. };
  6998. // Loading screen
  6999. Engine.prototype.displayLoadingUI = function () {
  7000. this._loadingScreen.displayLoadingUI();
  7001. };
  7002. Engine.prototype.hideLoadingUI = function () {
  7003. this._loadingScreen.hideLoadingUI();
  7004. };
  7005. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7006. get: function () {
  7007. return this._loadingScreen;
  7008. },
  7009. set: function (loadingScreen) {
  7010. this._loadingScreen = loadingScreen;
  7011. },
  7012. enumerable: true,
  7013. configurable: true
  7014. });
  7015. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7016. set: function (text) {
  7017. this._loadingScreen.loadingUIText = text;
  7018. },
  7019. enumerable: true,
  7020. configurable: true
  7021. });
  7022. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7023. set: function (color) {
  7024. this._loadingScreen.loadingUIBackgroundColor = color;
  7025. },
  7026. enumerable: true,
  7027. configurable: true
  7028. });
  7029. // FPS
  7030. Engine.prototype.getFps = function () {
  7031. return this.fps;
  7032. };
  7033. Engine.prototype.getDeltaTime = function () {
  7034. return this.deltaTime;
  7035. };
  7036. Engine.prototype._measureFps = function () {
  7037. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7038. var length = this.previousFramesDuration.length;
  7039. if (length >= 2) {
  7040. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7041. }
  7042. if (length >= this.fpsRange) {
  7043. if (length > this.fpsRange) {
  7044. this.previousFramesDuration.splice(0, 1);
  7045. length = this.previousFramesDuration.length;
  7046. }
  7047. var sum = 0;
  7048. for (var id = 0; id < length - 1; id++) {
  7049. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7050. }
  7051. this.fps = 1000.0 / (sum / (length - 1));
  7052. }
  7053. };
  7054. // Statics
  7055. Engine.isSupported = function () {
  7056. try {
  7057. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7058. if (navigator.isCocoonJS) {
  7059. return true;
  7060. }
  7061. var tempcanvas = document.createElement("canvas");
  7062. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7063. return gl != null && !!window.WebGLRenderingContext;
  7064. }
  7065. catch (e) {
  7066. return false;
  7067. }
  7068. };
  7069. // Const statics
  7070. Engine._ALPHA_DISABLE = 0;
  7071. Engine._ALPHA_ADD = 1;
  7072. Engine._ALPHA_COMBINE = 2;
  7073. Engine._ALPHA_SUBTRACT = 3;
  7074. Engine._ALPHA_MULTIPLY = 4;
  7075. Engine._ALPHA_MAXIMIZED = 5;
  7076. Engine._ALPHA_ONEONE = 6;
  7077. Engine._DELAYLOADSTATE_NONE = 0;
  7078. Engine._DELAYLOADSTATE_LOADED = 1;
  7079. Engine._DELAYLOADSTATE_LOADING = 2;
  7080. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7081. Engine._TEXTUREFORMAT_ALPHA = 0;
  7082. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7083. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7084. Engine._TEXTUREFORMAT_RGB = 4;
  7085. Engine._TEXTUREFORMAT_RGBA = 5;
  7086. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7087. Engine._TEXTURETYPE_FLOAT = 1;
  7088. // Updatable statics so stick with vars here
  7089. Engine.CollisionsEpsilon = 0.001;
  7090. Engine.CodeRepository = "src/";
  7091. Engine.ShadersRepository = "src/Shaders/";
  7092. return Engine;
  7093. })();
  7094. BABYLON.Engine = Engine;
  7095. })(BABYLON || (BABYLON = {}));
  7096. var BABYLON;
  7097. (function (BABYLON) {
  7098. /**
  7099. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7100. */
  7101. var Node = (function () {
  7102. /**
  7103. * @constructor
  7104. * @param {string} name - the name and id to be given to this node
  7105. * @param {BABYLON.Scene} the scene this node will be added to
  7106. */
  7107. function Node(name, scene) {
  7108. this.state = "";
  7109. this.animations = new Array();
  7110. this._ranges = {};
  7111. this._childrenFlag = -1;
  7112. this._isEnabled = true;
  7113. this._isReady = true;
  7114. this._currentRenderId = -1;
  7115. this._parentRenderId = -1;
  7116. this.name = name;
  7117. this.id = name;
  7118. this._scene = scene;
  7119. this._initCache();
  7120. }
  7121. Node.prototype.getScene = function () {
  7122. return this._scene;
  7123. };
  7124. Node.prototype.getEngine = function () {
  7125. return this._scene.getEngine();
  7126. };
  7127. // override it in derived class
  7128. Node.prototype.getWorldMatrix = function () {
  7129. return BABYLON.Matrix.Identity();
  7130. };
  7131. // override it in derived class if you add new variables to the cache
  7132. // and call the parent class method
  7133. Node.prototype._initCache = function () {
  7134. this._cache = {};
  7135. this._cache.parent = undefined;
  7136. };
  7137. Node.prototype.updateCache = function (force) {
  7138. if (!force && this.isSynchronized())
  7139. return;
  7140. this._cache.parent = this.parent;
  7141. this._updateCache();
  7142. };
  7143. // override it in derived class if you add new variables to the cache
  7144. // and call the parent class method if !ignoreParentClass
  7145. Node.prototype._updateCache = function (ignoreParentClass) {
  7146. };
  7147. // override it in derived class if you add new variables to the cache
  7148. Node.prototype._isSynchronized = function () {
  7149. return true;
  7150. };
  7151. Node.prototype._markSyncedWithParent = function () {
  7152. this._parentRenderId = this.parent._currentRenderId;
  7153. };
  7154. Node.prototype.isSynchronizedWithParent = function () {
  7155. if (!this.parent) {
  7156. return true;
  7157. }
  7158. if (this._parentRenderId !== this.parent._currentRenderId) {
  7159. return false;
  7160. }
  7161. return this.parent.isSynchronized();
  7162. };
  7163. Node.prototype.isSynchronized = function (updateCache) {
  7164. var check = this.hasNewParent();
  7165. check = check || !this.isSynchronizedWithParent();
  7166. check = check || !this._isSynchronized();
  7167. if (updateCache)
  7168. this.updateCache(true);
  7169. return !check;
  7170. };
  7171. Node.prototype.hasNewParent = function (update) {
  7172. if (this._cache.parent === this.parent)
  7173. return false;
  7174. if (update)
  7175. this._cache.parent = this.parent;
  7176. return true;
  7177. };
  7178. /**
  7179. * Is this node ready to be used/rendered
  7180. * @return {boolean} is it ready
  7181. */
  7182. Node.prototype.isReady = function () {
  7183. return this._isReady;
  7184. };
  7185. /**
  7186. * Is this node enabled.
  7187. * If the node has a parent and is enabled, the parent will be inspected as well.
  7188. * @return {boolean} whether this node (and its parent) is enabled.
  7189. * @see setEnabled
  7190. */
  7191. Node.prototype.isEnabled = function () {
  7192. if (!this._isEnabled) {
  7193. return false;
  7194. }
  7195. if (this.parent) {
  7196. return this.parent.isEnabled();
  7197. }
  7198. return true;
  7199. };
  7200. /**
  7201. * Set the enabled state of this node.
  7202. * @param {boolean} value - the new enabled state
  7203. * @see isEnabled
  7204. */
  7205. Node.prototype.setEnabled = function (value) {
  7206. this._isEnabled = value;
  7207. };
  7208. /**
  7209. * Is this node a descendant of the given node.
  7210. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7211. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7212. * @see parent
  7213. */
  7214. Node.prototype.isDescendantOf = function (ancestor) {
  7215. if (this.parent) {
  7216. if (this.parent === ancestor) {
  7217. return true;
  7218. }
  7219. return this.parent.isDescendantOf(ancestor);
  7220. }
  7221. return false;
  7222. };
  7223. /**
  7224. * Evaluate a list of nodes and determine if they should be considered as descendants considering the given criterias
  7225. * @param {BABYLON.Node[]} list the input array of nodes to evaluate
  7226. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7227. * @param {boolean} directDecendantsOnly 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.
  7228. * @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.
  7229. */
  7230. Node.prototype._getDescendants = function (list, results, directDecendantsOnly, predicate) {
  7231. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7232. for (var index = 0; index < list.length; index++) {
  7233. var item = list[index];
  7234. if (((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) && (!predicate || predicate(item))) {
  7235. results.push(item);
  7236. }
  7237. }
  7238. };
  7239. /**
  7240. * Will return all nodes that have this node as parent.
  7241. * @param {boolean} directDecendantsOnly 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.
  7242. * @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.
  7243. * @return {BABYLON.Node[]} all children nodes of all types.
  7244. */
  7245. Node.prototype.getDescendants = function (directDecendantsOnly, predicate) {
  7246. var results = [];
  7247. this._getDescendants(this._scene.meshes, results, directDecendantsOnly, predicate);
  7248. this._getDescendants(this._scene.lights, results, directDecendantsOnly, predicate);
  7249. this._getDescendants(this._scene.cameras, results, directDecendantsOnly, predicate);
  7250. return results;
  7251. };
  7252. /**
  7253. * @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.
  7254. * @Deprecated, legacy support.
  7255. * use getDecendants instead.
  7256. */
  7257. Node.prototype.getChildren = function (predicate) {
  7258. return this.getDescendants(true, predicate);
  7259. };
  7260. /**
  7261. * Get all child-meshes of this node.
  7262. */
  7263. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7264. var results = [];
  7265. this._getDescendants(this._scene.meshes, results, directDecendantsOnly, predicate);
  7266. return results;
  7267. };
  7268. Node.prototype._setReady = function (state) {
  7269. if (state === this._isReady) {
  7270. return;
  7271. }
  7272. if (!state) {
  7273. this._isReady = false;
  7274. return;
  7275. }
  7276. this._isReady = true;
  7277. if (this.onReady) {
  7278. this.onReady(this);
  7279. }
  7280. };
  7281. Node.prototype.getAnimationByName = function (name) {
  7282. for (var i = 0; i < this.animations.length; i++) {
  7283. var animation = this.animations[i];
  7284. if (animation.name === name) {
  7285. return animation;
  7286. }
  7287. }
  7288. return null;
  7289. };
  7290. Node.prototype.createAnimationRange = function (name, from, to) {
  7291. // check name not already in use
  7292. if (!this._ranges[name]) {
  7293. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7294. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7295. if (this.animations[i]) {
  7296. this.animations[i].createRange(name, from, to);
  7297. }
  7298. }
  7299. }
  7300. };
  7301. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7302. if (deleteFrames === void 0) { deleteFrames = true; }
  7303. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7304. if (this.animations[i]) {
  7305. this.animations[i].deleteRange(name, deleteFrames);
  7306. }
  7307. }
  7308. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7309. };
  7310. Node.prototype.getAnimationRange = function (name) {
  7311. return this._ranges[name];
  7312. };
  7313. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7314. var range = this.getAnimationRange(name);
  7315. if (!range) {
  7316. return null;
  7317. }
  7318. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7319. };
  7320. Node.prototype.serializeAnimationRanges = function () {
  7321. var serializationRanges = [];
  7322. for (var name in this._ranges) {
  7323. var range = {};
  7324. range.name = name;
  7325. range.from = this._ranges[name].from;
  7326. range.to = this._ranges[name].to;
  7327. serializationRanges.push(range);
  7328. }
  7329. return serializationRanges;
  7330. };
  7331. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7332. if (parsedNode.ranges) {
  7333. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7334. var data = parsedNode.ranges[index];
  7335. node.createAnimationRange(data.name, data.from, data.to);
  7336. }
  7337. }
  7338. };
  7339. __decorate([
  7340. BABYLON.serialize()
  7341. ], Node.prototype, "name", void 0);
  7342. __decorate([
  7343. BABYLON.serialize()
  7344. ], Node.prototype, "id", void 0);
  7345. __decorate([
  7346. BABYLON.serialize()
  7347. ], Node.prototype, "uniqueId", void 0);
  7348. __decorate([
  7349. BABYLON.serialize()
  7350. ], Node.prototype, "state", void 0);
  7351. return Node;
  7352. })();
  7353. BABYLON.Node = Node;
  7354. })(BABYLON || (BABYLON = {}));
  7355. var BABYLON;
  7356. (function (BABYLON) {
  7357. var FilesInput = (function () {
  7358. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7359. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7360. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7361. this._engine = p_engine;
  7362. this._canvas = p_canvas;
  7363. this._currentScene = p_scene;
  7364. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7365. this._progressCallback = p_progressCallback;
  7366. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7367. this._textureLoadingCallback = p_textureLoadingCallback;
  7368. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7369. }
  7370. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7371. var _this = this;
  7372. if (p_elementToMonitor) {
  7373. this._elementToMonitor = p_elementToMonitor;
  7374. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7375. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7376. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7377. }
  7378. };
  7379. FilesInput.prototype.renderFunction = function () {
  7380. if (this._additionnalRenderLoopLogicCallback) {
  7381. this._additionnalRenderLoopLogicCallback();
  7382. }
  7383. if (this._currentScene) {
  7384. if (this._textureLoadingCallback) {
  7385. var remaining = this._currentScene.getWaitingItemsCount();
  7386. if (remaining > 0) {
  7387. this._textureLoadingCallback(remaining);
  7388. }
  7389. }
  7390. this._currentScene.render();
  7391. }
  7392. };
  7393. FilesInput.prototype.drag = function (e) {
  7394. e.stopPropagation();
  7395. e.preventDefault();
  7396. };
  7397. FilesInput.prototype.drop = function (eventDrop) {
  7398. eventDrop.stopPropagation();
  7399. eventDrop.preventDefault();
  7400. this.loadFiles(eventDrop);
  7401. };
  7402. FilesInput.prototype.loadFiles = function (event) {
  7403. if (this._startingProcessingFilesCallback)
  7404. this._startingProcessingFilesCallback();
  7405. // Handling data transfer via drag'n'drop
  7406. if (event && event.dataTransfer && event.dataTransfer.files) {
  7407. this._filesToLoad = event.dataTransfer.files;
  7408. }
  7409. // Handling files from input files
  7410. if (event && event.target && event.target.files) {
  7411. this._filesToLoad = event.target.files;
  7412. }
  7413. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7414. for (var i = 0; i < this._filesToLoad.length; i++) {
  7415. switch (this._filesToLoad[i].type) {
  7416. case "image/jpeg":
  7417. case "image/png":
  7418. case "image/bmp":
  7419. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7420. break;
  7421. case "image/targa":
  7422. case "image/vnd.ms-dds":
  7423. case "audio/wav":
  7424. case "audio/x-wav":
  7425. case "audio/mp3":
  7426. case "audio/mpeg":
  7427. case "audio/mpeg3":
  7428. case "audio/x-mpeg-3":
  7429. case "audio/ogg":
  7430. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7431. break;
  7432. default:
  7433. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7434. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7435. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7436. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7437. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7438. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7439. this._sceneFileToLoad = this._filesToLoad[i];
  7440. }
  7441. break;
  7442. }
  7443. }
  7444. this.reload();
  7445. }
  7446. };
  7447. FilesInput.prototype.reload = function () {
  7448. var _this = this;
  7449. var that = this;
  7450. // If a ".babylon" file has been provided
  7451. if (this._sceneFileToLoad) {
  7452. if (this._currentScene) {
  7453. if (BABYLON.Tools.errorsCount > 0) {
  7454. BABYLON.Tools.ClearLogCache();
  7455. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7456. }
  7457. this._engine.stopRenderLoop();
  7458. this._currentScene.dispose();
  7459. }
  7460. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7461. that._currentScene = newScene;
  7462. // Wait for textures and shaders to be ready
  7463. that._currentScene.executeWhenReady(function () {
  7464. // Attach camera to canvas inputs
  7465. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7466. that._currentScene.createDefaultCameraOrLight();
  7467. }
  7468. that._currentScene.activeCamera.attachControl(that._canvas);
  7469. if (that._sceneLoadedCallback) {
  7470. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7471. }
  7472. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7473. });
  7474. }, function (progress) {
  7475. if (_this._progressCallback) {
  7476. _this._progressCallback(progress);
  7477. }
  7478. });
  7479. }
  7480. else {
  7481. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7482. }
  7483. };
  7484. FilesInput.FilesTextures = new Array();
  7485. FilesInput.FilesToLoad = new Array();
  7486. return FilesInput;
  7487. })();
  7488. BABYLON.FilesInput = FilesInput;
  7489. })(BABYLON || (BABYLON = {}));
  7490. var BABYLON;
  7491. (function (BABYLON) {
  7492. var IntersectionInfo = (function () {
  7493. function IntersectionInfo(bu, bv, distance) {
  7494. this.bu = bu;
  7495. this.bv = bv;
  7496. this.distance = distance;
  7497. this.faceId = 0;
  7498. this.subMeshId = 0;
  7499. }
  7500. return IntersectionInfo;
  7501. })();
  7502. BABYLON.IntersectionInfo = IntersectionInfo;
  7503. var PickingInfo = (function () {
  7504. function PickingInfo() {
  7505. this.hit = false;
  7506. this.distance = 0;
  7507. this.pickedPoint = null;
  7508. this.pickedMesh = null;
  7509. this.bu = 0;
  7510. this.bv = 0;
  7511. this.faceId = -1;
  7512. this.subMeshId = 0;
  7513. this.pickedSprite = null;
  7514. }
  7515. // Methods
  7516. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7517. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7518. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7519. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7520. return null;
  7521. }
  7522. var indices = this.pickedMesh.getIndices();
  7523. var result;
  7524. if (useVerticesNormals) {
  7525. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7526. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7527. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7528. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7529. normal0 = normal0.scale(this.bu);
  7530. normal1 = normal1.scale(this.bv);
  7531. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7532. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7533. }
  7534. else {
  7535. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7536. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7537. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7538. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7539. var p1p2 = vertex1.subtract(vertex2);
  7540. var p3p2 = vertex3.subtract(vertex2);
  7541. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7542. }
  7543. if (useWorldCoordinates) {
  7544. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7545. }
  7546. return BABYLON.Vector3.Normalize(result);
  7547. };
  7548. PickingInfo.prototype.getTextureCoordinates = function () {
  7549. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7550. return null;
  7551. }
  7552. var indices = this.pickedMesh.getIndices();
  7553. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7554. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7555. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7556. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7557. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7558. uv1 = uv1.scale(this.bu);
  7559. uv2 = uv2.scale(this.bv);
  7560. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7561. };
  7562. return PickingInfo;
  7563. })();
  7564. BABYLON.PickingInfo = PickingInfo;
  7565. })(BABYLON || (BABYLON = {}));
  7566. var BABYLON;
  7567. (function (BABYLON) {
  7568. var BoundingSphere = (function () {
  7569. function BoundingSphere(minimum, maximum) {
  7570. this.minimum = minimum;
  7571. this.maximum = maximum;
  7572. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7573. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7574. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7575. this.radius = distance * 0.5;
  7576. this.centerWorld = BABYLON.Vector3.Zero();
  7577. this._update(BABYLON.Matrix.Identity());
  7578. }
  7579. // Methods
  7580. BoundingSphere.prototype._update = function (world) {
  7581. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7582. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7583. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7584. };
  7585. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7586. for (var i = 0; i < 6; i++) {
  7587. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7588. return false;
  7589. }
  7590. return true;
  7591. };
  7592. BoundingSphere.prototype.intersectsPoint = function (point) {
  7593. var x = this.centerWorld.x - point.x;
  7594. var y = this.centerWorld.y - point.y;
  7595. var z = this.centerWorld.z - point.z;
  7596. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7597. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7598. return false;
  7599. return true;
  7600. };
  7601. // Statics
  7602. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7603. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7604. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7605. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7606. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7607. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7608. return false;
  7609. return true;
  7610. };
  7611. return BoundingSphere;
  7612. })();
  7613. BABYLON.BoundingSphere = BoundingSphere;
  7614. })(BABYLON || (BABYLON = {}));
  7615. var BABYLON;
  7616. (function (BABYLON) {
  7617. var BoundingBox = (function () {
  7618. function BoundingBox(minimum, maximum) {
  7619. this.minimum = minimum;
  7620. this.maximum = maximum;
  7621. this.vectors = new Array();
  7622. this.vectorsWorld = new Array();
  7623. // Bounding vectors
  7624. this.vectors.push(this.minimum.clone());
  7625. this.vectors.push(this.maximum.clone());
  7626. this.vectors.push(this.minimum.clone());
  7627. this.vectors[2].x = this.maximum.x;
  7628. this.vectors.push(this.minimum.clone());
  7629. this.vectors[3].y = this.maximum.y;
  7630. this.vectors.push(this.minimum.clone());
  7631. this.vectors[4].z = this.maximum.z;
  7632. this.vectors.push(this.maximum.clone());
  7633. this.vectors[5].z = this.minimum.z;
  7634. this.vectors.push(this.maximum.clone());
  7635. this.vectors[6].x = this.minimum.x;
  7636. this.vectors.push(this.maximum.clone());
  7637. this.vectors[7].y = this.minimum.y;
  7638. // OBB
  7639. this.center = this.maximum.add(this.minimum).scale(0.5);
  7640. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7641. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7642. // World
  7643. for (var index = 0; index < this.vectors.length; index++) {
  7644. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7645. }
  7646. this.minimumWorld = BABYLON.Vector3.Zero();
  7647. this.maximumWorld = BABYLON.Vector3.Zero();
  7648. this._update(BABYLON.Matrix.Identity());
  7649. }
  7650. // Methods
  7651. BoundingBox.prototype.getWorldMatrix = function () {
  7652. return this._worldMatrix;
  7653. };
  7654. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7655. this._worldMatrix.copyFrom(matrix);
  7656. return this;
  7657. };
  7658. BoundingBox.prototype._update = function (world) {
  7659. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7660. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7661. for (var index = 0; index < this.vectors.length; index++) {
  7662. var v = this.vectorsWorld[index];
  7663. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7664. if (v.x < this.minimumWorld.x)
  7665. this.minimumWorld.x = v.x;
  7666. if (v.y < this.minimumWorld.y)
  7667. this.minimumWorld.y = v.y;
  7668. if (v.z < this.minimumWorld.z)
  7669. this.minimumWorld.z = v.z;
  7670. if (v.x > this.maximumWorld.x)
  7671. this.maximumWorld.x = v.x;
  7672. if (v.y > this.maximumWorld.y)
  7673. this.maximumWorld.y = v.y;
  7674. if (v.z > this.maximumWorld.z)
  7675. this.maximumWorld.z = v.z;
  7676. }
  7677. // OBB
  7678. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7679. this.center.scaleInPlace(0.5);
  7680. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7681. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7682. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7683. this._worldMatrix = world;
  7684. };
  7685. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7686. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7687. };
  7688. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7689. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7690. };
  7691. BoundingBox.prototype.intersectsPoint = function (point) {
  7692. var delta = -BABYLON.Epsilon;
  7693. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7694. return false;
  7695. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7696. return false;
  7697. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7698. return false;
  7699. return true;
  7700. };
  7701. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7702. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7703. };
  7704. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7705. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7706. return false;
  7707. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7708. return false;
  7709. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7710. return false;
  7711. return true;
  7712. };
  7713. // Statics
  7714. BoundingBox.Intersects = function (box0, box1) {
  7715. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7716. return false;
  7717. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7718. return false;
  7719. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7720. return false;
  7721. return true;
  7722. };
  7723. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7724. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7725. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7726. return (num <= (sphereRadius * sphereRadius));
  7727. };
  7728. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7729. for (var p = 0; p < 6; p++) {
  7730. for (var i = 0; i < 8; i++) {
  7731. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7732. return false;
  7733. }
  7734. }
  7735. }
  7736. return true;
  7737. };
  7738. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7739. for (var p = 0; p < 6; p++) {
  7740. var inCount = 8;
  7741. for (var i = 0; i < 8; i++) {
  7742. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7743. --inCount;
  7744. }
  7745. else {
  7746. break;
  7747. }
  7748. }
  7749. if (inCount === 0)
  7750. return false;
  7751. }
  7752. return true;
  7753. };
  7754. return BoundingBox;
  7755. })();
  7756. BABYLON.BoundingBox = BoundingBox;
  7757. })(BABYLON || (BABYLON = {}));
  7758. var BABYLON;
  7759. (function (BABYLON) {
  7760. var computeBoxExtents = function (axis, box) {
  7761. var p = BABYLON.Vector3.Dot(box.center, axis);
  7762. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7763. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7764. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7765. var r = r0 + r1 + r2;
  7766. return {
  7767. min: p - r,
  7768. max: p + r
  7769. };
  7770. };
  7771. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7772. var axisOverlap = function (axis, box0, box1) {
  7773. var result0 = computeBoxExtents(axis, box0);
  7774. var result1 = computeBoxExtents(axis, box1);
  7775. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7776. };
  7777. var BoundingInfo = (function () {
  7778. function BoundingInfo(minimum, maximum) {
  7779. this.minimum = minimum;
  7780. this.maximum = maximum;
  7781. this._isLocked = false;
  7782. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7783. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7784. }
  7785. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7786. get: function () {
  7787. return this._isLocked;
  7788. },
  7789. set: function (value) {
  7790. this._isLocked = value;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. // Methods
  7796. BoundingInfo.prototype.update = function (world) {
  7797. if (this._isLocked) {
  7798. return;
  7799. }
  7800. this.boundingBox._update(world);
  7801. this.boundingSphere._update(world);
  7802. };
  7803. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7804. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7805. return false;
  7806. return this.boundingBox.isInFrustum(frustumPlanes);
  7807. };
  7808. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7809. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7810. };
  7811. BoundingInfo.prototype._checkCollision = function (collider) {
  7812. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7813. };
  7814. BoundingInfo.prototype.intersectsPoint = function (point) {
  7815. if (!this.boundingSphere.centerWorld) {
  7816. return false;
  7817. }
  7818. if (!this.boundingSphere.intersectsPoint(point)) {
  7819. return false;
  7820. }
  7821. if (!this.boundingBox.intersectsPoint(point)) {
  7822. return false;
  7823. }
  7824. return true;
  7825. };
  7826. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7827. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7828. return false;
  7829. }
  7830. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7831. return false;
  7832. }
  7833. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7834. return false;
  7835. }
  7836. if (!precise) {
  7837. return true;
  7838. }
  7839. var box0 = this.boundingBox;
  7840. var box1 = boundingInfo.boundingBox;
  7841. if (!axisOverlap(box0.directions[0], box0, box1))
  7842. return false;
  7843. if (!axisOverlap(box0.directions[1], box0, box1))
  7844. return false;
  7845. if (!axisOverlap(box0.directions[2], box0, box1))
  7846. return false;
  7847. if (!axisOverlap(box1.directions[0], box0, box1))
  7848. return false;
  7849. if (!axisOverlap(box1.directions[1], box0, box1))
  7850. return false;
  7851. if (!axisOverlap(box1.directions[2], box0, box1))
  7852. return false;
  7853. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7854. return false;
  7855. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7856. return false;
  7857. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7858. return false;
  7859. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7860. return false;
  7861. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7862. return false;
  7863. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7864. return false;
  7865. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7866. return false;
  7867. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7868. return false;
  7869. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7870. return false;
  7871. return true;
  7872. };
  7873. return BoundingInfo;
  7874. })();
  7875. BABYLON.BoundingInfo = BoundingInfo;
  7876. })(BABYLON || (BABYLON = {}));
  7877. var BABYLON;
  7878. (function (BABYLON) {
  7879. var Ray = (function () {
  7880. function Ray(origin, direction, length) {
  7881. if (length === void 0) { length = Number.MAX_VALUE; }
  7882. this.origin = origin;
  7883. this.direction = direction;
  7884. this.length = length;
  7885. }
  7886. // Methods
  7887. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  7888. var d = 0.0;
  7889. var maxValue = Number.MAX_VALUE;
  7890. var inv;
  7891. var min;
  7892. var max;
  7893. var temp;
  7894. if (Math.abs(this.direction.x) < 0.0000001) {
  7895. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  7896. return false;
  7897. }
  7898. }
  7899. else {
  7900. inv = 1.0 / this.direction.x;
  7901. min = (minimum.x - this.origin.x) * inv;
  7902. max = (maximum.x - this.origin.x) * inv;
  7903. if (max === -Infinity) {
  7904. max = Infinity;
  7905. }
  7906. if (min > max) {
  7907. temp = min;
  7908. min = max;
  7909. max = temp;
  7910. }
  7911. d = Math.max(min, d);
  7912. maxValue = Math.min(max, maxValue);
  7913. if (d > maxValue) {
  7914. return false;
  7915. }
  7916. }
  7917. if (Math.abs(this.direction.y) < 0.0000001) {
  7918. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  7919. return false;
  7920. }
  7921. }
  7922. else {
  7923. inv = 1.0 / this.direction.y;
  7924. min = (minimum.y - this.origin.y) * inv;
  7925. max = (maximum.y - this.origin.y) * inv;
  7926. if (max === -Infinity) {
  7927. max = Infinity;
  7928. }
  7929. if (min > max) {
  7930. temp = min;
  7931. min = max;
  7932. max = temp;
  7933. }
  7934. d = Math.max(min, d);
  7935. maxValue = Math.min(max, maxValue);
  7936. if (d > maxValue) {
  7937. return false;
  7938. }
  7939. }
  7940. if (Math.abs(this.direction.z) < 0.0000001) {
  7941. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  7942. return false;
  7943. }
  7944. }
  7945. else {
  7946. inv = 1.0 / this.direction.z;
  7947. min = (minimum.z - this.origin.z) * inv;
  7948. max = (maximum.z - this.origin.z) * inv;
  7949. if (max === -Infinity) {
  7950. max = Infinity;
  7951. }
  7952. if (min > max) {
  7953. temp = min;
  7954. min = max;
  7955. max = temp;
  7956. }
  7957. d = Math.max(min, d);
  7958. maxValue = Math.min(max, maxValue);
  7959. if (d > maxValue) {
  7960. return false;
  7961. }
  7962. }
  7963. return true;
  7964. };
  7965. Ray.prototype.intersectsBox = function (box) {
  7966. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  7967. };
  7968. Ray.prototype.intersectsSphere = function (sphere) {
  7969. var x = sphere.center.x - this.origin.x;
  7970. var y = sphere.center.y - this.origin.y;
  7971. var z = sphere.center.z - this.origin.z;
  7972. var pyth = (x * x) + (y * y) + (z * z);
  7973. var rr = sphere.radius * sphere.radius;
  7974. if (pyth <= rr) {
  7975. return true;
  7976. }
  7977. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  7978. if (dot < 0.0) {
  7979. return false;
  7980. }
  7981. var temp = pyth - (dot * dot);
  7982. return temp <= rr;
  7983. };
  7984. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  7985. if (!this._edge1) {
  7986. this._edge1 = BABYLON.Vector3.Zero();
  7987. this._edge2 = BABYLON.Vector3.Zero();
  7988. this._pvec = BABYLON.Vector3.Zero();
  7989. this._tvec = BABYLON.Vector3.Zero();
  7990. this._qvec = BABYLON.Vector3.Zero();
  7991. }
  7992. vertex1.subtractToRef(vertex0, this._edge1);
  7993. vertex2.subtractToRef(vertex0, this._edge2);
  7994. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  7995. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  7996. if (det === 0) {
  7997. return null;
  7998. }
  7999. var invdet = 1 / det;
  8000. this.origin.subtractToRef(vertex0, this._tvec);
  8001. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8002. if (bu < 0 || bu > 1.0) {
  8003. return null;
  8004. }
  8005. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8006. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8007. if (bv < 0 || bu + bv > 1.0) {
  8008. return null;
  8009. }
  8010. //check if the distance is longer than the predefined length.
  8011. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8012. if (distance > this.length) {
  8013. return null;
  8014. }
  8015. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8016. };
  8017. // Statics
  8018. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8019. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8020. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8021. var direction = end.subtract(start);
  8022. direction.normalize();
  8023. return new Ray(start, direction);
  8024. };
  8025. /**
  8026. * 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
  8027. * transformed to the given world matrix.
  8028. * @param origin The origin point
  8029. * @param end The end point
  8030. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8031. */
  8032. Ray.CreateNewFromTo = function (origin, end, world) {
  8033. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8034. var direction = end.subtract(origin);
  8035. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8036. direction.normalize();
  8037. return Ray.Transform(new Ray(origin, direction, length), world);
  8038. };
  8039. Ray.Transform = function (ray, matrix) {
  8040. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8041. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8042. return new Ray(newOrigin, newDirection, ray.length);
  8043. };
  8044. return Ray;
  8045. })();
  8046. BABYLON.Ray = Ray;
  8047. })(BABYLON || (BABYLON = {}));
  8048. var BABYLON;
  8049. (function (BABYLON) {
  8050. var AbstractMesh = (function (_super) {
  8051. __extends(AbstractMesh, _super);
  8052. // Constructor
  8053. function AbstractMesh(name, scene) {
  8054. var _this = this;
  8055. _super.call(this, name, scene);
  8056. // Properties
  8057. this.definedFacingForward = true; // orientation for POV movement & rotation
  8058. this.position = new BABYLON.Vector3(0, 0, 0);
  8059. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8060. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8061. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8062. this.visibility = 1.0;
  8063. this.alphaIndex = Number.MAX_VALUE;
  8064. this.infiniteDistance = false;
  8065. this.isVisible = true;
  8066. this.isPickable = true;
  8067. this.showBoundingBox = false;
  8068. this.showSubMeshesBoundingBox = false;
  8069. this.onDispose = null;
  8070. this.isBlocker = false;
  8071. this.renderingGroupId = 0;
  8072. this.receiveShadows = false;
  8073. this.renderOutline = false;
  8074. this.outlineColor = BABYLON.Color3.Red();
  8075. this.outlineWidth = 0.02;
  8076. this.renderOverlay = false;
  8077. this.overlayColor = BABYLON.Color3.Red();
  8078. this.overlayAlpha = 0.5;
  8079. this.hasVertexAlpha = false;
  8080. this.useVertexColors = true;
  8081. this.applyFog = true;
  8082. this.computeBonesUsingShaders = true;
  8083. this.scalingDeterminant = 1;
  8084. this.numBoneInfluencers = 4;
  8085. this.useOctreeForRenderingSelection = true;
  8086. this.useOctreeForPicking = true;
  8087. this.useOctreeForCollisions = true;
  8088. this.layerMask = 0x0FFFFFFF;
  8089. this.alwaysSelectAsActiveMesh = false;
  8090. // Collisions
  8091. this._checkCollisions = false;
  8092. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8093. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8094. this._collider = new BABYLON.Collider();
  8095. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8096. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8097. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8098. // Edges
  8099. this.edgesWidth = 1;
  8100. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8101. // Cache
  8102. this._localWorld = BABYLON.Matrix.Zero();
  8103. this._worldMatrix = BABYLON.Matrix.Zero();
  8104. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8105. this._absolutePosition = BABYLON.Vector3.Zero();
  8106. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8107. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8108. this._isDirty = false;
  8109. this._pivotMatrix = BABYLON.Matrix.Identity();
  8110. this._isDisposed = false;
  8111. this._renderId = 0;
  8112. this._intersectionsInProgress = new Array();
  8113. this._onAfterWorldMatrixUpdate = new Array();
  8114. this._isWorldMatrixFrozen = false;
  8115. this._unIndexed = false;
  8116. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8117. if (collidedMesh === void 0) { collidedMesh = null; }
  8118. //TODO move this to the collision coordinator!
  8119. if (_this.getScene().workerCollisions)
  8120. newPosition.multiplyInPlace(_this._collider.radius);
  8121. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8122. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8123. _this.position.addInPlace(_this._diffPositionForCollisions);
  8124. }
  8125. if (_this.onCollide && collidedMesh) {
  8126. _this.onCollide(collidedMesh);
  8127. }
  8128. if (_this.onCollisionPositionChange) {
  8129. _this.onCollisionPositionChange(_this.position);
  8130. }
  8131. };
  8132. scene.addMesh(this);
  8133. }
  8134. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8135. get: function () {
  8136. return AbstractMesh._BILLBOARDMODE_NONE;
  8137. },
  8138. enumerable: true,
  8139. configurable: true
  8140. });
  8141. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8142. get: function () {
  8143. return AbstractMesh._BILLBOARDMODE_X;
  8144. },
  8145. enumerable: true,
  8146. configurable: true
  8147. });
  8148. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8149. get: function () {
  8150. return AbstractMesh._BILLBOARDMODE_Y;
  8151. },
  8152. enumerable: true,
  8153. configurable: true
  8154. });
  8155. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8156. get: function () {
  8157. return AbstractMesh._BILLBOARDMODE_Z;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8163. get: function () {
  8164. return AbstractMesh._BILLBOARDMODE_ALL;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8170. get: function () {
  8171. return this._skeleton;
  8172. },
  8173. set: function (value) {
  8174. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8175. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8176. }
  8177. if (value && value.needInitialSkinMatrix) {
  8178. value._registerMeshWithPoseMatrix(this);
  8179. }
  8180. this._skeleton = value;
  8181. if (!this._skeleton) {
  8182. this._bonesTransformMatrices = null;
  8183. }
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. /**
  8189. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8190. */
  8191. AbstractMesh.prototype.toString = function (fullDetails) {
  8192. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8193. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8194. if (this._skeleton) {
  8195. ret += ", skeleton: " + this._skeleton.name;
  8196. }
  8197. if (fullDetails) {
  8198. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8199. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8200. }
  8201. return ret;
  8202. };
  8203. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8204. /**
  8205. * Getting the rotation object.
  8206. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8207. */
  8208. get: function () {
  8209. return this._rotation;
  8210. },
  8211. set: function (newRotation) {
  8212. this._rotation = newRotation;
  8213. },
  8214. enumerable: true,
  8215. configurable: true
  8216. });
  8217. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8218. get: function () {
  8219. return this._scaling;
  8220. },
  8221. set: function (newScaling) {
  8222. this._scaling = newScaling;
  8223. if (this.physicsImpostor) {
  8224. this.physicsImpostor.forceUpdate();
  8225. }
  8226. },
  8227. enumerable: true,
  8228. configurable: true
  8229. });
  8230. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8231. get: function () {
  8232. return this._rotationQuaternion;
  8233. },
  8234. set: function (quaternion) {
  8235. this._rotationQuaternion = quaternion;
  8236. //reset the rotation vector.
  8237. if (quaternion && this.rotation.length()) {
  8238. this.rotation.copyFromFloats(0, 0, 0);
  8239. }
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. // Methods
  8245. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8246. this._poseMatrix.copyFrom(matrix);
  8247. };
  8248. AbstractMesh.prototype.getPoseMatrix = function () {
  8249. return this._poseMatrix;
  8250. };
  8251. AbstractMesh.prototype.disableEdgesRendering = function () {
  8252. if (this._edgesRenderer !== undefined) {
  8253. this._edgesRenderer.dispose();
  8254. this._edgesRenderer = undefined;
  8255. }
  8256. };
  8257. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8258. if (epsilon === void 0) { epsilon = 0.95; }
  8259. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8260. this.disableEdgesRendering();
  8261. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8262. };
  8263. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8264. get: function () {
  8265. return false;
  8266. },
  8267. enumerable: true,
  8268. configurable: true
  8269. });
  8270. AbstractMesh.prototype.getLOD = function (camera) {
  8271. return this;
  8272. };
  8273. AbstractMesh.prototype.getTotalVertices = function () {
  8274. return 0;
  8275. };
  8276. AbstractMesh.prototype.getIndices = function () {
  8277. return null;
  8278. };
  8279. AbstractMesh.prototype.getVerticesData = function (kind) {
  8280. return null;
  8281. };
  8282. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8283. return false;
  8284. };
  8285. AbstractMesh.prototype.getBoundingInfo = function () {
  8286. if (this._masterMesh) {
  8287. return this._masterMesh.getBoundingInfo();
  8288. }
  8289. if (!this._boundingInfo) {
  8290. this._updateBoundingInfo();
  8291. }
  8292. return this._boundingInfo;
  8293. };
  8294. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8295. get: function () {
  8296. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8297. },
  8298. enumerable: true,
  8299. configurable: true
  8300. });
  8301. AbstractMesh.prototype._preActivate = function () {
  8302. };
  8303. AbstractMesh.prototype._activate = function (renderId) {
  8304. this._renderId = renderId;
  8305. };
  8306. AbstractMesh.prototype.getWorldMatrix = function () {
  8307. if (this._masterMesh) {
  8308. return this._masterMesh.getWorldMatrix();
  8309. }
  8310. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8311. this.computeWorldMatrix();
  8312. }
  8313. return this._worldMatrix;
  8314. };
  8315. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8316. get: function () {
  8317. return this._worldMatrix;
  8318. },
  8319. enumerable: true,
  8320. configurable: true
  8321. });
  8322. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8323. get: function () {
  8324. return this._absolutePosition;
  8325. },
  8326. enumerable: true,
  8327. configurable: true
  8328. });
  8329. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8330. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8331. this.computeWorldMatrix(true);
  8332. this._isWorldMatrixFrozen = true;
  8333. };
  8334. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8335. this._isWorldMatrixFrozen = false;
  8336. this.computeWorldMatrix(true);
  8337. };
  8338. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8339. get: function () {
  8340. return this._isWorldMatrixFrozen;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8346. axis.normalize();
  8347. if (!this.rotationQuaternion) {
  8348. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8349. this.rotation = BABYLON.Vector3.Zero();
  8350. }
  8351. var rotationQuaternion;
  8352. if (!space || space === BABYLON.Space.LOCAL) {
  8353. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8354. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8355. }
  8356. else {
  8357. if (this.parent) {
  8358. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8359. invertParentWorldMatrix.invert();
  8360. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8361. }
  8362. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8363. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8364. }
  8365. };
  8366. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8367. var displacementVector = axis.scale(distance);
  8368. if (!space || space === BABYLON.Space.LOCAL) {
  8369. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8370. this.setPositionWithLocalVector(tempV3);
  8371. }
  8372. else {
  8373. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8374. }
  8375. };
  8376. AbstractMesh.prototype.getAbsolutePosition = function () {
  8377. this.computeWorldMatrix();
  8378. return this._absolutePosition;
  8379. };
  8380. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8381. if (!absolutePosition) {
  8382. return;
  8383. }
  8384. var absolutePositionX;
  8385. var absolutePositionY;
  8386. var absolutePositionZ;
  8387. if (absolutePosition.x === undefined) {
  8388. if (arguments.length < 3) {
  8389. return;
  8390. }
  8391. absolutePositionX = arguments[0];
  8392. absolutePositionY = arguments[1];
  8393. absolutePositionZ = arguments[2];
  8394. }
  8395. else {
  8396. absolutePositionX = absolutePosition.x;
  8397. absolutePositionY = absolutePosition.y;
  8398. absolutePositionZ = absolutePosition.z;
  8399. }
  8400. if (this.parent) {
  8401. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8402. invertParentWorldMatrix.invert();
  8403. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8404. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8405. }
  8406. else {
  8407. this.position.x = absolutePositionX;
  8408. this.position.y = absolutePositionY;
  8409. this.position.z = absolutePositionZ;
  8410. }
  8411. };
  8412. // ================================== Point of View Movement =================================
  8413. /**
  8414. * Perform relative position change from the point of view of behind the front of the mesh.
  8415. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8416. * Supports definition of mesh facing forward or backward.
  8417. * @param {number} amountRight
  8418. * @param {number} amountUp
  8419. * @param {number} amountForward
  8420. */
  8421. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8422. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8423. };
  8424. /**
  8425. * Calculate relative position change from the point of view of behind the front of the mesh.
  8426. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8427. * Supports definition of mesh facing forward or backward.
  8428. * @param {number} amountRight
  8429. * @param {number} amountUp
  8430. * @param {number} amountForward
  8431. */
  8432. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8433. var rotMatrix = new BABYLON.Matrix();
  8434. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8435. rotQuaternion.toRotationMatrix(rotMatrix);
  8436. var translationDelta = BABYLON.Vector3.Zero();
  8437. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8438. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8439. return translationDelta;
  8440. };
  8441. // ================================== Point of View Rotation =================================
  8442. /**
  8443. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8444. * Supports definition of mesh facing forward or backward.
  8445. * @param {number} flipBack
  8446. * @param {number} twirlClockwise
  8447. * @param {number} tiltRight
  8448. */
  8449. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8450. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8451. };
  8452. /**
  8453. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8454. * Supports definition of mesh facing forward or backward.
  8455. * @param {number} flipBack
  8456. * @param {number} twirlClockwise
  8457. * @param {number} tiltRight
  8458. */
  8459. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8460. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8461. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8462. };
  8463. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8464. this._pivotMatrix = matrix;
  8465. this._cache.pivotMatrixUpdated = true;
  8466. };
  8467. AbstractMesh.prototype.getPivotMatrix = function () {
  8468. return this._pivotMatrix;
  8469. };
  8470. AbstractMesh.prototype._isSynchronized = function () {
  8471. if (this._isDirty) {
  8472. return false;
  8473. }
  8474. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8475. return false;
  8476. if (this._cache.pivotMatrixUpdated) {
  8477. return false;
  8478. }
  8479. if (this.infiniteDistance) {
  8480. return false;
  8481. }
  8482. if (!this._cache.position.equals(this.position))
  8483. return false;
  8484. if (this.rotationQuaternion) {
  8485. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8486. return false;
  8487. }
  8488. else {
  8489. if (!this._cache.rotation.equals(this.rotation))
  8490. return false;
  8491. }
  8492. if (!this._cache.scaling.equals(this.scaling))
  8493. return false;
  8494. return true;
  8495. };
  8496. AbstractMesh.prototype._initCache = function () {
  8497. _super.prototype._initCache.call(this);
  8498. this._cache.localMatrixUpdated = false;
  8499. this._cache.position = BABYLON.Vector3.Zero();
  8500. this._cache.scaling = BABYLON.Vector3.Zero();
  8501. this._cache.rotation = BABYLON.Vector3.Zero();
  8502. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8503. this._cache.billboardMode = -1;
  8504. };
  8505. AbstractMesh.prototype.markAsDirty = function (property) {
  8506. if (property === "rotation") {
  8507. this.rotationQuaternion = null;
  8508. }
  8509. this._currentRenderId = Number.MAX_VALUE;
  8510. this._isDirty = true;
  8511. };
  8512. AbstractMesh.prototype._updateBoundingInfo = function () {
  8513. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8514. this._boundingInfo.update(this.worldMatrixFromCache);
  8515. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8516. };
  8517. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8518. if (!this.subMeshes) {
  8519. return;
  8520. }
  8521. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8522. var subMesh = this.subMeshes[subIndex];
  8523. if (!subMesh.IsGlobal) {
  8524. subMesh.updateBoundingInfo(matrix);
  8525. }
  8526. }
  8527. };
  8528. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8529. if (this._isWorldMatrixFrozen) {
  8530. return this._worldMatrix;
  8531. }
  8532. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8533. this._currentRenderId = this.getScene().getRenderId();
  8534. return this._worldMatrix;
  8535. }
  8536. this._cache.position.copyFrom(this.position);
  8537. this._cache.scaling.copyFrom(this.scaling);
  8538. this._cache.pivotMatrixUpdated = false;
  8539. this._cache.billboardMode = this.billboardMode;
  8540. this._currentRenderId = this.getScene().getRenderId();
  8541. this._isDirty = false;
  8542. // Scaling
  8543. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8544. // Rotation
  8545. //rotate, if quaternion is set and rotation was used
  8546. if (this.rotationQuaternion) {
  8547. var len = this.rotation.length();
  8548. if (len) {
  8549. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8550. this.rotation.copyFromFloats(0, 0, 0);
  8551. }
  8552. }
  8553. if (this.rotationQuaternion) {
  8554. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8555. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8556. }
  8557. else {
  8558. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8559. this._cache.rotation.copyFrom(this.rotation);
  8560. }
  8561. // Translation
  8562. if (this.infiniteDistance && !this.parent) {
  8563. var camera = this.getScene().activeCamera;
  8564. if (camera) {
  8565. var cameraWorldMatrix = camera.getWorldMatrix();
  8566. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8567. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8568. }
  8569. }
  8570. else {
  8571. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8572. }
  8573. // Composing transformations
  8574. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8575. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8576. // Billboarding
  8577. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8578. var localPosition = this.position.clone();
  8579. var zero = this.getScene().activeCamera.globalPosition.clone();
  8580. if (this.parent && this.parent.position) {
  8581. localPosition.addInPlace(this.parent.position);
  8582. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8583. }
  8584. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8585. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8586. zero.x = localPosition.x + BABYLON.Epsilon;
  8587. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8588. zero.y = localPosition.y + BABYLON.Epsilon;
  8589. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8590. zero.z = localPosition.z + BABYLON.Epsilon;
  8591. }
  8592. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8593. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8594. BABYLON.Tmp.Matrix[3].invert();
  8595. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8596. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8597. }
  8598. // Local world
  8599. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8600. // Parent
  8601. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8602. this._markSyncedWithParent();
  8603. if (this._meshToBoneReferal) {
  8604. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8605. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8606. }
  8607. else {
  8608. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8609. }
  8610. }
  8611. else {
  8612. this._worldMatrix.copyFrom(this._localWorld);
  8613. }
  8614. // Bounding info
  8615. this._updateBoundingInfo();
  8616. // Absolute position
  8617. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8618. // Callbacks
  8619. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8620. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8621. }
  8622. if (!this._poseMatrix) {
  8623. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8624. }
  8625. return this._worldMatrix;
  8626. };
  8627. /**
  8628. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8629. * @param func: callback function to add
  8630. */
  8631. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8632. this._onAfterWorldMatrixUpdate.push(func);
  8633. };
  8634. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8635. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8636. if (index > -1) {
  8637. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8638. }
  8639. };
  8640. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8641. this.computeWorldMatrix();
  8642. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8643. };
  8644. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8645. this.computeWorldMatrix();
  8646. var invLocalWorldMatrix = this._localWorld.clone();
  8647. invLocalWorldMatrix.invert();
  8648. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8649. };
  8650. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8651. this.computeWorldMatrix(true);
  8652. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8653. };
  8654. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8655. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8656. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8657. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8658. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8659. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8660. /// <returns>Mesh oriented towards targetMesh</returns>
  8661. yawCor = yawCor || 0; // default to zero if undefined
  8662. pitchCor = pitchCor || 0;
  8663. rollCor = rollCor || 0;
  8664. var dv = targetPoint.subtract(this.position);
  8665. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8666. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8667. var pitch = Math.atan2(dv.y, len);
  8668. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8669. };
  8670. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8671. this._meshToBoneReferal = affectedMesh;
  8672. this.parent = bone;
  8673. if (bone.getWorldMatrix().determinant() < 0) {
  8674. this.scalingDeterminant *= -1;
  8675. }
  8676. };
  8677. AbstractMesh.prototype.detachFromBone = function () {
  8678. if (this.parent.getWorldMatrix().determinant() < 0) {
  8679. this.scalingDeterminant *= -1;
  8680. }
  8681. this._meshToBoneReferal = null;
  8682. this.parent = null;
  8683. };
  8684. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8685. return this._boundingInfo.isInFrustum(frustumPlanes);
  8686. };
  8687. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8688. if (!camera) {
  8689. camera = this.getScene().activeCamera;
  8690. }
  8691. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8692. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8693. return false;
  8694. }
  8695. return true;
  8696. };
  8697. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8698. if (!this._boundingInfo || !mesh._boundingInfo) {
  8699. return false;
  8700. }
  8701. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8702. };
  8703. AbstractMesh.prototype.intersectsPoint = function (point) {
  8704. if (!this._boundingInfo) {
  8705. return false;
  8706. }
  8707. return this._boundingInfo.intersectsPoint(point);
  8708. };
  8709. // Physics
  8710. /**
  8711. * @Deprecated. Use new PhysicsImpostor instead.
  8712. * */
  8713. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8714. //legacy support
  8715. if (impostor.impostor) {
  8716. options = impostor;
  8717. impostor = impostor.impostor;
  8718. }
  8719. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8720. return this.physicsImpostor.physicsBody;
  8721. };
  8722. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8723. return this.physicsImpostor;
  8724. };
  8725. /**
  8726. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8727. */
  8728. AbstractMesh.prototype.getPhysicsMass = function () {
  8729. return this.physicsImpostor.getParam("mass");
  8730. };
  8731. /**
  8732. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8733. */
  8734. AbstractMesh.prototype.getPhysicsFriction = function () {
  8735. return this.physicsImpostor.getParam("friction");
  8736. };
  8737. /**
  8738. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8739. */
  8740. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8741. return this.physicsImpostor.getParam("resitution");
  8742. };
  8743. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8744. if (!camera) {
  8745. camera = this.getScene().activeCamera;
  8746. }
  8747. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8748. };
  8749. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8750. if (!camera) {
  8751. camera = this.getScene().activeCamera;
  8752. }
  8753. return this.absolutePosition.subtract(camera.position).length();
  8754. };
  8755. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8756. if (!this.physicsImpostor) {
  8757. return;
  8758. }
  8759. this.physicsImpostor.applyImpulse(force, contactPoint);
  8760. };
  8761. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8762. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8763. return;
  8764. }
  8765. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8766. mainPivot: pivot1,
  8767. connectedPivot: pivot2,
  8768. nativeParams: options
  8769. });
  8770. };
  8771. /**
  8772. * @Deprecated
  8773. */
  8774. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8775. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8776. this.updatePhysicsBody();
  8777. };
  8778. /**
  8779. * @Deprecated
  8780. * Calling this function is not needed anymore.
  8781. * The physics engine takes care of transofmration automatically.
  8782. */
  8783. AbstractMesh.prototype.updatePhysicsBody = function () {
  8784. //Unneeded
  8785. };
  8786. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8787. // Collisions
  8788. get: function () {
  8789. return this._checkCollisions;
  8790. },
  8791. set: function (collisionEnabled) {
  8792. this._checkCollisions = collisionEnabled;
  8793. if (this.getScene().workerCollisions) {
  8794. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8795. }
  8796. },
  8797. enumerable: true,
  8798. configurable: true
  8799. });
  8800. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8801. var globalPosition = this.getAbsolutePosition();
  8802. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8803. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8804. this._collider.radius = this.ellipsoid;
  8805. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8806. };
  8807. // Submeshes octree
  8808. /**
  8809. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8810. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8811. */
  8812. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8813. if (maxCapacity === void 0) { maxCapacity = 64; }
  8814. if (maxDepth === void 0) { maxDepth = 2; }
  8815. if (!this._submeshesOctree) {
  8816. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8817. }
  8818. this.computeWorldMatrix(true);
  8819. // Update octree
  8820. var bbox = this.getBoundingInfo().boundingBox;
  8821. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8822. return this._submeshesOctree;
  8823. };
  8824. // Collisions
  8825. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8826. this._generatePointsArray();
  8827. // Transformation
  8828. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8829. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8830. subMesh._lastColliderWorldVertices = [];
  8831. subMesh._trianglePlanes = [];
  8832. var start = subMesh.verticesStart;
  8833. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8834. for (var i = start; i < end; i++) {
  8835. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8836. }
  8837. }
  8838. // Collide
  8839. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8840. if (collider.collisionFound) {
  8841. collider.collidedMesh = this;
  8842. }
  8843. };
  8844. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8845. var subMeshes;
  8846. var len;
  8847. // Octrees
  8848. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8849. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8850. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8851. len = intersections.length;
  8852. subMeshes = intersections.data;
  8853. }
  8854. else {
  8855. subMeshes = this.subMeshes;
  8856. len = subMeshes.length;
  8857. }
  8858. for (var index = 0; index < len; index++) {
  8859. var subMesh = subMeshes[index];
  8860. // Bounding test
  8861. if (len > 1 && !subMesh._checkCollision(collider))
  8862. continue;
  8863. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8864. }
  8865. };
  8866. AbstractMesh.prototype._checkCollision = function (collider) {
  8867. // Bounding box test
  8868. if (!this._boundingInfo._checkCollision(collider))
  8869. return;
  8870. // Transformation matrix
  8871. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8872. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8873. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8874. };
  8875. // Picking
  8876. AbstractMesh.prototype._generatePointsArray = function () {
  8877. return false;
  8878. };
  8879. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8880. var pickingInfo = new BABYLON.PickingInfo();
  8881. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8882. return pickingInfo;
  8883. }
  8884. if (!this._generatePointsArray()) {
  8885. return pickingInfo;
  8886. }
  8887. var intersectInfo = null;
  8888. // Octrees
  8889. var subMeshes;
  8890. var len;
  8891. if (this._submeshesOctree && this.useOctreeForPicking) {
  8892. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8893. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8894. len = intersections.length;
  8895. subMeshes = intersections.data;
  8896. }
  8897. else {
  8898. subMeshes = this.subMeshes;
  8899. len = subMeshes.length;
  8900. }
  8901. for (var index = 0; index < len; index++) {
  8902. var subMesh = subMeshes[index];
  8903. // Bounding test
  8904. if (len > 1 && !subMesh.canIntersects(ray))
  8905. continue;
  8906. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8907. if (currentIntersectInfo) {
  8908. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8909. intersectInfo = currentIntersectInfo;
  8910. intersectInfo.subMeshId = index;
  8911. if (fastCheck) {
  8912. break;
  8913. }
  8914. }
  8915. }
  8916. }
  8917. if (intersectInfo) {
  8918. // Get picked point
  8919. var world = this.getWorldMatrix();
  8920. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8921. var direction = ray.direction.clone();
  8922. direction = direction.scale(intersectInfo.distance);
  8923. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8924. var pickedPoint = worldOrigin.add(worldDirection);
  8925. // Return result
  8926. pickingInfo.hit = true;
  8927. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8928. pickingInfo.pickedPoint = pickedPoint;
  8929. pickingInfo.pickedMesh = this;
  8930. pickingInfo.bu = intersectInfo.bu;
  8931. pickingInfo.bv = intersectInfo.bv;
  8932. pickingInfo.faceId = intersectInfo.faceId;
  8933. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8934. return pickingInfo;
  8935. }
  8936. return pickingInfo;
  8937. };
  8938. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8939. return null;
  8940. };
  8941. AbstractMesh.prototype.releaseSubMeshes = function () {
  8942. if (this.subMeshes) {
  8943. while (this.subMeshes.length) {
  8944. this.subMeshes[0].dispose();
  8945. }
  8946. }
  8947. else {
  8948. this.subMeshes = new Array();
  8949. }
  8950. };
  8951. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8952. var index;
  8953. // Action manager
  8954. if (this.actionManager) {
  8955. this.actionManager.dispose();
  8956. this.actionManager = null;
  8957. }
  8958. // Skeleton
  8959. this.skeleton = null;
  8960. // Animations
  8961. this.getScene().stopAnimation(this);
  8962. // Physics
  8963. if (this.physicsImpostor) {
  8964. this.physicsImpostor.dispose(!doNotRecurse);
  8965. }
  8966. // Intersections in progress
  8967. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8968. var other = this._intersectionsInProgress[index];
  8969. var pos = other._intersectionsInProgress.indexOf(this);
  8970. other._intersectionsInProgress.splice(pos, 1);
  8971. }
  8972. this._intersectionsInProgress = [];
  8973. // Edges
  8974. if (this._edgesRenderer) {
  8975. this._edgesRenderer.dispose();
  8976. this._edgesRenderer = null;
  8977. }
  8978. // SubMeshes
  8979. this.releaseSubMeshes();
  8980. // Remove from scene
  8981. this.getScene().removeMesh(this);
  8982. if (!doNotRecurse) {
  8983. // Particles
  8984. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8985. if (this.getScene().particleSystems[index].emitter === this) {
  8986. this.getScene().particleSystems[index].dispose();
  8987. index--;
  8988. }
  8989. }
  8990. // Children
  8991. var objects = this.getScene().meshes.slice(0);
  8992. for (index = 0; index < objects.length; index++) {
  8993. if (objects[index].parent === this) {
  8994. objects[index].dispose();
  8995. }
  8996. }
  8997. }
  8998. else {
  8999. for (index = 0; index < this.getScene().meshes.length; index++) {
  9000. var obj = this.getScene().meshes[index];
  9001. if (obj.parent === this) {
  9002. obj.parent = null;
  9003. obj.computeWorldMatrix(true);
  9004. }
  9005. }
  9006. }
  9007. this._onAfterWorldMatrixUpdate = [];
  9008. this._isDisposed = true;
  9009. // Callback
  9010. if (this.onDispose) {
  9011. this.onDispose();
  9012. }
  9013. };
  9014. // Statics
  9015. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9016. AbstractMesh._BILLBOARDMODE_X = 1;
  9017. AbstractMesh._BILLBOARDMODE_Y = 2;
  9018. AbstractMesh._BILLBOARDMODE_Z = 4;
  9019. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9020. return AbstractMesh;
  9021. })(BABYLON.Node);
  9022. BABYLON.AbstractMesh = AbstractMesh;
  9023. })(BABYLON || (BABYLON = {}));
  9024. var BABYLON;
  9025. (function (BABYLON) {
  9026. var Light = (function (_super) {
  9027. __extends(Light, _super);
  9028. function Light(name, scene) {
  9029. _super.call(this, name, scene);
  9030. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9031. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9032. this.intensity = 1.0;
  9033. this.range = Number.MAX_VALUE;
  9034. this.includeOnlyWithLayerMask = 0;
  9035. this.includedOnlyMeshes = new Array();
  9036. this.excludedMeshes = new Array();
  9037. this.excludeWithLayerMask = 0;
  9038. // PBR Properties.
  9039. this.radius = 0.00001;
  9040. this._excludedMeshesIds = new Array();
  9041. this._includedOnlyMeshesIds = new Array();
  9042. scene.addLight(this);
  9043. }
  9044. /**
  9045. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9046. */
  9047. Light.prototype.toString = function (fullDetails) {
  9048. var ret = "Name: " + this.name;
  9049. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9050. if (this.animations) {
  9051. for (var i = 0; i < this.animations.length; i++) {
  9052. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9053. }
  9054. }
  9055. if (fullDetails) {
  9056. }
  9057. return ret;
  9058. };
  9059. Light.prototype.getShadowGenerator = function () {
  9060. return this._shadowGenerator;
  9061. };
  9062. Light.prototype.getAbsolutePosition = function () {
  9063. return BABYLON.Vector3.Zero();
  9064. };
  9065. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9066. };
  9067. Light.prototype._getWorldMatrix = function () {
  9068. return BABYLON.Matrix.Identity();
  9069. };
  9070. Light.prototype.canAffectMesh = function (mesh) {
  9071. if (!mesh) {
  9072. return true;
  9073. }
  9074. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9075. return false;
  9076. }
  9077. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9078. return false;
  9079. }
  9080. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9081. return false;
  9082. }
  9083. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9084. return false;
  9085. }
  9086. return true;
  9087. };
  9088. Light.prototype.getWorldMatrix = function () {
  9089. this._currentRenderId = this.getScene().getRenderId();
  9090. var worldMatrix = this._getWorldMatrix();
  9091. if (this.parent && this.parent.getWorldMatrix) {
  9092. if (!this._parentedWorldMatrix) {
  9093. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9094. }
  9095. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9096. this._markSyncedWithParent();
  9097. return this._parentedWorldMatrix;
  9098. }
  9099. return worldMatrix;
  9100. };
  9101. Light.prototype.dispose = function () {
  9102. if (this._shadowGenerator) {
  9103. this._shadowGenerator.dispose();
  9104. this._shadowGenerator = null;
  9105. }
  9106. // Animations
  9107. this.getScene().stopAnimation(this);
  9108. // Remove from scene
  9109. this.getScene().removeLight(this);
  9110. };
  9111. Light.prototype.getTypeID = function () {
  9112. return 0;
  9113. };
  9114. Light.prototype.clone = function (name) {
  9115. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9116. };
  9117. Light.prototype.serialize = function () {
  9118. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9119. // Type
  9120. serializationObject.type = this.getTypeID();
  9121. // Parent
  9122. if (this.parent) {
  9123. serializationObject.parentId = this.parent.id;
  9124. }
  9125. // Animations
  9126. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9127. serializationObject.ranges = this.serializeAnimationRanges();
  9128. return serializationObject;
  9129. };
  9130. Light.GetConstructorFromName = function (type, name, scene) {
  9131. switch (type) {
  9132. case 0:
  9133. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9134. case 1:
  9135. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9136. case 2:
  9137. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9138. case 3:
  9139. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9140. }
  9141. };
  9142. Light.Parse = function (parsedLight, scene) {
  9143. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9144. // Inclusion / exclusions
  9145. if (parsedLight.excludedMeshesIds) {
  9146. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9147. }
  9148. if (parsedLight.includedOnlyMeshesIds) {
  9149. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9150. }
  9151. // Parent
  9152. if (parsedLight.parentId) {
  9153. light._waitingParentId = parsedLight.parentId;
  9154. }
  9155. // Animations
  9156. if (parsedLight.animations) {
  9157. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9158. var parsedAnimation = parsedLight.animations[animationIndex];
  9159. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9160. }
  9161. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9162. }
  9163. if (parsedLight.autoAnimate) {
  9164. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9165. }
  9166. return light;
  9167. };
  9168. __decorate([
  9169. BABYLON.serializeAsColor3()
  9170. ], Light.prototype, "diffuse", void 0);
  9171. __decorate([
  9172. BABYLON.serializeAsColor3()
  9173. ], Light.prototype, "specular", void 0);
  9174. __decorate([
  9175. BABYLON.serialize()
  9176. ], Light.prototype, "intensity", void 0);
  9177. __decorate([
  9178. BABYLON.serialize()
  9179. ], Light.prototype, "range", void 0);
  9180. __decorate([
  9181. BABYLON.serialize()
  9182. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9183. __decorate([
  9184. BABYLON.serialize()
  9185. ], Light.prototype, "radius", void 0);
  9186. return Light;
  9187. })(BABYLON.Node);
  9188. BABYLON.Light = Light;
  9189. })(BABYLON || (BABYLON = {}));
  9190. var BABYLON;
  9191. (function (BABYLON) {
  9192. var PointLight = (function (_super) {
  9193. __extends(PointLight, _super);
  9194. function PointLight(name, position, scene) {
  9195. _super.call(this, name, scene);
  9196. this.position = position;
  9197. }
  9198. PointLight.prototype.getAbsolutePosition = function () {
  9199. return this.transformedPosition ? this.transformedPosition : this.position;
  9200. };
  9201. PointLight.prototype.computeTransformedPosition = function () {
  9202. if (this.parent && this.parent.getWorldMatrix) {
  9203. if (!this.transformedPosition) {
  9204. this.transformedPosition = BABYLON.Vector3.Zero();
  9205. }
  9206. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9207. return true;
  9208. }
  9209. return false;
  9210. };
  9211. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9212. if (this.parent && this.parent.getWorldMatrix) {
  9213. this.computeTransformedPosition();
  9214. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9215. return;
  9216. }
  9217. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9218. };
  9219. PointLight.prototype.needCube = function () {
  9220. return true;
  9221. };
  9222. PointLight.prototype.supportsVSM = function () {
  9223. return false;
  9224. };
  9225. PointLight.prototype.needRefreshPerFrame = function () {
  9226. return false;
  9227. };
  9228. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9229. switch (faceIndex) {
  9230. case 0:
  9231. return new BABYLON.Vector3(1, 0, 0);
  9232. case 1:
  9233. return new BABYLON.Vector3(-1, 0, 0);
  9234. case 2:
  9235. return new BABYLON.Vector3(0, -1, 0);
  9236. case 3:
  9237. return new BABYLON.Vector3(0, 1, 0);
  9238. case 4:
  9239. return new BABYLON.Vector3(0, 0, 1);
  9240. case 5:
  9241. return new BABYLON.Vector3(0, 0, -1);
  9242. }
  9243. return BABYLON.Vector3.Zero();
  9244. };
  9245. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9246. var activeCamera = this.getScene().activeCamera;
  9247. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9248. };
  9249. PointLight.prototype._getWorldMatrix = function () {
  9250. if (!this._worldMatrix) {
  9251. this._worldMatrix = BABYLON.Matrix.Identity();
  9252. }
  9253. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9254. return this._worldMatrix;
  9255. };
  9256. PointLight.prototype.getTypeID = function () {
  9257. return 0;
  9258. };
  9259. __decorate([
  9260. BABYLON.serializeAsVector3()
  9261. ], PointLight.prototype, "position", void 0);
  9262. return PointLight;
  9263. })(BABYLON.Light);
  9264. BABYLON.PointLight = PointLight;
  9265. })(BABYLON || (BABYLON = {}));
  9266. var BABYLON;
  9267. (function (BABYLON) {
  9268. var SpotLight = (function (_super) {
  9269. __extends(SpotLight, _super);
  9270. function SpotLight(name, position, direction, angle, exponent, scene) {
  9271. _super.call(this, name, scene);
  9272. this.position = position;
  9273. this.direction = direction;
  9274. this.angle = angle;
  9275. this.exponent = exponent;
  9276. }
  9277. SpotLight.prototype.getAbsolutePosition = function () {
  9278. return this.transformedPosition ? this.transformedPosition : this.position;
  9279. };
  9280. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9281. var activeCamera = this.getScene().activeCamera;
  9282. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9283. };
  9284. SpotLight.prototype.needCube = function () {
  9285. return false;
  9286. };
  9287. SpotLight.prototype.supportsVSM = function () {
  9288. return true;
  9289. };
  9290. SpotLight.prototype.needRefreshPerFrame = function () {
  9291. return false;
  9292. };
  9293. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9294. return this.direction;
  9295. };
  9296. SpotLight.prototype.setDirectionToTarget = function (target) {
  9297. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9298. return this.direction;
  9299. };
  9300. SpotLight.prototype.computeTransformedPosition = function () {
  9301. if (this.parent && this.parent.getWorldMatrix) {
  9302. if (!this.transformedPosition) {
  9303. this.transformedPosition = BABYLON.Vector3.Zero();
  9304. }
  9305. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9306. return true;
  9307. }
  9308. return false;
  9309. };
  9310. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9311. var normalizeDirection;
  9312. if (this.parent && this.parent.getWorldMatrix) {
  9313. if (!this._transformedDirection) {
  9314. this._transformedDirection = BABYLON.Vector3.Zero();
  9315. }
  9316. this.computeTransformedPosition();
  9317. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9318. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9319. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9320. }
  9321. else {
  9322. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9323. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9324. }
  9325. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9326. };
  9327. SpotLight.prototype._getWorldMatrix = function () {
  9328. if (!this._worldMatrix) {
  9329. this._worldMatrix = BABYLON.Matrix.Identity();
  9330. }
  9331. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9332. return this._worldMatrix;
  9333. };
  9334. SpotLight.prototype.getTypeID = function () {
  9335. return 2;
  9336. };
  9337. __decorate([
  9338. BABYLON.serializeAsVector3()
  9339. ], SpotLight.prototype, "position", void 0);
  9340. __decorate([
  9341. BABYLON.serializeAsVector3()
  9342. ], SpotLight.prototype, "direction", void 0);
  9343. __decorate([
  9344. BABYLON.serialize()
  9345. ], SpotLight.prototype, "angle", void 0);
  9346. __decorate([
  9347. BABYLON.serialize()
  9348. ], SpotLight.prototype, "exponent", void 0);
  9349. return SpotLight;
  9350. })(BABYLON.Light);
  9351. BABYLON.SpotLight = SpotLight;
  9352. })(BABYLON || (BABYLON = {}));
  9353. var BABYLON;
  9354. (function (BABYLON) {
  9355. var HemisphericLight = (function (_super) {
  9356. __extends(HemisphericLight, _super);
  9357. function HemisphericLight(name, direction, scene) {
  9358. _super.call(this, name, scene);
  9359. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9360. this.direction = direction;
  9361. }
  9362. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9363. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9364. return this.direction;
  9365. };
  9366. HemisphericLight.prototype.getShadowGenerator = function () {
  9367. return null;
  9368. };
  9369. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9370. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9371. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9372. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9373. };
  9374. HemisphericLight.prototype._getWorldMatrix = function () {
  9375. if (!this._worldMatrix) {
  9376. this._worldMatrix = BABYLON.Matrix.Identity();
  9377. }
  9378. return this._worldMatrix;
  9379. };
  9380. HemisphericLight.prototype.getTypeID = function () {
  9381. return 3;
  9382. };
  9383. __decorate([
  9384. BABYLON.serializeAsColor3()
  9385. ], HemisphericLight.prototype, "groundColor", void 0);
  9386. __decorate([
  9387. BABYLON.serializeAsVector3()
  9388. ], HemisphericLight.prototype, "direction", void 0);
  9389. return HemisphericLight;
  9390. })(BABYLON.Light);
  9391. BABYLON.HemisphericLight = HemisphericLight;
  9392. })(BABYLON || (BABYLON = {}));
  9393. var BABYLON;
  9394. (function (BABYLON) {
  9395. var DirectionalLight = (function (_super) {
  9396. __extends(DirectionalLight, _super);
  9397. function DirectionalLight(name, direction, scene) {
  9398. _super.call(this, name, scene);
  9399. this.shadowOrthoScale = 0.5;
  9400. this.autoUpdateExtends = true;
  9401. // Cache
  9402. this._orthoLeft = Number.MAX_VALUE;
  9403. this._orthoRight = Number.MIN_VALUE;
  9404. this._orthoTop = Number.MIN_VALUE;
  9405. this._orthoBottom = Number.MAX_VALUE;
  9406. this.position = direction.scale(-1);
  9407. this.direction = direction;
  9408. }
  9409. DirectionalLight.prototype.getAbsolutePosition = function () {
  9410. return this.transformedPosition ? this.transformedPosition : this.position;
  9411. };
  9412. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9413. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9414. return this.direction;
  9415. };
  9416. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9417. var activeCamera = this.getScene().activeCamera;
  9418. // Check extends
  9419. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9420. var tempVector3 = BABYLON.Vector3.Zero();
  9421. this._orthoLeft = Number.MAX_VALUE;
  9422. this._orthoRight = Number.MIN_VALUE;
  9423. this._orthoTop = Number.MIN_VALUE;
  9424. this._orthoBottom = Number.MAX_VALUE;
  9425. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9426. var mesh = renderList[meshIndex];
  9427. if (!mesh) {
  9428. continue;
  9429. }
  9430. var boundingInfo = mesh.getBoundingInfo();
  9431. if (!boundingInfo) {
  9432. continue;
  9433. }
  9434. var boundingBox = boundingInfo.boundingBox;
  9435. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9436. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9437. if (tempVector3.x < this._orthoLeft)
  9438. this._orthoLeft = tempVector3.x;
  9439. if (tempVector3.y < this._orthoBottom)
  9440. this._orthoBottom = tempVector3.y;
  9441. if (tempVector3.x > this._orthoRight)
  9442. this._orthoRight = tempVector3.x;
  9443. if (tempVector3.y > this._orthoTop)
  9444. this._orthoTop = tempVector3.y;
  9445. }
  9446. }
  9447. }
  9448. var xOffset = this._orthoRight - this._orthoLeft;
  9449. var yOffset = this._orthoTop - this._orthoBottom;
  9450. 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);
  9451. };
  9452. DirectionalLight.prototype.supportsVSM = function () {
  9453. return true;
  9454. };
  9455. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9456. return true;
  9457. };
  9458. DirectionalLight.prototype.needCube = function () {
  9459. return false;
  9460. };
  9461. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9462. return this.direction;
  9463. };
  9464. DirectionalLight.prototype.computeTransformedPosition = function () {
  9465. if (this.parent && this.parent.getWorldMatrix) {
  9466. if (!this.transformedPosition) {
  9467. this.transformedPosition = BABYLON.Vector3.Zero();
  9468. }
  9469. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9470. return true;
  9471. }
  9472. return false;
  9473. };
  9474. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9475. if (this.parent && this.parent.getWorldMatrix) {
  9476. if (!this._transformedDirection) {
  9477. this._transformedDirection = BABYLON.Vector3.Zero();
  9478. }
  9479. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9480. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9481. return;
  9482. }
  9483. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9484. };
  9485. DirectionalLight.prototype._getWorldMatrix = function () {
  9486. if (!this._worldMatrix) {
  9487. this._worldMatrix = BABYLON.Matrix.Identity();
  9488. }
  9489. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9490. return this._worldMatrix;
  9491. };
  9492. DirectionalLight.prototype.getTypeID = function () {
  9493. return 1;
  9494. };
  9495. __decorate([
  9496. BABYLON.serializeAsVector3()
  9497. ], DirectionalLight.prototype, "position", void 0);
  9498. __decorate([
  9499. BABYLON.serializeAsVector3()
  9500. ], DirectionalLight.prototype, "direction", void 0);
  9501. __decorate([
  9502. BABYLON.serialize()
  9503. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9504. __decorate([
  9505. BABYLON.serialize()
  9506. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9507. return DirectionalLight;
  9508. })(BABYLON.Light);
  9509. BABYLON.DirectionalLight = DirectionalLight;
  9510. })(BABYLON || (BABYLON = {}));
  9511. var BABYLON;
  9512. (function (BABYLON) {
  9513. var ShadowGenerator = (function () {
  9514. function ShadowGenerator(mapSize, light) {
  9515. var _this = this;
  9516. // Members
  9517. this._filter = ShadowGenerator.FILTER_NONE;
  9518. this.blurScale = 2;
  9519. this._blurBoxOffset = 0;
  9520. this._bias = 0.00005;
  9521. this._lightDirection = BABYLON.Vector3.Zero();
  9522. this.forceBackFacesOnly = false;
  9523. this._darkness = 0;
  9524. this._transparencyShadow = false;
  9525. this._viewMatrix = BABYLON.Matrix.Zero();
  9526. this._projectionMatrix = BABYLON.Matrix.Zero();
  9527. this._transformMatrix = BABYLON.Matrix.Zero();
  9528. this._worldViewProjection = BABYLON.Matrix.Zero();
  9529. this._currentFaceIndex = 0;
  9530. this._currentFaceIndexCache = 0;
  9531. this._light = light;
  9532. this._scene = light.getScene();
  9533. this._mapSize = mapSize;
  9534. light._shadowGenerator = this;
  9535. // Render target
  9536. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9537. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9538. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9539. this._shadowMap.anisotropicFilteringLevel = 1;
  9540. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9541. this._shadowMap.renderParticles = false;
  9542. this._shadowMap.onBeforeRender = function (faceIndex) {
  9543. _this._currentFaceIndex = faceIndex;
  9544. };
  9545. this._shadowMap.onAfterUnbind = function () {
  9546. if (!_this.useBlurVarianceShadowMap) {
  9547. return;
  9548. }
  9549. if (!_this._shadowMap2) {
  9550. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9551. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9552. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9553. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9554. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9555. _this._downSamplePostprocess.onApply = function (effect) {
  9556. effect.setTexture("textureSampler", _this._shadowMap);
  9557. };
  9558. _this.blurBoxOffset = 1;
  9559. }
  9560. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9561. };
  9562. // Custom render function
  9563. var renderSubMesh = function (subMesh) {
  9564. var mesh = subMesh.getRenderingMesh();
  9565. var scene = _this._scene;
  9566. var engine = scene.getEngine();
  9567. // Culling
  9568. engine.setState(subMesh.getMaterial().backFaceCulling);
  9569. // Managing instances
  9570. var batch = mesh._getInstancesRenderList(subMesh._id);
  9571. if (batch.mustReturn) {
  9572. return;
  9573. }
  9574. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9575. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9576. engine.enableEffect(_this._effect);
  9577. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9578. var material = subMesh.getMaterial();
  9579. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9580. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9581. if (_this.getLight().needCube()) {
  9582. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9583. }
  9584. // Alpha test
  9585. if (material && material.needAlphaTesting()) {
  9586. var alphaTexture = material.getAlphaTestTexture();
  9587. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9588. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9589. }
  9590. // Bones
  9591. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9592. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9593. }
  9594. if (_this.forceBackFacesOnly) {
  9595. engine.setState(true, 0, false, true);
  9596. }
  9597. // Draw
  9598. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9599. if (_this.forceBackFacesOnly) {
  9600. engine.setState(true, 0, false, false);
  9601. }
  9602. }
  9603. else {
  9604. // Need to reset refresh rate of the shadowMap
  9605. _this._shadowMap.resetRefreshCounter();
  9606. }
  9607. };
  9608. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9609. var index;
  9610. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9611. renderSubMesh(opaqueSubMeshes.data[index]);
  9612. }
  9613. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9614. renderSubMesh(alphaTestSubMeshes.data[index]);
  9615. }
  9616. if (_this._transparencyShadow) {
  9617. for (index = 0; index < transparentSubMeshes.length; index++) {
  9618. renderSubMesh(transparentSubMeshes.data[index]);
  9619. }
  9620. }
  9621. };
  9622. this._shadowMap.onClear = function (engine) {
  9623. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9624. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9625. }
  9626. else {
  9627. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9628. }
  9629. };
  9630. }
  9631. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9632. // Static
  9633. get: function () {
  9634. return ShadowGenerator._FILTER_NONE;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9640. get: function () {
  9641. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9642. },
  9643. enumerable: true,
  9644. configurable: true
  9645. });
  9646. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9647. get: function () {
  9648. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9649. },
  9650. enumerable: true,
  9651. configurable: true
  9652. });
  9653. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9654. get: function () {
  9655. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9656. },
  9657. enumerable: true,
  9658. configurable: true
  9659. });
  9660. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9661. get: function () {
  9662. return this._bias;
  9663. },
  9664. set: function (bias) {
  9665. this._bias = bias;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9671. get: function () {
  9672. return this._blurBoxOffset;
  9673. },
  9674. set: function (value) {
  9675. var _this = this;
  9676. if (this._blurBoxOffset === value) {
  9677. return;
  9678. }
  9679. this._blurBoxOffset = value;
  9680. if (this._boxBlurPostprocess) {
  9681. this._boxBlurPostprocess.dispose();
  9682. }
  9683. 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);
  9684. this._boxBlurPostprocess.onApply = function (effect) {
  9685. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9686. };
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9692. get: function () {
  9693. return this._filter;
  9694. },
  9695. set: function (value) {
  9696. if (this._filter === value) {
  9697. return;
  9698. }
  9699. this._filter = value;
  9700. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9701. this._shadowMap.anisotropicFilteringLevel = 16;
  9702. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9703. }
  9704. else {
  9705. this._shadowMap.anisotropicFilteringLevel = 1;
  9706. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9707. }
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9713. get: function () {
  9714. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9715. },
  9716. set: function (value) {
  9717. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9718. },
  9719. enumerable: true,
  9720. configurable: true
  9721. });
  9722. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9723. get: function () {
  9724. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9725. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9726. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9727. },
  9728. set: function (value) {
  9729. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9735. get: function () {
  9736. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9737. },
  9738. set: function (value) {
  9739. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9740. },
  9741. enumerable: true,
  9742. configurable: true
  9743. });
  9744. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9745. var defines = [];
  9746. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9747. defines.push("#define VSM");
  9748. }
  9749. if (this.getLight().needCube()) {
  9750. defines.push("#define CUBEMAP");
  9751. }
  9752. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9753. var mesh = subMesh.getMesh();
  9754. var material = subMesh.getMaterial();
  9755. // Alpha test
  9756. if (material && material.needAlphaTesting()) {
  9757. defines.push("#define ALPHATEST");
  9758. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9759. attribs.push(BABYLON.VertexBuffer.UVKind);
  9760. defines.push("#define UV1");
  9761. }
  9762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9763. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9764. defines.push("#define UV2");
  9765. }
  9766. }
  9767. // Bones
  9768. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9769. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9770. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9771. if (mesh.numBoneInfluencers > 4) {
  9772. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9773. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9774. }
  9775. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9776. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9777. }
  9778. else {
  9779. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9780. }
  9781. // Instances
  9782. if (useInstances) {
  9783. defines.push("#define INSTANCES");
  9784. attribs.push("world0");
  9785. attribs.push("world1");
  9786. attribs.push("world2");
  9787. attribs.push("world3");
  9788. }
  9789. // Get correct effect
  9790. var join = defines.join("\n");
  9791. if (this._cachedDefines !== join) {
  9792. this._cachedDefines = join;
  9793. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9794. }
  9795. return this._effect.isReady();
  9796. };
  9797. ShadowGenerator.prototype.getShadowMap = function () {
  9798. return this._shadowMap;
  9799. };
  9800. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9801. if (this._shadowMap2) {
  9802. return this._shadowMap2;
  9803. }
  9804. return this._shadowMap;
  9805. };
  9806. ShadowGenerator.prototype.getLight = function () {
  9807. return this._light;
  9808. };
  9809. // Methods
  9810. ShadowGenerator.prototype.getTransformMatrix = function () {
  9811. var scene = this._scene;
  9812. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9813. return this._transformMatrix;
  9814. }
  9815. this._currentRenderID = scene.getRenderId();
  9816. this._currentFaceIndexCache = this._currentFaceIndex;
  9817. var lightPosition = this._light.position;
  9818. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9819. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9820. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9821. }
  9822. if (this._light.computeTransformedPosition()) {
  9823. lightPosition = this._light.transformedPosition;
  9824. }
  9825. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9826. this._cachedPosition = lightPosition.clone();
  9827. this._cachedDirection = this._lightDirection.clone();
  9828. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9829. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9830. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9831. }
  9832. return this._transformMatrix;
  9833. };
  9834. ShadowGenerator.prototype.getDarkness = function () {
  9835. return this._darkness;
  9836. };
  9837. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9838. if (darkness >= 1.0)
  9839. this._darkness = 1.0;
  9840. else if (darkness <= 0.0)
  9841. this._darkness = 0.0;
  9842. else
  9843. this._darkness = darkness;
  9844. };
  9845. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9846. this._transparencyShadow = hasShadow;
  9847. };
  9848. ShadowGenerator.prototype._packHalf = function (depth) {
  9849. var scale = depth * 255.0;
  9850. var fract = scale - Math.floor(scale);
  9851. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9852. };
  9853. ShadowGenerator.prototype.dispose = function () {
  9854. this._shadowMap.dispose();
  9855. if (this._shadowMap2) {
  9856. this._shadowMap2.dispose();
  9857. }
  9858. if (this._downSamplePostprocess) {
  9859. this._downSamplePostprocess.dispose();
  9860. }
  9861. if (this._boxBlurPostprocess) {
  9862. this._boxBlurPostprocess.dispose();
  9863. }
  9864. };
  9865. ShadowGenerator.prototype.serialize = function () {
  9866. var serializationObject = {};
  9867. serializationObject.lightId = this._light.id;
  9868. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9869. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9870. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9871. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9872. serializationObject.renderList = [];
  9873. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9874. var mesh = this.getShadowMap().renderList[meshIndex];
  9875. serializationObject.renderList.push(mesh.id);
  9876. }
  9877. return serializationObject;
  9878. };
  9879. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9880. //casting to point light, as light is missing the position attr and typescript complains.
  9881. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9882. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9883. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9884. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9885. shadowGenerator.getShadowMap().renderList.push(mesh);
  9886. }
  9887. if (parsedShadowGenerator.usePoissonSampling) {
  9888. shadowGenerator.usePoissonSampling = true;
  9889. }
  9890. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9891. shadowGenerator.useVarianceShadowMap = true;
  9892. }
  9893. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9894. shadowGenerator.useBlurVarianceShadowMap = true;
  9895. if (parsedShadowGenerator.blurScale) {
  9896. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9897. }
  9898. if (parsedShadowGenerator.blurBoxOffset) {
  9899. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9900. }
  9901. }
  9902. if (parsedShadowGenerator.bias !== undefined) {
  9903. shadowGenerator.bias = parsedShadowGenerator.bias;
  9904. }
  9905. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9906. return shadowGenerator;
  9907. };
  9908. ShadowGenerator._FILTER_NONE = 0;
  9909. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9910. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9911. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9912. return ShadowGenerator;
  9913. })();
  9914. BABYLON.ShadowGenerator = ShadowGenerator;
  9915. })(BABYLON || (BABYLON = {}));
  9916. var BABYLON;
  9917. (function (BABYLON) {
  9918. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9919. if (boxMin.x > sphereCenter.x + sphereRadius)
  9920. return false;
  9921. if (sphereCenter.x - sphereRadius > boxMax.x)
  9922. return false;
  9923. if (boxMin.y > sphereCenter.y + sphereRadius)
  9924. return false;
  9925. if (sphereCenter.y - sphereRadius > boxMax.y)
  9926. return false;
  9927. if (boxMin.z > sphereCenter.z + sphereRadius)
  9928. return false;
  9929. if (sphereCenter.z - sphereRadius > boxMax.z)
  9930. return false;
  9931. return true;
  9932. };
  9933. var getLowestRoot = function (a, b, c, maxR) {
  9934. var determinant = b * b - 4.0 * a * c;
  9935. var result = { root: 0, found: false };
  9936. if (determinant < 0)
  9937. return result;
  9938. var sqrtD = Math.sqrt(determinant);
  9939. var r1 = (-b - sqrtD) / (2.0 * a);
  9940. var r2 = (-b + sqrtD) / (2.0 * a);
  9941. if (r1 > r2) {
  9942. var temp = r2;
  9943. r2 = r1;
  9944. r1 = temp;
  9945. }
  9946. if (r1 > 0 && r1 < maxR) {
  9947. result.root = r1;
  9948. result.found = true;
  9949. return result;
  9950. }
  9951. if (r2 > 0 && r2 < maxR) {
  9952. result.root = r2;
  9953. result.found = true;
  9954. return result;
  9955. }
  9956. return result;
  9957. };
  9958. var Collider = (function () {
  9959. function Collider() {
  9960. this.radius = new BABYLON.Vector3(1, 1, 1);
  9961. this.retry = 0;
  9962. this.basePointWorld = BABYLON.Vector3.Zero();
  9963. this.velocityWorld = BABYLON.Vector3.Zero();
  9964. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9965. this._collisionPoint = BABYLON.Vector3.Zero();
  9966. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9967. this._tempVector = BABYLON.Vector3.Zero();
  9968. this._tempVector2 = BABYLON.Vector3.Zero();
  9969. this._tempVector3 = BABYLON.Vector3.Zero();
  9970. this._tempVector4 = BABYLON.Vector3.Zero();
  9971. this._edge = BABYLON.Vector3.Zero();
  9972. this._baseToVertex = BABYLON.Vector3.Zero();
  9973. this._destinationPoint = BABYLON.Vector3.Zero();
  9974. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9975. this._displacementVector = BABYLON.Vector3.Zero();
  9976. }
  9977. // Methods
  9978. Collider.prototype._initialize = function (source, dir, e) {
  9979. this.velocity = dir;
  9980. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9981. this.basePoint = source;
  9982. source.multiplyToRef(this.radius, this.basePointWorld);
  9983. dir.multiplyToRef(this.radius, this.velocityWorld);
  9984. this.velocityWorldLength = this.velocityWorld.length();
  9985. this.epsilon = e;
  9986. this.collisionFound = false;
  9987. };
  9988. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9989. pa.subtractToRef(point, this._tempVector);
  9990. pb.subtractToRef(point, this._tempVector2);
  9991. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9992. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9993. if (d < 0)
  9994. return false;
  9995. pc.subtractToRef(point, this._tempVector3);
  9996. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9997. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9998. if (d < 0)
  9999. return false;
  10000. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10001. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10002. return d >= 0;
  10003. };
  10004. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10005. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10006. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10007. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10008. return false;
  10009. }
  10010. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10011. return false;
  10012. return true;
  10013. };
  10014. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10015. var t0;
  10016. var embeddedInPlane = false;
  10017. //defensive programming, actually not needed.
  10018. if (!trianglePlaneArray) {
  10019. trianglePlaneArray = [];
  10020. }
  10021. if (!trianglePlaneArray[faceIndex]) {
  10022. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10023. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10024. }
  10025. var trianglePlane = trianglePlaneArray[faceIndex];
  10026. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10027. return;
  10028. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10029. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10030. if (normalDotVelocity == 0) {
  10031. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10032. return;
  10033. embeddedInPlane = true;
  10034. t0 = 0;
  10035. }
  10036. else {
  10037. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10038. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10039. if (t0 > t1) {
  10040. var temp = t1;
  10041. t1 = t0;
  10042. t0 = temp;
  10043. }
  10044. if (t0 > 1.0 || t1 < 0.0)
  10045. return;
  10046. if (t0 < 0)
  10047. t0 = 0;
  10048. if (t0 > 1.0)
  10049. t0 = 1.0;
  10050. }
  10051. this._collisionPoint.copyFromFloats(0, 0, 0);
  10052. var found = false;
  10053. var t = 1.0;
  10054. if (!embeddedInPlane) {
  10055. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10056. this.velocity.scaleToRef(t0, this._tempVector);
  10057. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10058. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10059. found = true;
  10060. t = t0;
  10061. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10062. }
  10063. }
  10064. if (!found) {
  10065. var velocitySquaredLength = this.velocity.lengthSquared();
  10066. var a = velocitySquaredLength;
  10067. this.basePoint.subtractToRef(p1, this._tempVector);
  10068. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10069. var c = this._tempVector.lengthSquared() - 1.0;
  10070. var lowestRoot = getLowestRoot(a, b, c, t);
  10071. if (lowestRoot.found) {
  10072. t = lowestRoot.root;
  10073. found = true;
  10074. this._collisionPoint.copyFrom(p1);
  10075. }
  10076. this.basePoint.subtractToRef(p2, this._tempVector);
  10077. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10078. c = this._tempVector.lengthSquared() - 1.0;
  10079. lowestRoot = getLowestRoot(a, b, c, t);
  10080. if (lowestRoot.found) {
  10081. t = lowestRoot.root;
  10082. found = true;
  10083. this._collisionPoint.copyFrom(p2);
  10084. }
  10085. this.basePoint.subtractToRef(p3, this._tempVector);
  10086. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10087. c = this._tempVector.lengthSquared() - 1.0;
  10088. lowestRoot = getLowestRoot(a, b, c, t);
  10089. if (lowestRoot.found) {
  10090. t = lowestRoot.root;
  10091. found = true;
  10092. this._collisionPoint.copyFrom(p3);
  10093. }
  10094. p2.subtractToRef(p1, this._edge);
  10095. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10096. var edgeSquaredLength = this._edge.lengthSquared();
  10097. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10098. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10099. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10100. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10101. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10102. lowestRoot = getLowestRoot(a, b, c, t);
  10103. if (lowestRoot.found) {
  10104. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10105. if (f >= 0.0 && f <= 1.0) {
  10106. t = lowestRoot.root;
  10107. found = true;
  10108. this._edge.scaleInPlace(f);
  10109. p1.addToRef(this._edge, this._collisionPoint);
  10110. }
  10111. }
  10112. p3.subtractToRef(p2, this._edge);
  10113. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10114. edgeSquaredLength = this._edge.lengthSquared();
  10115. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10116. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10117. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10118. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10119. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10120. lowestRoot = getLowestRoot(a, b, c, t);
  10121. if (lowestRoot.found) {
  10122. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10123. if (f >= 0.0 && f <= 1.0) {
  10124. t = lowestRoot.root;
  10125. found = true;
  10126. this._edge.scaleInPlace(f);
  10127. p2.addToRef(this._edge, this._collisionPoint);
  10128. }
  10129. }
  10130. p1.subtractToRef(p3, this._edge);
  10131. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10132. edgeSquaredLength = this._edge.lengthSquared();
  10133. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10134. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10135. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10136. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10137. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10138. lowestRoot = getLowestRoot(a, b, c, t);
  10139. if (lowestRoot.found) {
  10140. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10141. if (f >= 0.0 && f <= 1.0) {
  10142. t = lowestRoot.root;
  10143. found = true;
  10144. this._edge.scaleInPlace(f);
  10145. p3.addToRef(this._edge, this._collisionPoint);
  10146. }
  10147. }
  10148. }
  10149. if (found) {
  10150. var distToCollision = t * this.velocity.length();
  10151. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10152. if (!this.intersectionPoint) {
  10153. this.intersectionPoint = this._collisionPoint.clone();
  10154. }
  10155. else {
  10156. this.intersectionPoint.copyFrom(this._collisionPoint);
  10157. }
  10158. this.nearestDistance = distToCollision;
  10159. this.collisionFound = true;
  10160. }
  10161. }
  10162. };
  10163. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10164. for (var i = indexStart; i < indexEnd; i += 3) {
  10165. var p1 = pts[indices[i] - decal];
  10166. var p2 = pts[indices[i + 1] - decal];
  10167. var p3 = pts[indices[i + 2] - decal];
  10168. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10169. }
  10170. };
  10171. Collider.prototype._getResponse = function (pos, vel) {
  10172. pos.addToRef(vel, this._destinationPoint);
  10173. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10174. this.basePoint.addToRef(vel, pos);
  10175. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10176. this._slidePlaneNormal.normalize();
  10177. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10178. pos.addInPlace(this._displacementVector);
  10179. this.intersectionPoint.addInPlace(this._displacementVector);
  10180. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10181. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10182. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10183. };
  10184. return Collider;
  10185. })();
  10186. BABYLON.Collider = Collider;
  10187. })(BABYLON || (BABYLON = {}));
  10188. var BABYLON;
  10189. (function (BABYLON) {
  10190. //WebWorker code will be inserted to this variable.
  10191. BABYLON.CollisionWorker = "";
  10192. (function (WorkerTaskType) {
  10193. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10194. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10195. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10196. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10197. var WorkerTaskType = BABYLON.WorkerTaskType;
  10198. (function (WorkerReplyType) {
  10199. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10200. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10201. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10202. var WorkerReplyType = BABYLON.WorkerReplyType;
  10203. var CollisionCoordinatorWorker = (function () {
  10204. function CollisionCoordinatorWorker() {
  10205. var _this = this;
  10206. this._scaledPosition = BABYLON.Vector3.Zero();
  10207. this._scaledVelocity = BABYLON.Vector3.Zero();
  10208. this.onMeshUpdated = function (mesh) {
  10209. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10210. };
  10211. this.onGeometryUpdated = function (geometry) {
  10212. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10213. };
  10214. this._afterRender = function () {
  10215. if (!_this._init)
  10216. return;
  10217. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10218. return;
  10219. }
  10220. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10221. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10222. if (_this._runningUpdated > 4) {
  10223. return;
  10224. }
  10225. ++_this._runningUpdated;
  10226. var payload = {
  10227. updatedMeshes: _this._addUpdateMeshesList,
  10228. updatedGeometries: _this._addUpdateGeometriesList,
  10229. removedGeometries: _this._toRemoveGeometryArray,
  10230. removedMeshes: _this._toRemoveMeshesArray
  10231. };
  10232. var message = {
  10233. payload: payload,
  10234. taskType: WorkerTaskType.UPDATE
  10235. };
  10236. var serializable = [];
  10237. for (var id in payload.updatedGeometries) {
  10238. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10239. //prepare transferables
  10240. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10241. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10242. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10243. }
  10244. }
  10245. _this._worker.postMessage(message, serializable);
  10246. _this._addUpdateMeshesList = {};
  10247. _this._addUpdateGeometriesList = {};
  10248. _this._toRemoveGeometryArray = [];
  10249. _this._toRemoveMeshesArray = [];
  10250. };
  10251. this._onMessageFromWorker = function (e) {
  10252. var returnData = e.data;
  10253. if (returnData.error != WorkerReplyType.SUCCESS) {
  10254. //TODO what errors can be returned from the worker?
  10255. BABYLON.Tools.Warn("error returned from worker!");
  10256. return;
  10257. }
  10258. switch (returnData.taskType) {
  10259. case WorkerTaskType.INIT:
  10260. _this._init = true;
  10261. //Update the worked with ALL of the scene's current state
  10262. _this._scene.meshes.forEach(function (mesh) {
  10263. _this.onMeshAdded(mesh);
  10264. });
  10265. _this._scene.getGeometries().forEach(function (geometry) {
  10266. _this.onGeometryAdded(geometry);
  10267. });
  10268. break;
  10269. case WorkerTaskType.UPDATE:
  10270. _this._runningUpdated--;
  10271. break;
  10272. case WorkerTaskType.COLLIDE:
  10273. _this._runningCollisionTask = false;
  10274. var returnPayload = returnData.payload;
  10275. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10276. return;
  10277. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10278. //cleanup
  10279. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10280. break;
  10281. }
  10282. };
  10283. this._collisionsCallbackArray = [];
  10284. this._init = false;
  10285. this._runningUpdated = 0;
  10286. this._runningCollisionTask = false;
  10287. this._addUpdateMeshesList = {};
  10288. this._addUpdateGeometriesList = {};
  10289. this._toRemoveGeometryArray = [];
  10290. this._toRemoveMeshesArray = [];
  10291. }
  10292. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10293. if (!this._init)
  10294. return;
  10295. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10296. return;
  10297. position.divideToRef(collider.radius, this._scaledPosition);
  10298. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10299. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10300. var payload = {
  10301. collider: {
  10302. position: this._scaledPosition.asArray(),
  10303. velocity: this._scaledVelocity.asArray(),
  10304. radius: collider.radius.asArray()
  10305. },
  10306. collisionId: collisionIndex,
  10307. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10308. maximumRetry: maximumRetry
  10309. };
  10310. var message = {
  10311. payload: payload,
  10312. taskType: WorkerTaskType.COLLIDE
  10313. };
  10314. this._worker.postMessage(message);
  10315. };
  10316. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10317. this._scene = scene;
  10318. this._scene.registerAfterRender(this._afterRender);
  10319. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10320. this._worker = new Worker(workerUrl);
  10321. this._worker.onmessage = this._onMessageFromWorker;
  10322. var message = {
  10323. payload: {},
  10324. taskType: WorkerTaskType.INIT
  10325. };
  10326. this._worker.postMessage(message);
  10327. };
  10328. CollisionCoordinatorWorker.prototype.destroy = function () {
  10329. this._scene.unregisterAfterRender(this._afterRender);
  10330. this._worker.terminate();
  10331. };
  10332. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10333. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10334. this.onMeshUpdated(mesh);
  10335. };
  10336. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10337. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10338. };
  10339. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10340. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10341. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10342. this.onGeometryUpdated(geometry);
  10343. };
  10344. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10345. this._toRemoveGeometryArray.push(geometry.id);
  10346. };
  10347. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10348. var submeshes = [];
  10349. if (mesh.subMeshes) {
  10350. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10351. return {
  10352. position: idx,
  10353. verticesStart: sm.verticesStart,
  10354. verticesCount: sm.verticesCount,
  10355. indexStart: sm.indexStart,
  10356. indexCount: sm.indexCount,
  10357. hasMaterial: !!sm.getMaterial(),
  10358. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10359. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10360. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10361. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10362. };
  10363. });
  10364. }
  10365. var geometryId = null;
  10366. if (mesh instanceof BABYLON.Mesh) {
  10367. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10368. }
  10369. else if (mesh instanceof BABYLON.InstancedMesh) {
  10370. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10371. }
  10372. return {
  10373. uniqueId: mesh.uniqueId,
  10374. id: mesh.id,
  10375. name: mesh.name,
  10376. geometryId: geometryId,
  10377. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10378. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10379. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10380. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10381. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10382. subMeshes: submeshes,
  10383. checkCollisions: mesh.checkCollisions
  10384. };
  10385. };
  10386. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10387. return {
  10388. id: geometry.id,
  10389. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10390. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10391. indices: new Int32Array(geometry.getIndices() || []),
  10392. };
  10393. };
  10394. return CollisionCoordinatorWorker;
  10395. })();
  10396. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10397. var CollisionCoordinatorLegacy = (function () {
  10398. function CollisionCoordinatorLegacy() {
  10399. this._scaledPosition = BABYLON.Vector3.Zero();
  10400. this._scaledVelocity = BABYLON.Vector3.Zero();
  10401. this._finalPosition = BABYLON.Vector3.Zero();
  10402. }
  10403. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10404. position.divideToRef(collider.radius, this._scaledPosition);
  10405. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10406. collider.collidedMesh = null;
  10407. collider.retry = 0;
  10408. collider.initialVelocity = this._scaledVelocity;
  10409. collider.initialPosition = this._scaledPosition;
  10410. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10411. this._finalPosition.multiplyInPlace(collider.radius);
  10412. //run the callback
  10413. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10414. };
  10415. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10416. this._scene = scene;
  10417. };
  10418. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10419. //Legacy need no destruction method.
  10420. };
  10421. //No update in legacy mode
  10422. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10423. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10424. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10425. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10426. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10427. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10428. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10429. if (excludedMesh === void 0) { excludedMesh = null; }
  10430. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10431. if (collider.retry >= maximumRetry) {
  10432. finalPosition.copyFrom(position);
  10433. return;
  10434. }
  10435. collider._initialize(position, velocity, closeDistance);
  10436. // Check all meshes
  10437. for (var index = 0; index < this._scene.meshes.length; index++) {
  10438. var mesh = this._scene.meshes[index];
  10439. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10440. mesh._checkCollision(collider);
  10441. }
  10442. }
  10443. if (!collider.collisionFound) {
  10444. position.addToRef(velocity, finalPosition);
  10445. return;
  10446. }
  10447. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10448. collider._getResponse(position, velocity);
  10449. }
  10450. if (velocity.length() <= closeDistance) {
  10451. finalPosition.copyFrom(position);
  10452. return;
  10453. }
  10454. collider.retry++;
  10455. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10456. };
  10457. return CollisionCoordinatorLegacy;
  10458. })();
  10459. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10460. })(BABYLON || (BABYLON = {}));
  10461. var BABYLON;
  10462. (function (BABYLON) {
  10463. var Camera = (function (_super) {
  10464. __extends(Camera, _super);
  10465. function Camera(name, position, scene) {
  10466. _super.call(this, name, scene);
  10467. this.upVector = BABYLON.Vector3.Up();
  10468. this.orthoLeft = null;
  10469. this.orthoRight = null;
  10470. this.orthoBottom = null;
  10471. this.orthoTop = null;
  10472. this.fov = 0.8;
  10473. this.minZ = 1.0;
  10474. this.maxZ = 10000.0;
  10475. this.inertia = 0.9;
  10476. this.mode = Camera.PERSPECTIVE_CAMERA;
  10477. this.isIntermediate = false;
  10478. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10479. this.layerMask = 0x0FFFFFFF;
  10480. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10481. // Camera rig members
  10482. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10483. this._rigCameras = new Array();
  10484. // Cache
  10485. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10486. this._projectionMatrix = new BABYLON.Matrix();
  10487. this._postProcesses = new Array();
  10488. this._postProcessesTakenIndices = [];
  10489. this._activeMeshes = new BABYLON.SmartArray(256);
  10490. this._globalPosition = BABYLON.Vector3.Zero();
  10491. scene.addCamera(this);
  10492. if (!scene.activeCamera) {
  10493. scene.activeCamera = this;
  10494. }
  10495. this.position = position;
  10496. }
  10497. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10498. get: function () {
  10499. return Camera._PERSPECTIVE_CAMERA;
  10500. },
  10501. enumerable: true,
  10502. configurable: true
  10503. });
  10504. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10505. get: function () {
  10506. return Camera._ORTHOGRAPHIC_CAMERA;
  10507. },
  10508. enumerable: true,
  10509. configurable: true
  10510. });
  10511. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10512. get: function () {
  10513. return Camera._FOVMODE_VERTICAL_FIXED;
  10514. },
  10515. enumerable: true,
  10516. configurable: true
  10517. });
  10518. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10519. get: function () {
  10520. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10521. },
  10522. enumerable: true,
  10523. configurable: true
  10524. });
  10525. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10526. get: function () {
  10527. return Camera._RIG_MODE_NONE;
  10528. },
  10529. enumerable: true,
  10530. configurable: true
  10531. });
  10532. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10533. get: function () {
  10534. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10535. },
  10536. enumerable: true,
  10537. configurable: true
  10538. });
  10539. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10540. get: function () {
  10541. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10542. },
  10543. enumerable: true,
  10544. configurable: true
  10545. });
  10546. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10547. get: function () {
  10548. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10549. },
  10550. enumerable: true,
  10551. configurable: true
  10552. });
  10553. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10554. get: function () {
  10555. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10556. },
  10557. enumerable: true,
  10558. configurable: true
  10559. });
  10560. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10561. get: function () {
  10562. return Camera._RIG_MODE_VR;
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. /**
  10568. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10569. */
  10570. Camera.prototype.toString = function (fullDetails) {
  10571. var ret = "Name: " + this.name;
  10572. ret += ", type: " + this.getTypeName();
  10573. if (this.animations) {
  10574. for (var i = 0; i < this.animations.length; i++) {
  10575. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10576. }
  10577. }
  10578. if (fullDetails) {
  10579. }
  10580. return ret;
  10581. };
  10582. Object.defineProperty(Camera.prototype, "globalPosition", {
  10583. get: function () {
  10584. return this._globalPosition;
  10585. },
  10586. enumerable: true,
  10587. configurable: true
  10588. });
  10589. Camera.prototype.getActiveMeshes = function () {
  10590. return this._activeMeshes;
  10591. };
  10592. Camera.prototype.isActiveMesh = function (mesh) {
  10593. return (this._activeMeshes.indexOf(mesh) !== -1);
  10594. };
  10595. //Cache
  10596. Camera.prototype._initCache = function () {
  10597. _super.prototype._initCache.call(this);
  10598. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10599. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10600. this._cache.mode = undefined;
  10601. this._cache.minZ = undefined;
  10602. this._cache.maxZ = undefined;
  10603. this._cache.fov = undefined;
  10604. this._cache.aspectRatio = undefined;
  10605. this._cache.orthoLeft = undefined;
  10606. this._cache.orthoRight = undefined;
  10607. this._cache.orthoBottom = undefined;
  10608. this._cache.orthoTop = undefined;
  10609. this._cache.renderWidth = undefined;
  10610. this._cache.renderHeight = undefined;
  10611. };
  10612. Camera.prototype._updateCache = function (ignoreParentClass) {
  10613. if (!ignoreParentClass) {
  10614. _super.prototype._updateCache.call(this);
  10615. }
  10616. var engine = this.getEngine();
  10617. this._cache.position.copyFrom(this.position);
  10618. this._cache.upVector.copyFrom(this.upVector);
  10619. this._cache.mode = this.mode;
  10620. this._cache.minZ = this.minZ;
  10621. this._cache.maxZ = this.maxZ;
  10622. this._cache.fov = this.fov;
  10623. this._cache.aspectRatio = engine.getAspectRatio(this);
  10624. this._cache.orthoLeft = this.orthoLeft;
  10625. this._cache.orthoRight = this.orthoRight;
  10626. this._cache.orthoBottom = this.orthoBottom;
  10627. this._cache.orthoTop = this.orthoTop;
  10628. this._cache.renderWidth = engine.getRenderWidth();
  10629. this._cache.renderHeight = engine.getRenderHeight();
  10630. };
  10631. Camera.prototype._updateFromScene = function () {
  10632. this.updateCache();
  10633. this._update();
  10634. };
  10635. // Synchronized
  10636. Camera.prototype._isSynchronized = function () {
  10637. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10638. };
  10639. Camera.prototype._isSynchronizedViewMatrix = function () {
  10640. if (!_super.prototype._isSynchronized.call(this))
  10641. return false;
  10642. return this._cache.position.equals(this.position)
  10643. && this._cache.upVector.equals(this.upVector)
  10644. && this.isSynchronizedWithParent();
  10645. };
  10646. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10647. var check = this._cache.mode === this.mode
  10648. && this._cache.minZ === this.minZ
  10649. && this._cache.maxZ === this.maxZ;
  10650. if (!check) {
  10651. return false;
  10652. }
  10653. var engine = this.getEngine();
  10654. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10655. check = this._cache.fov === this.fov
  10656. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10657. }
  10658. else {
  10659. check = this._cache.orthoLeft === this.orthoLeft
  10660. && this._cache.orthoRight === this.orthoRight
  10661. && this._cache.orthoBottom === this.orthoBottom
  10662. && this._cache.orthoTop === this.orthoTop
  10663. && this._cache.renderWidth === engine.getRenderWidth()
  10664. && this._cache.renderHeight === engine.getRenderHeight();
  10665. }
  10666. return check;
  10667. };
  10668. // Controls
  10669. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10670. };
  10671. Camera.prototype.detachControl = function (element) {
  10672. };
  10673. Camera.prototype._update = function () {
  10674. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10675. this._updateRigCameras();
  10676. }
  10677. this._checkInputs();
  10678. };
  10679. Camera.prototype._checkInputs = function () {
  10680. };
  10681. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10682. if (insertAt === void 0) { insertAt = null; }
  10683. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10684. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10685. return 0;
  10686. }
  10687. if (insertAt == null || insertAt < 0) {
  10688. this._postProcesses.push(postProcess);
  10689. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10690. return this._postProcesses.length - 1;
  10691. }
  10692. var add = 0;
  10693. var i;
  10694. var start;
  10695. if (this._postProcesses[insertAt]) {
  10696. start = this._postProcesses.length - 1;
  10697. for (i = start; i >= insertAt + 1; --i) {
  10698. this._postProcesses[i + 1] = this._postProcesses[i];
  10699. }
  10700. add = 1;
  10701. }
  10702. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10703. if (this._postProcessesTakenIndices[i] < insertAt) {
  10704. continue;
  10705. }
  10706. start = this._postProcessesTakenIndices.length - 1;
  10707. for (var j = start; j >= i; --j) {
  10708. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10709. }
  10710. this._postProcessesTakenIndices[i] = insertAt;
  10711. break;
  10712. }
  10713. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10714. this._postProcessesTakenIndices.push(insertAt);
  10715. }
  10716. var result = insertAt + add;
  10717. this._postProcesses[result] = postProcess;
  10718. return result;
  10719. };
  10720. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10721. if (atIndices === void 0) { atIndices = null; }
  10722. var result = [];
  10723. var i;
  10724. var index;
  10725. if (!atIndices) {
  10726. var length = this._postProcesses.length;
  10727. for (i = 0; i < length; i++) {
  10728. if (this._postProcesses[i] !== postProcess) {
  10729. continue;
  10730. }
  10731. delete this._postProcesses[i];
  10732. index = this._postProcessesTakenIndices.indexOf(i);
  10733. this._postProcessesTakenIndices.splice(index, 1);
  10734. }
  10735. }
  10736. else {
  10737. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10738. for (i = 0; i < atIndices.length; i++) {
  10739. var foundPostProcess = this._postProcesses[atIndices[i]];
  10740. if (foundPostProcess !== postProcess) {
  10741. result.push(i);
  10742. continue;
  10743. }
  10744. delete this._postProcesses[atIndices[i]];
  10745. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10746. this._postProcessesTakenIndices.splice(index, 1);
  10747. }
  10748. }
  10749. return result;
  10750. };
  10751. Camera.prototype.getWorldMatrix = function () {
  10752. if (!this._worldMatrix) {
  10753. this._worldMatrix = BABYLON.Matrix.Identity();
  10754. }
  10755. var viewMatrix = this.getViewMatrix();
  10756. viewMatrix.invertToRef(this._worldMatrix);
  10757. return this._worldMatrix;
  10758. };
  10759. Camera.prototype._getViewMatrix = function () {
  10760. return BABYLON.Matrix.Identity();
  10761. };
  10762. Camera.prototype.getViewMatrix = function (force) {
  10763. this._computedViewMatrix = this._computeViewMatrix(force);
  10764. if (!force && this._isSynchronizedViewMatrix()) {
  10765. return this._computedViewMatrix;
  10766. }
  10767. if (!this.parent || !this.parent.getWorldMatrix) {
  10768. this._globalPosition.copyFrom(this.position);
  10769. }
  10770. else {
  10771. if (!this._worldMatrix) {
  10772. this._worldMatrix = BABYLON.Matrix.Identity();
  10773. }
  10774. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10775. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10776. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10777. this._computedViewMatrix.invert();
  10778. this._markSyncedWithParent();
  10779. }
  10780. this._currentRenderId = this.getScene().getRenderId();
  10781. return this._computedViewMatrix;
  10782. };
  10783. Camera.prototype._computeViewMatrix = function (force) {
  10784. if (!force && this._isSynchronizedViewMatrix()) {
  10785. return this._computedViewMatrix;
  10786. }
  10787. this._computedViewMatrix = this._getViewMatrix();
  10788. this._currentRenderId = this.getScene().getRenderId();
  10789. return this._computedViewMatrix;
  10790. };
  10791. Camera.prototype.getProjectionMatrix = function (force) {
  10792. if (!force && this._isSynchronizedProjectionMatrix()) {
  10793. return this._projectionMatrix;
  10794. }
  10795. var engine = this.getEngine();
  10796. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10797. if (this.minZ <= 0) {
  10798. this.minZ = 0.1;
  10799. }
  10800. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  10801. return this._projectionMatrix;
  10802. }
  10803. var halfWidth = engine.getRenderWidth() / 2.0;
  10804. var halfHeight = engine.getRenderHeight() / 2.0;
  10805. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10806. return this._projectionMatrix;
  10807. };
  10808. Camera.prototype.dispose = function () {
  10809. // Animations
  10810. this.getScene().stopAnimation(this);
  10811. // Remove from scene
  10812. this.getScene().removeCamera(this);
  10813. while (this._rigCameras.length > 0) {
  10814. this._rigCameras.pop().dispose();
  10815. }
  10816. // Postprocesses
  10817. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10818. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10819. }
  10820. };
  10821. // ---- Camera rigs section ----
  10822. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10823. while (this._rigCameras.length > 0) {
  10824. this._rigCameras.pop().dispose();
  10825. }
  10826. this.cameraRigMode = mode;
  10827. this._cameraRigParams = {};
  10828. switch (this.cameraRigMode) {
  10829. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10830. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10831. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10832. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10833. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10834. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10835. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10836. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10837. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10838. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10839. break;
  10840. }
  10841. var postProcesses = new Array();
  10842. switch (this.cameraRigMode) {
  10843. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10844. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10845. this._rigCameras[0].isIntermediate = true;
  10846. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10847. postProcesses[1].onApply = function (effect) {
  10848. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10849. };
  10850. break;
  10851. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10852. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10853. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10854. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10855. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10856. var secondCamIndex = 1 - firstCamIndex;
  10857. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10858. this._rigCameras[firstCamIndex].isIntermediate = true;
  10859. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10860. break;
  10861. case Camera.RIG_MODE_VR:
  10862. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10863. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10864. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10865. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10866. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10867. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10868. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10869. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10870. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10871. if (metrics.compensateDistortion) {
  10872. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10873. }
  10874. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10875. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10876. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10877. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10878. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10879. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10880. if (metrics.compensateDistortion) {
  10881. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10882. }
  10883. break;
  10884. }
  10885. this._update();
  10886. };
  10887. Camera.prototype._getVRProjectionMatrix = function () {
  10888. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10889. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10890. return this._projectionMatrix;
  10891. };
  10892. Camera.prototype.setCameraRigParameter = function (name, value) {
  10893. this._cameraRigParams[name] = value;
  10894. //provisionnally:
  10895. if (name === "interaxialDistance") {
  10896. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10897. }
  10898. };
  10899. /**
  10900. * May needs to be overridden by children so sub has required properties to be copied
  10901. */
  10902. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10903. return null;
  10904. };
  10905. /**
  10906. * May needs to be overridden by children
  10907. */
  10908. Camera.prototype._updateRigCameras = function () {
  10909. for (var i = 0; i < this._rigCameras.length; i++) {
  10910. this._rigCameras[i].minZ = this.minZ;
  10911. this._rigCameras[i].maxZ = this.maxZ;
  10912. this._rigCameras[i].fov = this.fov;
  10913. }
  10914. // only update viewport when ANAGLYPH
  10915. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10916. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10917. }
  10918. };
  10919. Camera.prototype.serialize = function () {
  10920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10921. // Type
  10922. serializationObject.type = this.getTypeName();
  10923. // Parent
  10924. if (this.parent) {
  10925. serializationObject.parentId = this.parent.id;
  10926. }
  10927. if (this.inputs) {
  10928. this.inputs.serialize(serializationObject);
  10929. }
  10930. // Animations
  10931. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10932. serializationObject.ranges = this.serializeAnimationRanges();
  10933. return serializationObject;
  10934. };
  10935. Camera.prototype.getTypeName = function () {
  10936. return "Camera";
  10937. };
  10938. Camera.prototype.clone = function (name) {
  10939. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10940. };
  10941. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10942. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10943. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10944. switch (type) {
  10945. case "ArcRotateCamera":
  10946. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10947. case "DeviceOrientationCamera":
  10948. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10949. case "FollowCamera":
  10950. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10951. case "ArcFollowCamera":
  10952. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10953. case "GamepadCamera":
  10954. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10955. case "TouchCamera":
  10956. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10957. case "VirtualJoysticksCamera":
  10958. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10959. case "WebVRFreeCamera":
  10960. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10961. case "VRDeviceOrientationFreeCamera":
  10962. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10963. case "AnaglyphArcRotateCamera":
  10964. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10965. case "AnaglyphFreeCamera":
  10966. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10967. case "AnaglyphGamepadCamera":
  10968. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10969. case "AnaglyphUniversalCamera":
  10970. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10971. case "StereoscopicArcRotateCamera":
  10972. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10973. case "StereoscopicFreeCamera":
  10974. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10975. case "StereoscopicGamepadCamera":
  10976. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10977. case "StereoscopicUniversalCamera":
  10978. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10979. case "FreeCamera":
  10980. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10981. default:
  10982. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10983. }
  10984. };
  10985. Camera.Parse = function (parsedCamera, scene) {
  10986. var type = parsedCamera.type;
  10987. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10988. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10989. // Parent
  10990. if (parsedCamera.parentId) {
  10991. camera._waitingParentId = parsedCamera.parentId;
  10992. }
  10993. //If camera has an input manager, let it parse inputs settings
  10994. if (camera.inputs) {
  10995. camera.inputs.parse(parsedCamera);
  10996. }
  10997. // Target
  10998. if (parsedCamera.target) {
  10999. if (camera.setTarget) {
  11000. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11001. }
  11002. }
  11003. // Apply 3d rig, when found
  11004. if (parsedCamera.cameraRigMode) {
  11005. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11006. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11007. }
  11008. // Animations
  11009. if (parsedCamera.animations) {
  11010. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11011. var parsedAnimation = parsedCamera.animations[animationIndex];
  11012. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11013. }
  11014. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11015. }
  11016. if (parsedCamera.autoAnimate) {
  11017. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11018. }
  11019. return camera;
  11020. };
  11021. // Statics
  11022. Camera._PERSPECTIVE_CAMERA = 0;
  11023. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11024. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11025. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11026. Camera._RIG_MODE_NONE = 0;
  11027. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11028. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11029. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11030. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11031. Camera._RIG_MODE_VR = 20;
  11032. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11033. __decorate([
  11034. BABYLON.serializeAsVector3()
  11035. ], Camera.prototype, "position", void 0);
  11036. __decorate([
  11037. BABYLON.serialize()
  11038. ], Camera.prototype, "upVector", void 0);
  11039. __decorate([
  11040. BABYLON.serialize()
  11041. ], Camera.prototype, "orthoLeft", void 0);
  11042. __decorate([
  11043. BABYLON.serialize()
  11044. ], Camera.prototype, "orthoRight", void 0);
  11045. __decorate([
  11046. BABYLON.serialize()
  11047. ], Camera.prototype, "orthoBottom", void 0);
  11048. __decorate([
  11049. BABYLON.serialize()
  11050. ], Camera.prototype, "orthoTop", void 0);
  11051. __decorate([
  11052. BABYLON.serialize()
  11053. ], Camera.prototype, "fov", void 0);
  11054. __decorate([
  11055. BABYLON.serialize()
  11056. ], Camera.prototype, "minZ", void 0);
  11057. __decorate([
  11058. BABYLON.serialize()
  11059. ], Camera.prototype, "maxZ", void 0);
  11060. __decorate([
  11061. BABYLON.serialize()
  11062. ], Camera.prototype, "inertia", void 0);
  11063. __decorate([
  11064. BABYLON.serialize()
  11065. ], Camera.prototype, "mode", void 0);
  11066. __decorate([
  11067. BABYLON.serialize()
  11068. ], Camera.prototype, "layerMask", void 0);
  11069. __decorate([
  11070. BABYLON.serialize()
  11071. ], Camera.prototype, "fovMode", void 0);
  11072. __decorate([
  11073. BABYLON.serialize()
  11074. ], Camera.prototype, "cameraRigMode", void 0);
  11075. __decorate([
  11076. BABYLON.serialize()
  11077. ], Camera.prototype, "interaxialDistance", void 0);
  11078. __decorate([
  11079. BABYLON.serialize()
  11080. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11081. return Camera;
  11082. })(BABYLON.Node);
  11083. BABYLON.Camera = Camera;
  11084. })(BABYLON || (BABYLON = {}));
  11085. var BABYLON;
  11086. (function (BABYLON) {
  11087. BABYLON.CameraInputTypes = {};
  11088. var CameraInputsManager = (function () {
  11089. function CameraInputsManager(camera) {
  11090. this.attached = {};
  11091. this.camera = camera;
  11092. this.checkInputs = function () { };
  11093. }
  11094. CameraInputsManager.prototype.add = function (input) {
  11095. var type = input.getSimpleName();
  11096. if (this.attached[type]) {
  11097. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11098. return;
  11099. }
  11100. this.attached[type] = input;
  11101. input.attachCamera(this.camera);
  11102. //for checkInputs, we are dynamically creating a function
  11103. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11104. if (input.checkInputs) {
  11105. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11106. }
  11107. };
  11108. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11109. for (var cam in this.attached) {
  11110. var input = this.attached[cam];
  11111. if (input == inputToRemove) {
  11112. input.detach();
  11113. delete this.attached[cam];
  11114. }
  11115. }
  11116. };
  11117. CameraInputsManager.prototype.removeByType = function (inputType) {
  11118. for (var cam in this.attached) {
  11119. var input = this.attached[cam];
  11120. if (input.getTypeName() == inputType) {
  11121. input.detach();
  11122. delete this.attached[cam];
  11123. }
  11124. }
  11125. };
  11126. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11127. var current = this.checkInputs;
  11128. return function () {
  11129. current();
  11130. fn();
  11131. };
  11132. };
  11133. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11134. for (var cam in this.attached) {
  11135. var input = this.attached[cam];
  11136. if (input.attachElement)
  11137. this.attached[cam].attachElement(element, noPreventDefault);
  11138. }
  11139. };
  11140. CameraInputsManager.prototype.detachElement = function (element) {
  11141. for (var cam in this.attached) {
  11142. var input = this.attached[cam];
  11143. if (input.detachElement)
  11144. this.attached[cam].detachElement(element);
  11145. }
  11146. };
  11147. CameraInputsManager.prototype.rebuildInputCheck = function (element) {
  11148. this.checkInputs = function () { };
  11149. for (var cam in this.attached) {
  11150. var input = this.attached[cam];
  11151. if (input.checkInputs) {
  11152. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11153. }
  11154. }
  11155. };
  11156. CameraInputsManager.prototype.clear = function () {
  11157. for (var cam in this.attached) {
  11158. this.attached[cam].detach();
  11159. }
  11160. this.attached = {};
  11161. this.checkInputs = function () { };
  11162. };
  11163. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11164. var inputs = {};
  11165. for (var cam in this.attached) {
  11166. var input = this.attached[cam];
  11167. var res = BABYLON.SerializationHelper.Serialize(input, serializedCamera);
  11168. inputs[input.getTypeName()] = res;
  11169. }
  11170. serializedCamera.inputsmgr = inputs;
  11171. };
  11172. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11173. var parsedInputs = parsedCamera.inputsmgr;
  11174. if (parsedInputs) {
  11175. this.clear();
  11176. for (var n in parsedInputs) {
  11177. var construct = BABYLON.CameraInputTypes[n];
  11178. if (construct) {
  11179. var parsedinput = parsedInputs[n];
  11180. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11181. this.add(input);
  11182. }
  11183. }
  11184. }
  11185. else {
  11186. //2016-03-08 this part is for managing backward compatibility
  11187. for (var n in this.attached) {
  11188. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11189. if (construct) {
  11190. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11191. this.add(input);
  11192. }
  11193. }
  11194. }
  11195. };
  11196. return CameraInputsManager;
  11197. })();
  11198. BABYLON.CameraInputsManager = CameraInputsManager;
  11199. })(BABYLON || (BABYLON = {}));
  11200. var BABYLON;
  11201. (function (BABYLON) {
  11202. var FreeCameraMouseInput = (function () {
  11203. function FreeCameraMouseInput() {
  11204. this.angularSensibility = 2000.0;
  11205. }
  11206. FreeCameraMouseInput.prototype.attachCamera = function (camera) {
  11207. this.camera = camera;
  11208. };
  11209. FreeCameraMouseInput.prototype.attachElement = function (element, noPreventDefault) {
  11210. var _this = this;
  11211. var previousPosition;
  11212. this.attachedElement = element;
  11213. if (this._onMouseDown === undefined) {
  11214. var camera = this.camera;
  11215. var engine = this.camera.getEngine();
  11216. this._onMouseDown = function (evt) {
  11217. previousPosition = {
  11218. x: evt.clientX,
  11219. y: evt.clientY
  11220. };
  11221. if (!noPreventDefault) {
  11222. evt.preventDefault();
  11223. }
  11224. };
  11225. this._onMouseUp = function (evt) {
  11226. previousPosition = null;
  11227. if (!noPreventDefault) {
  11228. evt.preventDefault();
  11229. }
  11230. };
  11231. this._onMouseOut = function (evt) {
  11232. previousPosition = null;
  11233. if (!noPreventDefault) {
  11234. evt.preventDefault();
  11235. }
  11236. };
  11237. this._onMouseMove = function (evt) {
  11238. if (!previousPosition && !engine.isPointerLock) {
  11239. return;
  11240. }
  11241. var offsetX;
  11242. var offsetY;
  11243. if (!engine.isPointerLock) {
  11244. offsetX = evt.clientX - previousPosition.x;
  11245. offsetY = evt.clientY - previousPosition.y;
  11246. }
  11247. else {
  11248. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11249. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11250. }
  11251. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11252. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11253. previousPosition = {
  11254. x: evt.clientX,
  11255. y: evt.clientY
  11256. };
  11257. if (!noPreventDefault) {
  11258. evt.preventDefault();
  11259. }
  11260. };
  11261. }
  11262. element.addEventListener("mousedown", this._onMouseDown, false);
  11263. element.addEventListener("mouseup", this._onMouseUp, false);
  11264. element.addEventListener("mouseout", this._onMouseOut, false);
  11265. element.addEventListener("mousemove", this._onMouseMove, false);
  11266. };
  11267. FreeCameraMouseInput.prototype.detachElement = function (element) {
  11268. if (this.attachedElement !== element) {
  11269. return;
  11270. }
  11271. element.removeEventListener("mousedown", this._onMouseDown);
  11272. element.removeEventListener("mouseup", this._onMouseUp);
  11273. element.removeEventListener("mouseout", this._onMouseOut);
  11274. element.removeEventListener("mousemove", this._onMouseMove);
  11275. this.attachedElement = null;
  11276. };
  11277. FreeCameraMouseInput.prototype.detach = function () {
  11278. if (this.attachedElement) {
  11279. this.detachElement(this.attachedElement);
  11280. }
  11281. };
  11282. FreeCameraMouseInput.prototype.getTypeName = function () {
  11283. return "FreeCameraMouseInput";
  11284. };
  11285. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11286. return "mouse";
  11287. };
  11288. __decorate([
  11289. BABYLON.serialize()
  11290. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11291. return FreeCameraMouseInput;
  11292. })();
  11293. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11294. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11295. })(BABYLON || (BABYLON = {}));
  11296. var BABYLON;
  11297. (function (BABYLON) {
  11298. var FreeCameraKeyboardMoveInput = (function () {
  11299. function FreeCameraKeyboardMoveInput() {
  11300. this._keys = [];
  11301. this.keysUp = [38];
  11302. this.keysDown = [40];
  11303. this.keysLeft = [37];
  11304. this.keysRight = [39];
  11305. }
  11306. FreeCameraKeyboardMoveInput.prototype.attachCamera = function (camera) {
  11307. var _this = this;
  11308. this.camera = camera;
  11309. if (this._onKeyDown === undefined) {
  11310. this._onKeyDown = function (evt) {
  11311. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11312. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11313. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11314. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11315. var index = _this._keys.indexOf(evt.keyCode);
  11316. if (index === -1) {
  11317. _this._keys.push(evt.keyCode);
  11318. }
  11319. if (!camera._noPreventDefault) {
  11320. evt.preventDefault();
  11321. }
  11322. }
  11323. };
  11324. this._onKeyUp = function (evt) {
  11325. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11326. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11327. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11328. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11329. var index = _this._keys.indexOf(evt.keyCode);
  11330. if (index >= 0) {
  11331. _this._keys.splice(index, 1);
  11332. }
  11333. if (!camera._noPreventDefault) {
  11334. evt.preventDefault();
  11335. }
  11336. }
  11337. };
  11338. BABYLON.Tools.RegisterTopRootEvents([
  11339. { name: "keydown", handler: this._onKeyDown },
  11340. { name: "keyup", handler: this._onKeyUp },
  11341. { name: "blur", handler: this._onLostFocus }
  11342. ]);
  11343. }
  11344. };
  11345. FreeCameraKeyboardMoveInput.prototype.detach = function () {
  11346. BABYLON.Tools.UnregisterTopRootEvents([
  11347. { name: "keydown", handler: this._onKeyDown },
  11348. { name: "keyup", handler: this._onKeyUp },
  11349. { name: "blur", handler: this._onLostFocus }
  11350. ]);
  11351. };
  11352. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11353. var camera = this.camera;
  11354. // Keyboard
  11355. for (var index = 0; index < this._keys.length; index++) {
  11356. var keyCode = this._keys[index];
  11357. var speed = camera._computeLocalCameraSpeed();
  11358. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11359. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11360. }
  11361. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11362. camera._localDirection.copyFromFloats(0, 0, speed);
  11363. }
  11364. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11365. camera._localDirection.copyFromFloats(speed, 0, 0);
  11366. }
  11367. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11368. camera._localDirection.copyFromFloats(0, 0, -speed);
  11369. }
  11370. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11371. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11372. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11373. }
  11374. };
  11375. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11376. return "FreeCameraKeyboardMoveInput";
  11377. };
  11378. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11379. this._keys = [];
  11380. };
  11381. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11382. return "keyboard";
  11383. };
  11384. __decorate([
  11385. BABYLON.serialize()
  11386. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11387. __decorate([
  11388. BABYLON.serialize()
  11389. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11390. __decorate([
  11391. BABYLON.serialize()
  11392. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11393. __decorate([
  11394. BABYLON.serialize()
  11395. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11396. return FreeCameraKeyboardMoveInput;
  11397. })();
  11398. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11399. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11400. })(BABYLON || (BABYLON = {}));
  11401. var BABYLON;
  11402. (function (BABYLON) {
  11403. var FreeCameraTouchInput = (function () {
  11404. function FreeCameraTouchInput() {
  11405. this._offsetX = null;
  11406. this._offsetY = null;
  11407. this._pointerCount = 0;
  11408. this._pointerPressed = [];
  11409. this.touchAngularSensibility = 200000.0;
  11410. this.touchMoveSensibility = 250.0;
  11411. }
  11412. FreeCameraTouchInput.prototype.attachCamera = function (camera) {
  11413. this.camera = camera;
  11414. };
  11415. FreeCameraTouchInput.prototype.attachElement = function (element, noPreventDefault) {
  11416. var _this = this;
  11417. var previousPosition;
  11418. if (this._attachedElement) {
  11419. return;
  11420. }
  11421. this._attachedElement = element;
  11422. if (this._onPointerDown === undefined) {
  11423. this._onLostFocus = function (evt) {
  11424. _this._offsetX = null;
  11425. _this._offsetY = null;
  11426. };
  11427. this._onPointerDown = function (evt) {
  11428. if (evt.pointerType === "mouse") {
  11429. return;
  11430. }
  11431. if (!noPreventDefault) {
  11432. evt.preventDefault();
  11433. }
  11434. _this._pointerPressed.push(evt.pointerId);
  11435. if (_this._pointerPressed.length !== 1) {
  11436. return;
  11437. }
  11438. previousPosition = {
  11439. x: evt.clientX,
  11440. y: evt.clientY
  11441. };
  11442. };
  11443. this._onPointerUp = function (evt) {
  11444. if (evt.pointerType === "mouse") {
  11445. return;
  11446. }
  11447. if (!noPreventDefault) {
  11448. evt.preventDefault();
  11449. }
  11450. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11451. if (index === -1) {
  11452. return;
  11453. }
  11454. _this._pointerPressed.splice(index, 1);
  11455. if (index != 0) {
  11456. return;
  11457. }
  11458. previousPosition = null;
  11459. _this._offsetX = null;
  11460. _this._offsetY = null;
  11461. };
  11462. this._onPointerMove = function (evt) {
  11463. if (evt.pointerType === "mouse") {
  11464. return;
  11465. }
  11466. if (!noPreventDefault) {
  11467. evt.preventDefault();
  11468. }
  11469. if (!previousPosition) {
  11470. return;
  11471. }
  11472. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11473. if (index != 0) {
  11474. return;
  11475. }
  11476. _this._offsetX = evt.clientX - previousPosition.x;
  11477. _this._offsetY = -(evt.clientY - previousPosition.y);
  11478. };
  11479. }
  11480. element.addEventListener("blur", this._onLostFocus);
  11481. element.addEventListener("pointerdown", this._onPointerDown);
  11482. element.addEventListener("pointerup", this._onPointerUp);
  11483. element.addEventListener("pointerout", this._onPointerUp);
  11484. element.addEventListener("pointermove", this._onPointerMove);
  11485. };
  11486. FreeCameraTouchInput.prototype.detachElement = function (element) {
  11487. if (this._attachedElement !== element) {
  11488. return;
  11489. }
  11490. element.removeEventListener("blur", this._onLostFocus);
  11491. element.removeEventListener("pointerdown", this._onPointerDown);
  11492. element.removeEventListener("pointerup", this._onPointerUp);
  11493. element.removeEventListener("pointerout", this._onPointerUp);
  11494. element.removeEventListener("pointermove", this._onPointerMove);
  11495. this._attachedElement = null;
  11496. };
  11497. FreeCameraTouchInput.prototype.checkInputs = function () {
  11498. if (this._offsetX) {
  11499. var camera = this.camera;
  11500. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11501. if (this._pointerPressed.length > 1) {
  11502. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11503. }
  11504. else {
  11505. var speed = camera._computeLocalCameraSpeed();
  11506. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11507. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11508. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11509. }
  11510. }
  11511. };
  11512. FreeCameraTouchInput.prototype.detach = function () {
  11513. if (this._attachedElement) {
  11514. this.detachElement(this._attachedElement);
  11515. }
  11516. };
  11517. FreeCameraTouchInput.prototype.getTypeName = function () {
  11518. return "FreeCameraTouchInput";
  11519. };
  11520. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11521. return "touch";
  11522. };
  11523. __decorate([
  11524. BABYLON.serialize()
  11525. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11526. __decorate([
  11527. BABYLON.serialize()
  11528. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11529. return FreeCameraTouchInput;
  11530. })();
  11531. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11532. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11533. })(BABYLON || (BABYLON = {}));
  11534. var BABYLON;
  11535. (function (BABYLON) {
  11536. var FreeCameraDeviceOrientationInput = (function () {
  11537. function FreeCameraDeviceOrientationInput() {
  11538. this._offsetX = null;
  11539. this._offsetY = null;
  11540. this._orientationGamma = 0;
  11541. this._orientationBeta = 0;
  11542. this._initialOrientationGamma = 0;
  11543. this._initialOrientationBeta = 0;
  11544. this.angularSensibility = 10000.0;
  11545. this.moveSensibility = 50.0;
  11546. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11547. this._orientationChanged = this.orientationChanged.bind(this);
  11548. }
  11549. FreeCameraDeviceOrientationInput.prototype.attachCamera = function (camera) {
  11550. this.camera = camera;
  11551. window.addEventListener("resize", this._resetOrientationGamma, false);
  11552. window.addEventListener("deviceorientation", this._orientationChanged);
  11553. };
  11554. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11555. this._initialOrientationGamma = null;
  11556. };
  11557. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11558. if (!this._initialOrientationGamma) {
  11559. this._initialOrientationGamma = evt.gamma;
  11560. this._initialOrientationBeta = evt.beta;
  11561. }
  11562. this._orientationGamma = evt.gamma;
  11563. this._orientationBeta = evt.beta;
  11564. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11565. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11566. };
  11567. FreeCameraDeviceOrientationInput.prototype.detach = function () {
  11568. window.removeEventListener("resize", this._resetOrientationGamma);
  11569. window.removeEventListener("deviceorientation", this._orientationChanged);
  11570. this._orientationGamma = 0;
  11571. this._orientationBeta = 0;
  11572. this._initialOrientationGamma = 0;
  11573. this._initialOrientationBeta = 0;
  11574. };
  11575. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11576. if (!this._offsetX) {
  11577. return;
  11578. }
  11579. var camera = this.camera;
  11580. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11581. var speed = camera._computeLocalCameraSpeed();
  11582. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11583. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11584. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11585. };
  11586. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11587. return "FreeCameraDeviceOrientationInput";
  11588. };
  11589. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11590. return "deviceOrientation";
  11591. };
  11592. __decorate([
  11593. BABYLON.serialize()
  11594. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11595. __decorate([
  11596. BABYLON.serialize()
  11597. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11598. return FreeCameraDeviceOrientationInput;
  11599. })();
  11600. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11601. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11602. })(BABYLON || (BABYLON = {}));
  11603. var BABYLON;
  11604. (function (BABYLON) {
  11605. var FreeCameraVRDeviceOrientationInput = (function () {
  11606. function FreeCameraVRDeviceOrientationInput() {
  11607. this._alpha = 0;
  11608. this._beta = 0;
  11609. this._gamma = 0;
  11610. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11611. }
  11612. FreeCameraVRDeviceOrientationInput.prototype.attachCamera = function (camera) {
  11613. this.camera = camera;
  11614. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11615. };
  11616. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11617. var camera = this.camera;
  11618. this._alpha = +evt.alpha | 0;
  11619. this._beta = +evt.beta | 0;
  11620. this._gamma = +evt.gamma | 0;
  11621. if (this._gamma < 0) {
  11622. this._gamma = 90 + this._gamma;
  11623. }
  11624. else {
  11625. // Incline it in the correct angle.
  11626. this._gamma = 270 - this._gamma;
  11627. }
  11628. camera.rotation.x = this._gamma / 180.0 * Math.PI;
  11629. camera.rotation.y = -this._alpha / 180.0 * Math.PI;
  11630. camera.rotation.z = this._beta / 180.0 * Math.PI;
  11631. };
  11632. FreeCameraVRDeviceOrientationInput.prototype.detach = function () {
  11633. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11634. };
  11635. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  11636. return "FreeCameraVRDeviceOrientationInput";
  11637. };
  11638. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  11639. return "VRDeviceOrientation";
  11640. };
  11641. return FreeCameraVRDeviceOrientationInput;
  11642. })();
  11643. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  11644. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  11645. })(BABYLON || (BABYLON = {}));
  11646. var BABYLON;
  11647. (function (BABYLON) {
  11648. var FreeCameraGamepadInput = (function () {
  11649. function FreeCameraGamepadInput() {
  11650. var _this = this;
  11651. this.gamepadAngularSensibility = 200;
  11652. this.gamepadMoveSensibility = 40;
  11653. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11654. }
  11655. FreeCameraGamepadInput.prototype.attachCamera = function (camera) {
  11656. this.camera = camera;
  11657. };
  11658. FreeCameraGamepadInput.prototype.detach = function () {
  11659. this._gamepads.dispose();
  11660. };
  11661. FreeCameraGamepadInput.prototype.checkInputs = function () {
  11662. if (this.gamepad) {
  11663. var camera = this.camera;
  11664. var LSValues = this.gamepad.leftStick;
  11665. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  11666. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  11667. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11668. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11669. var RSValues = this.gamepad.rightStick;
  11670. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  11671. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  11672. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11673. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11674. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11675. var speed = camera._computeLocalCameraSpeed() * 50.0;
  11676. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11677. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11678. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11679. }
  11680. };
  11681. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  11682. // Only the first gamepad can control the camera
  11683. if (gamepad.index === 0) {
  11684. this.gamepad = gamepad;
  11685. }
  11686. };
  11687. FreeCameraGamepadInput.prototype.getTypeName = function () {
  11688. return "FreeCameraGamepadInput";
  11689. };
  11690. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  11691. return "gamepad";
  11692. };
  11693. __decorate([
  11694. BABYLON.serialize()
  11695. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  11696. __decorate([
  11697. BABYLON.serialize()
  11698. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  11699. return FreeCameraGamepadInput;
  11700. })();
  11701. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  11702. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  11703. })(BABYLON || (BABYLON = {}));
  11704. var BABYLON;
  11705. (function (BABYLON) {
  11706. var FreeCameraVirtualJoystickInput = (function () {
  11707. function FreeCameraVirtualJoystickInput() {
  11708. }
  11709. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  11710. return this._leftjoystick;
  11711. };
  11712. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  11713. return this._rightjoystick;
  11714. };
  11715. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  11716. var camera = this.camera;
  11717. var speed = camera._computeLocalCameraSpeed() * 50;
  11718. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11719. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  11720. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11721. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  11722. if (!this._leftjoystick.pressed) {
  11723. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  11724. }
  11725. if (!this._rightjoystick.pressed) {
  11726. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  11727. }
  11728. };
  11729. FreeCameraVirtualJoystickInput.prototype.attachCamera = function (camera) {
  11730. this.camera = camera;
  11731. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  11732. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  11733. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  11734. this._leftjoystick.setJoystickSensibility(0.15);
  11735. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  11736. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  11737. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  11738. this._rightjoystick.reverseUpDown = true;
  11739. this._rightjoystick.setJoystickSensibility(0.05);
  11740. this._rightjoystick.setJoystickColor("yellow");
  11741. };
  11742. FreeCameraVirtualJoystickInput.prototype.detach = function () {
  11743. this._leftjoystick.releaseCanvas();
  11744. };
  11745. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  11746. return "FreeCameraVirtualJoystickInput";
  11747. };
  11748. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  11749. return "virtualJoystick";
  11750. };
  11751. return FreeCameraVirtualJoystickInput;
  11752. })();
  11753. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  11754. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  11755. })(BABYLON || (BABYLON = {}));
  11756. var BABYLON;
  11757. (function (BABYLON) {
  11758. var ArcRotateCameraKeyboardMoveInput = (function () {
  11759. function ArcRotateCameraKeyboardMoveInput() {
  11760. this._keys = [];
  11761. this.keysUp = [38];
  11762. this.keysDown = [40];
  11763. this.keysLeft = [37];
  11764. this.keysRight = [39];
  11765. }
  11766. ArcRotateCameraKeyboardMoveInput.prototype.attachCamera = function (camera) {
  11767. var _this = this;
  11768. this.camera = camera;
  11769. this._onKeyDown = function (evt) {
  11770. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11771. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11772. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11773. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11774. var index = _this._keys.indexOf(evt.keyCode);
  11775. if (index === -1) {
  11776. _this._keys.push(evt.keyCode);
  11777. }
  11778. if (evt.preventDefault) {
  11779. if (!camera._noPreventDefault) {
  11780. evt.preventDefault();
  11781. }
  11782. }
  11783. }
  11784. };
  11785. this._onKeyUp = function (evt) {
  11786. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11787. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11788. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11789. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11790. var index = _this._keys.indexOf(evt.keyCode);
  11791. if (index >= 0) {
  11792. _this._keys.splice(index, 1);
  11793. }
  11794. if (evt.preventDefault) {
  11795. if (!camera._noPreventDefault) {
  11796. evt.preventDefault();
  11797. }
  11798. }
  11799. }
  11800. };
  11801. this._onLostFocus = function () {
  11802. _this._keys = [];
  11803. };
  11804. BABYLON.Tools.RegisterTopRootEvents([
  11805. { name: "keydown", handler: this._onKeyDown },
  11806. { name: "keyup", handler: this._onKeyUp },
  11807. { name: "blur", handler: this._onLostFocus }
  11808. ]);
  11809. };
  11810. ArcRotateCameraKeyboardMoveInput.prototype.detach = function () {
  11811. BABYLON.Tools.UnregisterTopRootEvents([
  11812. { name: "keydown", handler: this._onKeyDown },
  11813. { name: "keyup", handler: this._onKeyUp },
  11814. { name: "blur", handler: this._onLostFocus }
  11815. ]);
  11816. };
  11817. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11818. var camera = this.camera;
  11819. for (var index = 0; index < this._keys.length; index++) {
  11820. var keyCode = this._keys[index];
  11821. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11822. camera.inertialAlphaOffset -= 0.01;
  11823. }
  11824. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11825. camera.inertialBetaOffset -= 0.01;
  11826. }
  11827. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11828. camera.inertialAlphaOffset += 0.01;
  11829. }
  11830. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11831. camera.inertialBetaOffset += 0.01;
  11832. }
  11833. }
  11834. };
  11835. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11836. return "ArcRotateCameraKeyboardMoveInput";
  11837. };
  11838. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11839. return "keyboard";
  11840. };
  11841. __decorate([
  11842. BABYLON.serialize()
  11843. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11844. __decorate([
  11845. BABYLON.serialize()
  11846. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11847. __decorate([
  11848. BABYLON.serialize()
  11849. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11850. __decorate([
  11851. BABYLON.serialize()
  11852. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11853. return ArcRotateCameraKeyboardMoveInput;
  11854. })();
  11855. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  11856. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  11857. })(BABYLON || (BABYLON = {}));
  11858. var BABYLON;
  11859. (function (BABYLON) {
  11860. var ArcRotateCameraMouseWheelInput = (function () {
  11861. function ArcRotateCameraMouseWheelInput() {
  11862. this.wheelPrecision = 3.0;
  11863. }
  11864. ArcRotateCameraMouseWheelInput.prototype.attachCamera = function (camera) {
  11865. this.camera = camera;
  11866. };
  11867. ArcRotateCameraMouseWheelInput.prototype.attachElement = function (element) {
  11868. var _this = this;
  11869. this.attachedElement = element;
  11870. this._wheel = function (event) {
  11871. var delta = 0;
  11872. if (event.wheelDelta) {
  11873. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11874. }
  11875. else if (event.detail) {
  11876. delta = -event.detail / _this.wheelPrecision;
  11877. }
  11878. if (delta)
  11879. _this.camera.inertialRadiusOffset += delta;
  11880. if (event.preventDefault) {
  11881. if (!_this.camera._noPreventDefault) {
  11882. event.preventDefault();
  11883. }
  11884. }
  11885. };
  11886. element.addEventListener('mousewheel', this._wheel, false);
  11887. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11888. };
  11889. ArcRotateCameraMouseWheelInput.prototype.detach = function () {
  11890. this.attachedElement.removeEventListener('mousewheel', this._wheel);
  11891. this.attachedElement.removeEventListener('DOMMouseScroll', this._wheel);
  11892. };
  11893. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  11894. return "ArcRotateCameraMouseWheelInput";
  11895. };
  11896. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  11897. return "mousewheel";
  11898. };
  11899. __decorate([
  11900. BABYLON.serialize()
  11901. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  11902. return ArcRotateCameraMouseWheelInput;
  11903. })();
  11904. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  11905. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  11906. })(BABYLON || (BABYLON = {}));
  11907. var BABYLON;
  11908. (function (BABYLON) {
  11909. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11910. var ArcRotateCameraPointersInput = (function () {
  11911. function ArcRotateCameraPointersInput() {
  11912. this._isRightClick = false;
  11913. this._isCtrlPushed = false;
  11914. this.pinchInwards = true;
  11915. this.angularSensibilityX = 1000.0;
  11916. this.angularSensibilityY = 1000.0;
  11917. this.pinchPrecision = 6.0;
  11918. this.panningSensibility = 50.0;
  11919. }
  11920. ArcRotateCameraPointersInput.prototype.attachCamera = function (camera) {
  11921. this.camera = camera;
  11922. };
  11923. ArcRotateCameraPointersInput.prototype.attachElement = function (element, noPreventDefault) {
  11924. var _this = this;
  11925. this.attachedElement = element;
  11926. var engine = this.camera.getEngine();
  11927. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11928. var pointers = new BABYLON.SmartCollection();
  11929. var previousPinchDistance = 0;
  11930. if (this._onPointerDown === undefined) {
  11931. if (!this.camera._useCtrlForPanning) {
  11932. element.addEventListener("contextmenu", this._onContextMenu, false);
  11933. }
  11934. this._onLostFocus = function () {
  11935. //this._keys = [];
  11936. pointers.empty();
  11937. previousPinchDistance = 0;
  11938. cacheSoloPointer = null;
  11939. };
  11940. this._onKeyDown = function (evt) {
  11941. _this._isCtrlPushed = evt.ctrlKey;
  11942. };
  11943. this._onKeyUp = function (evt) {
  11944. _this._isCtrlPushed = evt.ctrlKey;
  11945. };
  11946. this._onPointerDown = function (evt) {
  11947. // Manage panning with right click
  11948. _this._isRightClick = evt.button === 2;
  11949. // manage pointers
  11950. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11951. cacheSoloPointer = pointers.item(evt.pointerId);
  11952. if (!noPreventDefault) {
  11953. evt.preventDefault();
  11954. }
  11955. };
  11956. this._onPointerUp = function (evt) {
  11957. cacheSoloPointer = null;
  11958. previousPinchDistance = 0;
  11959. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11960. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11961. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11962. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11963. pointers.empty();
  11964. if (!noPreventDefault) {
  11965. evt.preventDefault();
  11966. }
  11967. };
  11968. this._onContextMenu = function (evt) {
  11969. evt.preventDefault();
  11970. };
  11971. this._onPointerMove = function (evt) {
  11972. if (!noPreventDefault) {
  11973. evt.preventDefault();
  11974. }
  11975. switch (pointers.count) {
  11976. case 1:
  11977. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  11978. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11979. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11980. }
  11981. else {
  11982. var offsetX = evt.clientX - cacheSoloPointer.x;
  11983. var offsetY = evt.clientY - cacheSoloPointer.y;
  11984. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11985. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11986. }
  11987. cacheSoloPointer.x = evt.clientX;
  11988. cacheSoloPointer.y = evt.clientY;
  11989. break;
  11990. case 2:
  11991. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11992. pointers.item(evt.pointerId).x = evt.clientX;
  11993. pointers.item(evt.pointerId).y = evt.clientY;
  11994. var direction = _this.pinchInwards ? 1 : -1;
  11995. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11996. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11997. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11998. if (previousPinchDistance === 0) {
  11999. previousPinchDistance = pinchSquaredDistance;
  12000. return;
  12001. }
  12002. if (pinchSquaredDistance !== previousPinchDistance) {
  12003. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12004. previousPinchDistance = pinchSquaredDistance;
  12005. }
  12006. break;
  12007. default:
  12008. if (pointers.item(evt.pointerId)) {
  12009. pointers.item(evt.pointerId).x = evt.clientX;
  12010. pointers.item(evt.pointerId).y = evt.clientY;
  12011. }
  12012. }
  12013. };
  12014. this._onMouseMove = function (evt) {
  12015. if (!engine.isPointerLock) {
  12016. return;
  12017. }
  12018. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12019. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12020. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12021. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12022. if (!noPreventDefault) {
  12023. evt.preventDefault();
  12024. }
  12025. };
  12026. this._onGestureStart = function (e) {
  12027. if (window.MSGesture === undefined) {
  12028. return;
  12029. }
  12030. if (!_this._MSGestureHandler) {
  12031. _this._MSGestureHandler = new MSGesture();
  12032. _this._MSGestureHandler.target = element;
  12033. }
  12034. _this._MSGestureHandler.addPointer(e.pointerId);
  12035. };
  12036. this._onGesture = function (e) {
  12037. _this.camera.radius *= e.scale;
  12038. if (e.preventDefault) {
  12039. if (!noPreventDefault) {
  12040. e.stopPropagation();
  12041. e.preventDefault();
  12042. }
  12043. }
  12044. };
  12045. }
  12046. this.attachedElement.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12047. this.attachedElement.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12048. this.attachedElement.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12049. this.attachedElement.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12050. this.attachedElement.addEventListener("mousemove", this._onMouseMove, false);
  12051. this.attachedElement.addEventListener("MSPointerDown", this._onGestureStart, false);
  12052. this.attachedElement.addEventListener("MSGestureChange", this._onGesture, false);
  12053. BABYLON.Tools.RegisterTopRootEvents([
  12054. { name: "blur", handler: this._onLostFocus }
  12055. ]);
  12056. };
  12057. ArcRotateCameraPointersInput.prototype.detach = function () {
  12058. this._MSGestureHandler = null;
  12059. this.attachedElement.removeEventListener("contextmenu", this._onContextMenu);
  12060. this.attachedElement.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12061. this.attachedElement.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12062. this.attachedElement.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12063. this.attachedElement.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12064. this.attachedElement.removeEventListener("mousemove", this._onMouseMove);
  12065. this.attachedElement.removeEventListener("MSPointerDown", this._onGestureStart);
  12066. this.attachedElement.removeEventListener("MSGestureChange", this._onGesture);
  12067. BABYLON.Tools.UnregisterTopRootEvents([
  12068. { name: "blur", handler: this._onLostFocus }
  12069. ]);
  12070. };
  12071. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12072. return "ArcRotateCameraPointersInput";
  12073. };
  12074. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12075. return "pointers";
  12076. };
  12077. __decorate([
  12078. BABYLON.serialize()
  12079. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12080. __decorate([
  12081. BABYLON.serialize()
  12082. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12083. __decorate([
  12084. BABYLON.serialize()
  12085. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12086. __decorate([
  12087. BABYLON.serialize()
  12088. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12089. return ArcRotateCameraPointersInput;
  12090. })();
  12091. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12092. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12093. })(BABYLON || (BABYLON = {}));
  12094. var BABYLON;
  12095. (function (BABYLON) {
  12096. var ArcRotateCameraGamepadInput = (function () {
  12097. function ArcRotateCameraGamepadInput() {
  12098. var _this = this;
  12099. this.gamepadRotationSensibility = 80;
  12100. this.gamepadMoveSensibility = 40;
  12101. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12102. }
  12103. ArcRotateCameraGamepadInput.prototype.attachCamera = function (camera) {
  12104. this.camera = camera;
  12105. };
  12106. ArcRotateCameraGamepadInput.prototype.detach = function () {
  12107. this._gamepads.dispose();
  12108. };
  12109. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12110. if (this.gamepad) {
  12111. var camera = this.camera;
  12112. var RSValues = this.gamepad.rightStick;
  12113. if (RSValues.x != 0) {
  12114. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12115. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12116. camera.inertialAlphaOffset += normalizedRX;
  12117. }
  12118. }
  12119. if (RSValues.y != 0) {
  12120. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12121. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12122. camera.inertialBetaOffset += normalizedRY;
  12123. }
  12124. }
  12125. var LSValues = this.gamepad.leftStick;
  12126. if (LSValues.y != 0) {
  12127. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12128. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12129. this.camera.inertialRadiusOffset -= normalizedLY;
  12130. }
  12131. }
  12132. }
  12133. };
  12134. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12135. // Only the first gamepad can control the camera
  12136. if (gamepad.index === 0) {
  12137. this.gamepad = gamepad;
  12138. }
  12139. };
  12140. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12141. return "ArcRotateCameraGamepadInput";
  12142. };
  12143. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12144. return "gamepad";
  12145. };
  12146. __decorate([
  12147. BABYLON.serialize()
  12148. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12149. __decorate([
  12150. BABYLON.serialize()
  12151. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12152. return ArcRotateCameraGamepadInput;
  12153. })();
  12154. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12155. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12156. })(BABYLON || (BABYLON = {}));
  12157. var BABYLON;
  12158. (function (BABYLON) {
  12159. var TargetCamera = (function (_super) {
  12160. __extends(TargetCamera, _super);
  12161. function TargetCamera(name, position, scene) {
  12162. _super.call(this, name, position, scene);
  12163. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12164. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12165. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12166. this.speed = 2.0;
  12167. this.noRotationConstraint = false;
  12168. this.lockedTarget = null;
  12169. this._currentTarget = BABYLON.Vector3.Zero();
  12170. this._viewMatrix = BABYLON.Matrix.Zero();
  12171. this._camMatrix = BABYLON.Matrix.Zero();
  12172. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12173. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12174. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12175. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12176. this._lookAtTemp = BABYLON.Matrix.Zero();
  12177. this._tempMatrix = BABYLON.Matrix.Zero();
  12178. }
  12179. TargetCamera.prototype.getFrontPosition = function (distance) {
  12180. var direction = this.getTarget().subtract(this.position);
  12181. direction.normalize();
  12182. direction.scaleInPlace(distance);
  12183. return this.globalPosition.add(direction);
  12184. };
  12185. TargetCamera.prototype._getLockedTargetPosition = function () {
  12186. if (!this.lockedTarget) {
  12187. return null;
  12188. }
  12189. return this.lockedTarget.position || this.lockedTarget;
  12190. };
  12191. // Cache
  12192. TargetCamera.prototype._initCache = function () {
  12193. _super.prototype._initCache.call(this);
  12194. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12195. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12196. };
  12197. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12198. if (!ignoreParentClass) {
  12199. _super.prototype._updateCache.call(this);
  12200. }
  12201. var lockedTargetPosition = this._getLockedTargetPosition();
  12202. if (!lockedTargetPosition) {
  12203. this._cache.lockedTarget = null;
  12204. }
  12205. else {
  12206. if (!this._cache.lockedTarget) {
  12207. this._cache.lockedTarget = lockedTargetPosition.clone();
  12208. }
  12209. else {
  12210. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12211. }
  12212. }
  12213. this._cache.rotation.copyFrom(this.rotation);
  12214. };
  12215. // Synchronized
  12216. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12217. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12218. return false;
  12219. }
  12220. var lockedTargetPosition = this._getLockedTargetPosition();
  12221. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12222. && this._cache.rotation.equals(this.rotation);
  12223. };
  12224. // Methods
  12225. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12226. var engine = this.getEngine();
  12227. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12228. };
  12229. // Target
  12230. TargetCamera.prototype.setTarget = function (target) {
  12231. this.upVector.normalize();
  12232. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12233. this._camMatrix.invert();
  12234. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12235. var vDir = target.subtract(this.position);
  12236. if (vDir.x >= 0.0) {
  12237. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12238. }
  12239. else {
  12240. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12241. }
  12242. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12243. if (isNaN(this.rotation.x)) {
  12244. this.rotation.x = 0;
  12245. }
  12246. if (isNaN(this.rotation.y)) {
  12247. this.rotation.y = 0;
  12248. }
  12249. if (isNaN(this.rotation.z)) {
  12250. this.rotation.z = 0;
  12251. }
  12252. };
  12253. TargetCamera.prototype.getTarget = function () {
  12254. return this._currentTarget;
  12255. };
  12256. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12257. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12258. };
  12259. TargetCamera.prototype._updatePosition = function () {
  12260. this.position.addInPlace(this.cameraDirection);
  12261. };
  12262. TargetCamera.prototype._checkInputs = function () {
  12263. var needToMove = this._decideIfNeedsToMove();
  12264. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12265. // Move
  12266. if (needToMove) {
  12267. this._updatePosition();
  12268. }
  12269. // Rotate
  12270. if (needToRotate) {
  12271. this.rotation.x += this.cameraRotation.x;
  12272. this.rotation.y += this.cameraRotation.y;
  12273. if (!this.noRotationConstraint) {
  12274. var limit = (Math.PI / 2) * 0.95;
  12275. if (this.rotation.x > limit)
  12276. this.rotation.x = limit;
  12277. if (this.rotation.x < -limit)
  12278. this.rotation.x = -limit;
  12279. }
  12280. }
  12281. // Inertia
  12282. if (needToMove) {
  12283. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12284. this.cameraDirection.x = 0;
  12285. }
  12286. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12287. this.cameraDirection.y = 0;
  12288. }
  12289. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12290. this.cameraDirection.z = 0;
  12291. }
  12292. this.cameraDirection.scaleInPlace(this.inertia);
  12293. }
  12294. if (needToRotate) {
  12295. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12296. this.cameraRotation.x = 0;
  12297. }
  12298. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12299. this.cameraRotation.y = 0;
  12300. }
  12301. this.cameraRotation.scaleInPlace(this.inertia);
  12302. }
  12303. _super.prototype._checkInputs.call(this);
  12304. };
  12305. TargetCamera.prototype._getViewMatrix = function () {
  12306. if (!this.lockedTarget) {
  12307. // Compute
  12308. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12309. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12310. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12311. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12312. this._lookAtTemp.invert();
  12313. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12314. }
  12315. else {
  12316. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12317. }
  12318. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12319. // Computing target and final matrix
  12320. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12321. }
  12322. else {
  12323. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12324. }
  12325. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12326. return this._viewMatrix;
  12327. };
  12328. TargetCamera.prototype._getVRViewMatrix = function () {
  12329. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12330. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12331. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12332. // Computing target and final matrix
  12333. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12334. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12335. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12336. return this._viewMatrix;
  12337. };
  12338. /**
  12339. * @override
  12340. * Override Camera.createRigCamera
  12341. */
  12342. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12343. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12344. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12345. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12346. rigCamera._cameraRigParams = {};
  12347. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12348. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12349. }
  12350. return rigCamera;
  12351. }
  12352. return null;
  12353. };
  12354. /**
  12355. * @override
  12356. * Override Camera._updateRigCameras
  12357. */
  12358. TargetCamera.prototype._updateRigCameras = function () {
  12359. switch (this.cameraRigMode) {
  12360. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12361. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12362. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12363. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12364. case BABYLON.Camera.RIG_MODE_VR:
  12365. var camLeft = this._rigCameras[0];
  12366. var camRight = this._rigCameras[1];
  12367. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12368. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12369. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12370. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12371. camLeft.position.copyFrom(this.position);
  12372. camRight.position.copyFrom(this.position);
  12373. }
  12374. else {
  12375. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12376. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12377. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12378. camLeft.setTarget(this.getTarget());
  12379. camRight.setTarget(this.getTarget());
  12380. }
  12381. break;
  12382. }
  12383. _super.prototype._updateRigCameras.call(this);
  12384. };
  12385. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12386. if (!this._rigCamTransformMatrix) {
  12387. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12388. }
  12389. var target = this.getTarget();
  12390. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12391. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12392. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12393. };
  12394. TargetCamera.prototype.getTypeName = function () {
  12395. return "TargetCamera";
  12396. };
  12397. __decorate([
  12398. BABYLON.serializeAsVector3()
  12399. ], TargetCamera.prototype, "rotation", void 0);
  12400. __decorate([
  12401. BABYLON.serialize()
  12402. ], TargetCamera.prototype, "speed", void 0);
  12403. __decorate([
  12404. BABYLON.serializeAsMeshReference("lockedTargetId")
  12405. ], TargetCamera.prototype, "lockedTarget", void 0);
  12406. return TargetCamera;
  12407. })(BABYLON.Camera);
  12408. BABYLON.TargetCamera = TargetCamera;
  12409. })(BABYLON || (BABYLON = {}));
  12410. var BABYLON;
  12411. (function (BABYLON) {
  12412. var FreeCamera = (function (_super) {
  12413. __extends(FreeCamera, _super);
  12414. function FreeCamera(name, position, scene) {
  12415. var _this = this;
  12416. _super.call(this, name, position, scene);
  12417. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12418. this.checkCollisions = false;
  12419. this.applyGravity = false;
  12420. this._collider = new BABYLON.Collider();
  12421. this._needMoveForGravity = false;
  12422. this._oldPosition = BABYLON.Vector3.Zero();
  12423. this._diffPosition = BABYLON.Vector3.Zero();
  12424. this._newPosition = BABYLON.Vector3.Zero();
  12425. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12426. if (collidedMesh === void 0) { collidedMesh = null; }
  12427. //TODO move this to the collision coordinator!
  12428. if (_this.getScene().workerCollisions)
  12429. newPosition.multiplyInPlace(_this._collider.radius);
  12430. var updatePosition = function (newPos) {
  12431. _this._newPosition.copyFrom(newPos);
  12432. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12433. var oldPosition = _this.position.clone();
  12434. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12435. _this.position.addInPlace(_this._diffPosition);
  12436. if (_this.onCollide && collidedMesh) {
  12437. _this.onCollide(collidedMesh);
  12438. }
  12439. }
  12440. };
  12441. updatePosition(newPosition);
  12442. };
  12443. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12444. this.inputs.addKeyboard().addMouse();
  12445. }
  12446. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12447. //-- begin properties for backward compatibility for inputs
  12448. get: function () {
  12449. var mouse = this.inputs.attached["mouse"];
  12450. if (mouse)
  12451. return mouse.angularSensibility;
  12452. },
  12453. set: function (value) {
  12454. var mouse = this.inputs.attached["mouse"];
  12455. if (mouse)
  12456. mouse.angularSensibility = value;
  12457. },
  12458. enumerable: true,
  12459. configurable: true
  12460. });
  12461. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12462. get: function () {
  12463. var keyboard = this.inputs.attached["keyboard"];
  12464. if (keyboard)
  12465. return keyboard.keysUp;
  12466. },
  12467. set: function (value) {
  12468. var keyboard = this.inputs.attached["keyboard"];
  12469. if (keyboard)
  12470. keyboard.keysUp = value;
  12471. },
  12472. enumerable: true,
  12473. configurable: true
  12474. });
  12475. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12476. get: function () {
  12477. var keyboard = this.inputs.attached["keyboard"];
  12478. if (keyboard)
  12479. return keyboard.keysDown;
  12480. },
  12481. set: function (value) {
  12482. var keyboard = this.inputs.attached["keyboard"];
  12483. if (keyboard)
  12484. keyboard.keysDown = value;
  12485. },
  12486. enumerable: true,
  12487. configurable: true
  12488. });
  12489. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12490. get: function () {
  12491. var keyboard = this.inputs.attached["keyboard"];
  12492. if (keyboard)
  12493. return keyboard.keysLeft;
  12494. },
  12495. set: function (value) {
  12496. var keyboard = this.inputs.attached["keyboard"];
  12497. if (keyboard)
  12498. keyboard.keysLeft = value;
  12499. },
  12500. enumerable: true,
  12501. configurable: true
  12502. });
  12503. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12504. get: function () {
  12505. var keyboard = this.inputs.attached["keyboard"];
  12506. if (keyboard)
  12507. return keyboard.keysRight;
  12508. },
  12509. set: function (value) {
  12510. var keyboard = this.inputs.attached["keyboard"];
  12511. if (keyboard)
  12512. keyboard.keysRight = value;
  12513. },
  12514. enumerable: true,
  12515. configurable: true
  12516. });
  12517. // Controls
  12518. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12519. if (this._attachedElement) {
  12520. return;
  12521. }
  12522. this._noPreventDefault = noPreventDefault;
  12523. this._attachedElement = element;
  12524. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12525. this.inputs.attachElement(element, noPreventDefault);
  12526. };
  12527. FreeCamera.prototype.detachControl = function (element) {
  12528. if (this._attachedElement !== element) {
  12529. return;
  12530. }
  12531. this.inputs.detachElement(this._attachedElement);
  12532. this._attachedElement = null;
  12533. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12534. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12535. };
  12536. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12537. var globalPosition;
  12538. if (this.parent) {
  12539. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12540. }
  12541. else {
  12542. globalPosition = this.position;
  12543. }
  12544. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12545. this._collider.radius = this.ellipsoid;
  12546. //no need for clone, as long as gravity is not on.
  12547. var actualVelocity = velocity;
  12548. //add gravity to the velocity to prevent the dual-collision checking
  12549. if (this.applyGravity) {
  12550. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12551. actualVelocity = velocity.add(this.getScene().gravity);
  12552. }
  12553. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12554. };
  12555. FreeCamera.prototype._checkInputs = function () {
  12556. if (!this._localDirection) {
  12557. this._localDirection = BABYLON.Vector3.Zero();
  12558. this._transformedDirection = BABYLON.Vector3.Zero();
  12559. }
  12560. this.inputs.checkInputs();
  12561. _super.prototype._checkInputs.call(this);
  12562. };
  12563. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12564. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12565. };
  12566. FreeCamera.prototype._updatePosition = function () {
  12567. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  12568. this._collideWithWorld(this.cameraDirection);
  12569. }
  12570. else {
  12571. this.position.addInPlace(this.cameraDirection);
  12572. }
  12573. };
  12574. FreeCamera.prototype.dispose = function () {
  12575. this.inputs.clear();
  12576. _super.prototype.dispose.call(this);
  12577. };
  12578. FreeCamera.prototype.getTypeName = function () {
  12579. return "FreeCamera";
  12580. };
  12581. __decorate([
  12582. BABYLON.serializeAsVector3()
  12583. ], FreeCamera.prototype, "ellipsoid", void 0);
  12584. __decorate([
  12585. BABYLON.serialize()
  12586. ], FreeCamera.prototype, "checkCollisions", void 0);
  12587. __decorate([
  12588. BABYLON.serialize()
  12589. ], FreeCamera.prototype, "applyGravity", void 0);
  12590. return FreeCamera;
  12591. })(BABYLON.TargetCamera);
  12592. BABYLON.FreeCamera = FreeCamera;
  12593. })(BABYLON || (BABYLON = {}));
  12594. var BABYLON;
  12595. (function (BABYLON) {
  12596. var FreeCameraInputsManager = (function (_super) {
  12597. __extends(FreeCameraInputsManager, _super);
  12598. function FreeCameraInputsManager(camera) {
  12599. _super.call(this, camera);
  12600. }
  12601. FreeCameraInputsManager.prototype.add = function (input) {
  12602. _super.prototype.add.call(this, input);
  12603. if (this.camera._attachedElement && input.attachElement) {
  12604. input.attachElement(this.camera._attachedElement, this.camera._noPreventDefault);
  12605. }
  12606. };
  12607. FreeCameraInputsManager.prototype.addKeyboard = function () {
  12608. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  12609. return this;
  12610. };
  12611. FreeCameraInputsManager.prototype.addMouse = function () {
  12612. this.add(new BABYLON.FreeCameraMouseInput());
  12613. return this;
  12614. };
  12615. FreeCameraInputsManager.prototype.addGamepad = function () {
  12616. this.add(new BABYLON.FreeCameraGamepadInput());
  12617. return this;
  12618. };
  12619. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  12620. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  12621. return this;
  12622. };
  12623. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  12624. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  12625. return this;
  12626. };
  12627. FreeCameraInputsManager.prototype.addTouch = function () {
  12628. this.add(new BABYLON.FreeCameraTouchInput());
  12629. return this;
  12630. };
  12631. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  12632. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  12633. return this;
  12634. };
  12635. return FreeCameraInputsManager;
  12636. })(BABYLON.CameraInputsManager);
  12637. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  12638. })(BABYLON || (BABYLON = {}));
  12639. var BABYLON;
  12640. (function (BABYLON) {
  12641. var FollowCamera = (function (_super) {
  12642. __extends(FollowCamera, _super);
  12643. function FollowCamera(name, position, scene, target) {
  12644. _super.call(this, name, position, scene);
  12645. this.radius = 12;
  12646. this.rotationOffset = 0;
  12647. this.heightOffset = 4;
  12648. this.cameraAcceleration = 0.05;
  12649. this.maxCameraSpeed = 20;
  12650. this.target = target;
  12651. }
  12652. FollowCamera.prototype.getRadians = function (degrees) {
  12653. return degrees * Math.PI / 180;
  12654. };
  12655. FollowCamera.prototype.follow = function (cameraTarget) {
  12656. if (!cameraTarget)
  12657. return;
  12658. var yRotation;
  12659. if (cameraTarget.rotationQuaternion) {
  12660. var rotMatrix = new BABYLON.Matrix();
  12661. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  12662. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  12663. }
  12664. else {
  12665. yRotation = cameraTarget.rotation.y;
  12666. }
  12667. var radians = this.getRadians(this.rotationOffset) + yRotation;
  12668. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  12669. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  12670. var dx = targetX - this.position.x;
  12671. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  12672. var dz = (targetZ) - this.position.z;
  12673. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  12674. var vy = dy * this.cameraAcceleration;
  12675. var vz = dz * this.cameraAcceleration * 2;
  12676. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  12677. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12678. }
  12679. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  12680. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12681. }
  12682. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  12683. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12684. }
  12685. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  12686. this.setTarget(cameraTarget.position);
  12687. };
  12688. FollowCamera.prototype._checkInputs = function () {
  12689. _super.prototype._checkInputs.call(this);
  12690. this.follow(this.target);
  12691. };
  12692. FollowCamera.prototype.getTypeName = function () {
  12693. return "FollowCamera";
  12694. };
  12695. __decorate([
  12696. BABYLON.serialize()
  12697. ], FollowCamera.prototype, "radius", void 0);
  12698. __decorate([
  12699. BABYLON.serialize()
  12700. ], FollowCamera.prototype, "rotationOffset", void 0);
  12701. __decorate([
  12702. BABYLON.serialize()
  12703. ], FollowCamera.prototype, "heightOffset", void 0);
  12704. __decorate([
  12705. BABYLON.serialize()
  12706. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  12707. __decorate([
  12708. BABYLON.serialize()
  12709. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  12710. __decorate([
  12711. BABYLON.serializeAsMeshReference("lockedTargetId")
  12712. ], FollowCamera.prototype, "target", void 0);
  12713. return FollowCamera;
  12714. })(BABYLON.TargetCamera);
  12715. BABYLON.FollowCamera = FollowCamera;
  12716. var ArcFollowCamera = (function (_super) {
  12717. __extends(ArcFollowCamera, _super);
  12718. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  12719. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12720. this.alpha = alpha;
  12721. this.beta = beta;
  12722. this.radius = radius;
  12723. this.target = target;
  12724. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  12725. this.follow();
  12726. }
  12727. ArcFollowCamera.prototype.follow = function () {
  12728. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  12729. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  12730. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  12731. this.position = this.target.position.add(this._cartesianCoordinates);
  12732. this.setTarget(this.target.position);
  12733. };
  12734. ArcFollowCamera.prototype._checkInputs = function () {
  12735. _super.prototype._checkInputs.call(this);
  12736. this.follow();
  12737. };
  12738. ArcFollowCamera.prototype.getTypeName = function () {
  12739. return "ArcFollowCamera";
  12740. };
  12741. return ArcFollowCamera;
  12742. })(BABYLON.TargetCamera);
  12743. BABYLON.ArcFollowCamera = ArcFollowCamera;
  12744. })(BABYLON || (BABYLON = {}));
  12745. var BABYLON;
  12746. (function (BABYLON) {
  12747. // We're mainly based on the logic defined into the FreeCamera code
  12748. var TouchCamera = (function (_super) {
  12749. __extends(TouchCamera, _super);
  12750. //-- end properties for backward compatibility for inputs
  12751. function TouchCamera(name, position, scene) {
  12752. _super.call(this, name, position, scene);
  12753. this.inputs.addTouch();
  12754. }
  12755. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  12756. //-- Begin properties for backward compatibility for inputs
  12757. get: function () {
  12758. var touch = this.inputs.attached["touch"];
  12759. if (touch)
  12760. return touch.touchAngularSensibility;
  12761. },
  12762. set: function (value) {
  12763. var touch = this.inputs.attached["touch"];
  12764. if (touch)
  12765. touch.touchAngularSensibility = value;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  12771. get: function () {
  12772. var touch = this.inputs.attached["touch"];
  12773. if (touch)
  12774. return touch.touchMoveSensibility;
  12775. },
  12776. set: function (value) {
  12777. var touch = this.inputs.attached["touch"];
  12778. if (touch)
  12779. touch.touchMoveSensibility = value;
  12780. },
  12781. enumerable: true,
  12782. configurable: true
  12783. });
  12784. TouchCamera.prototype.getTypeName = function () {
  12785. return "TouchCamera";
  12786. };
  12787. return TouchCamera;
  12788. })(BABYLON.FreeCamera);
  12789. BABYLON.TouchCamera = TouchCamera;
  12790. })(BABYLON || (BABYLON = {}));
  12791. var BABYLON;
  12792. (function (BABYLON) {
  12793. var ArcRotateCamera = (function (_super) {
  12794. __extends(ArcRotateCamera, _super);
  12795. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  12796. var _this = this;
  12797. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12798. this.inertialAlphaOffset = 0;
  12799. this.inertialBetaOffset = 0;
  12800. this.inertialRadiusOffset = 0;
  12801. this.lowerAlphaLimit = null;
  12802. this.upperAlphaLimit = null;
  12803. this.lowerBetaLimit = 0.01;
  12804. this.upperBetaLimit = Math.PI;
  12805. this.lowerRadiusLimit = null;
  12806. this.upperRadiusLimit = null;
  12807. this.inertialPanningX = 0;
  12808. this.inertialPanningY = 0;
  12809. //-- end properties for backward compatibility for inputs
  12810. this.zoomOnFactor = 1;
  12811. this.targetScreenOffset = BABYLON.Vector2.Zero();
  12812. this.allowUpsideDown = true;
  12813. this._viewMatrix = new BABYLON.Matrix();
  12814. // Panning
  12815. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  12816. this.checkCollisions = false;
  12817. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12818. this._collider = new BABYLON.Collider();
  12819. this._previousPosition = BABYLON.Vector3.Zero();
  12820. this._collisionVelocity = BABYLON.Vector3.Zero();
  12821. this._newPosition = BABYLON.Vector3.Zero();
  12822. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12823. if (collidedMesh === void 0) { collidedMesh = null; }
  12824. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  12825. newPosition.multiplyInPlace(_this._collider.radius);
  12826. }
  12827. if (!collidedMesh) {
  12828. _this._previousPosition.copyFrom(_this.position);
  12829. }
  12830. else {
  12831. _this.setPosition(newPosition);
  12832. if (_this.onCollide) {
  12833. _this.onCollide(collidedMesh);
  12834. }
  12835. }
  12836. // Recompute because of constraints
  12837. var cosa = Math.cos(_this.alpha);
  12838. var sina = Math.sin(_this.alpha);
  12839. var cosb = Math.cos(_this.beta);
  12840. var sinb = Math.sin(_this.beta);
  12841. if (sinb === 0) {
  12842. sinb = 0.0001;
  12843. }
  12844. var target = _this._getTargetPosition();
  12845. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  12846. _this.position.copyFrom(_this._newPosition);
  12847. var up = _this.upVector;
  12848. if (_this.allowUpsideDown && _this.beta < 0) {
  12849. up = up.clone();
  12850. up = up.negate();
  12851. }
  12852. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  12853. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  12854. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  12855. _this._collisionTriggered = false;
  12856. };
  12857. if (!target) {
  12858. this.target = BABYLON.Vector3.Zero();
  12859. }
  12860. else {
  12861. this.target = target;
  12862. }
  12863. this.alpha = alpha;
  12864. this.beta = beta;
  12865. this.radius = radius;
  12866. this.getViewMatrix();
  12867. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  12868. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  12869. }
  12870. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  12871. //-- begin properties for backward compatibility for inputs
  12872. get: function () {
  12873. var pointers = this.inputs.attached["pointers"];
  12874. if (pointers)
  12875. return pointers.angularSensibilityX;
  12876. },
  12877. set: function (value) {
  12878. var pointers = this.inputs.attached["pointers"];
  12879. if (pointers) {
  12880. pointers.angularSensibilityX = value;
  12881. }
  12882. },
  12883. enumerable: true,
  12884. configurable: true
  12885. });
  12886. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  12887. get: function () {
  12888. var pointers = this.inputs.attached["pointers"];
  12889. if (pointers)
  12890. return pointers.angularSensibilityY;
  12891. },
  12892. set: function (value) {
  12893. var pointers = this.inputs.attached["pointers"];
  12894. if (pointers) {
  12895. pointers.angularSensibilityY = value;
  12896. }
  12897. },
  12898. enumerable: true,
  12899. configurable: true
  12900. });
  12901. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  12902. get: function () {
  12903. var pointers = this.inputs.attached["pointers"];
  12904. if (pointers)
  12905. return pointers.pinchPrecision;
  12906. },
  12907. set: function (value) {
  12908. var pointers = this.inputs.attached["pointers"];
  12909. if (pointers) {
  12910. pointers.pinchPrecision = value;
  12911. }
  12912. },
  12913. enumerable: true,
  12914. configurable: true
  12915. });
  12916. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  12917. get: function () {
  12918. var pointers = this.inputs.attached["pointers"];
  12919. if (pointers)
  12920. return pointers.panningSensibility;
  12921. },
  12922. set: function (value) {
  12923. var pointers = this.inputs.attached["pointers"];
  12924. if (pointers) {
  12925. pointers.panningSensibility = value;
  12926. }
  12927. },
  12928. enumerable: true,
  12929. configurable: true
  12930. });
  12931. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  12932. get: function () {
  12933. var keyboard = this.inputs.attached["keyboard"];
  12934. if (keyboard)
  12935. return keyboard.keysUp;
  12936. },
  12937. set: function (value) {
  12938. var keyboard = this.inputs.attached["keyboard"];
  12939. if (keyboard)
  12940. keyboard.keysUp = value;
  12941. },
  12942. enumerable: true,
  12943. configurable: true
  12944. });
  12945. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  12946. get: function () {
  12947. var keyboard = this.inputs.attached["keyboard"];
  12948. if (keyboard)
  12949. return keyboard.keysDown;
  12950. },
  12951. set: function (value) {
  12952. var keyboard = this.inputs.attached["keyboard"];
  12953. if (keyboard)
  12954. keyboard.keysDown = value;
  12955. },
  12956. enumerable: true,
  12957. configurable: true
  12958. });
  12959. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  12960. get: function () {
  12961. var keyboard = this.inputs.attached["keyboard"];
  12962. if (keyboard)
  12963. return keyboard.keysLeft;
  12964. },
  12965. set: function (value) {
  12966. var keyboard = this.inputs.attached["keyboard"];
  12967. if (keyboard)
  12968. keyboard.keysLeft = value;
  12969. },
  12970. enumerable: true,
  12971. configurable: true
  12972. });
  12973. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  12974. get: function () {
  12975. var keyboard = this.inputs.attached["keyboard"];
  12976. if (keyboard)
  12977. return keyboard.keysRight;
  12978. },
  12979. set: function (value) {
  12980. var keyboard = this.inputs.attached["keyboard"];
  12981. if (keyboard)
  12982. keyboard.keysRight = value;
  12983. },
  12984. enumerable: true,
  12985. configurable: true
  12986. });
  12987. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  12988. get: function () {
  12989. var mousewheel = this.inputs.attached["mousewheel"];
  12990. if (mousewheel)
  12991. return mousewheel.wheelPrecision;
  12992. },
  12993. set: function (value) {
  12994. var mousewheel = this.inputs.attached["mousewheel"];
  12995. if (mousewheel)
  12996. mousewheel.wheelPrecision = value;
  12997. },
  12998. enumerable: true,
  12999. configurable: true
  13000. });
  13001. // Cache
  13002. ArcRotateCamera.prototype._initCache = function () {
  13003. _super.prototype._initCache.call(this);
  13004. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13005. this._cache.alpha = undefined;
  13006. this._cache.beta = undefined;
  13007. this._cache.radius = undefined;
  13008. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13009. };
  13010. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13011. if (!ignoreParentClass) {
  13012. _super.prototype._updateCache.call(this);
  13013. }
  13014. this._cache.target.copyFrom(this._getTargetPosition());
  13015. this._cache.alpha = this.alpha;
  13016. this._cache.beta = this.beta;
  13017. this._cache.radius = this.radius;
  13018. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13019. };
  13020. ArcRotateCamera.prototype._getTargetPosition = function () {
  13021. if (this.target.getAbsolutePosition) {
  13022. return this.target.getAbsolutePosition();
  13023. }
  13024. return this.target;
  13025. };
  13026. // Synchronized
  13027. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13028. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13029. return false;
  13030. return this._cache.target.equals(this.target)
  13031. && this._cache.alpha === this.alpha
  13032. && this._cache.beta === this.beta
  13033. && this._cache.radius === this.radius
  13034. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13035. };
  13036. // Methods
  13037. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13038. var _this = this;
  13039. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13040. if (this._attachedElement) {
  13041. return;
  13042. }
  13043. this._attachedElement = element;
  13044. this._noPreventDefault = noPreventDefault;
  13045. this._useCtrlForPanning = useCtrlForPanning;
  13046. this.inputs.attachElement(element, noPreventDefault);
  13047. this._reset = function () {
  13048. _this.inertialAlphaOffset = 0;
  13049. _this.inertialBetaOffset = 0;
  13050. _this.inertialRadiusOffset = 0;
  13051. };
  13052. };
  13053. ArcRotateCamera.prototype.detachControl = function (element) {
  13054. if (this._attachedElement !== element) {
  13055. return;
  13056. }
  13057. this.inputs.detachElement(this._attachedElement);
  13058. this._attachedElement = null;
  13059. if (this._reset) {
  13060. this._reset();
  13061. }
  13062. };
  13063. ArcRotateCamera.prototype._checkInputs = function () {
  13064. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13065. if (this._collisionTriggered) {
  13066. return;
  13067. }
  13068. this.inputs.checkInputs();
  13069. // Inertia
  13070. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13071. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13072. this.beta += this.inertialBetaOffset;
  13073. this.radius -= this.inertialRadiusOffset;
  13074. this.inertialAlphaOffset *= this.inertia;
  13075. this.inertialBetaOffset *= this.inertia;
  13076. this.inertialRadiusOffset *= this.inertia;
  13077. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13078. this.inertialAlphaOffset = 0;
  13079. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13080. this.inertialBetaOffset = 0;
  13081. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13082. this.inertialRadiusOffset = 0;
  13083. }
  13084. // Panning inertia
  13085. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13086. if (!this._localDirection) {
  13087. this._localDirection = BABYLON.Vector3.Zero();
  13088. this._transformedDirection = BABYLON.Vector3.Zero();
  13089. }
  13090. this.inertialPanningX *= this.inertia;
  13091. this.inertialPanningY *= this.inertia;
  13092. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13093. this.inertialPanningX = 0;
  13094. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13095. this.inertialPanningY = 0;
  13096. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13097. this._localDirection.multiplyInPlace(this.panningAxis);
  13098. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13099. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13100. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13101. if (!this.panningAxis.y) {
  13102. this._transformedDirection.y = 0;
  13103. }
  13104. this.target.addInPlace(this._transformedDirection);
  13105. }
  13106. // Limits
  13107. this._checkLimits();
  13108. _super.prototype._checkInputs.call(this);
  13109. };
  13110. ArcRotateCamera.prototype._checkLimits = function () {
  13111. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13112. if (this.allowUpsideDown && this.beta > Math.PI) {
  13113. this.beta = this.beta - (2 * Math.PI);
  13114. }
  13115. }
  13116. else {
  13117. if (this.beta < this.lowerBetaLimit) {
  13118. this.beta = this.lowerBetaLimit;
  13119. }
  13120. }
  13121. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13122. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13123. this.beta = this.beta + (2 * Math.PI);
  13124. }
  13125. }
  13126. else {
  13127. if (this.beta > this.upperBetaLimit) {
  13128. this.beta = this.upperBetaLimit;
  13129. }
  13130. }
  13131. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13132. this.alpha = this.lowerAlphaLimit;
  13133. }
  13134. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13135. this.alpha = this.upperAlphaLimit;
  13136. }
  13137. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13138. this.radius = this.lowerRadiusLimit;
  13139. }
  13140. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13141. this.radius = this.upperRadiusLimit;
  13142. }
  13143. };
  13144. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13145. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13146. this.radius = radiusv3.length();
  13147. // Alpha
  13148. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13149. if (radiusv3.z < 0) {
  13150. this.alpha = 2 * Math.PI - this.alpha;
  13151. }
  13152. // Beta
  13153. this.beta = Math.acos(radiusv3.y / this.radius);
  13154. this._checkLimits();
  13155. };
  13156. ArcRotateCamera.prototype.setPosition = function (position) {
  13157. if (this.position.equals(position)) {
  13158. return;
  13159. }
  13160. this.position = position;
  13161. this.rebuildAnglesAndRadius();
  13162. };
  13163. ArcRotateCamera.prototype.setTarget = function (target) {
  13164. if (this._getTargetPosition().equals(target)) {
  13165. return;
  13166. }
  13167. this.target = target;
  13168. this.rebuildAnglesAndRadius();
  13169. };
  13170. ArcRotateCamera.prototype._getViewMatrix = function () {
  13171. // Compute
  13172. var cosa = Math.cos(this.alpha);
  13173. var sina = Math.sin(this.alpha);
  13174. var cosb = Math.cos(this.beta);
  13175. var sinb = Math.sin(this.beta);
  13176. if (sinb === 0) {
  13177. sinb = 0.0001;
  13178. }
  13179. var target = this._getTargetPosition();
  13180. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13181. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13182. this._collider.radius = this.collisionRadius;
  13183. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13184. this._collisionTriggered = true;
  13185. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13186. }
  13187. else {
  13188. this.position.copyFrom(this._newPosition);
  13189. var up = this.upVector;
  13190. if (this.allowUpsideDown && this.beta < 0) {
  13191. up = up.clone();
  13192. up = up.negate();
  13193. }
  13194. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13195. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13196. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13197. }
  13198. return this._viewMatrix;
  13199. };
  13200. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13201. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13202. meshes = meshes || this.getScene().meshes;
  13203. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13204. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13205. this.radius = distance * this.zoomOnFactor;
  13206. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13207. };
  13208. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13209. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13210. var meshesOrMinMaxVector;
  13211. var distance;
  13212. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13213. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13214. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13215. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13216. }
  13217. else {
  13218. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13219. distance = meshesOrMinMaxVectorAndDistance.distance;
  13220. }
  13221. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13222. if (!doNotUpdateMaxZ) {
  13223. this.maxZ = distance * 2;
  13224. }
  13225. };
  13226. /**
  13227. * @override
  13228. * Override Camera.createRigCamera
  13229. */
  13230. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13231. switch (this.cameraRigMode) {
  13232. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13233. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13234. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13235. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13236. case BABYLON.Camera.RIG_MODE_VR:
  13237. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13238. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13239. }
  13240. return null;
  13241. };
  13242. /**
  13243. * @override
  13244. * Override Camera._updateRigCameras
  13245. */
  13246. ArcRotateCamera.prototype._updateRigCameras = function () {
  13247. switch (this.cameraRigMode) {
  13248. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13249. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13251. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13252. case BABYLON.Camera.RIG_MODE_VR:
  13253. var camLeft = this._rigCameras[0];
  13254. var camRight = this._rigCameras[1];
  13255. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13256. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13257. camLeft.beta = camRight.beta = this.beta;
  13258. camLeft.radius = camRight.radius = this.radius;
  13259. break;
  13260. }
  13261. _super.prototype._updateRigCameras.call(this);
  13262. };
  13263. ArcRotateCamera.prototype.dispose = function () {
  13264. this.inputs.clear();
  13265. _super.prototype.dispose.call(this);
  13266. };
  13267. ArcRotateCamera.prototype.getTypeName = function () {
  13268. return "ArcRotateCamera";
  13269. };
  13270. __decorate([
  13271. BABYLON.serialize()
  13272. ], ArcRotateCamera.prototype, "alpha", void 0);
  13273. __decorate([
  13274. BABYLON.serialize()
  13275. ], ArcRotateCamera.prototype, "beta", void 0);
  13276. __decorate([
  13277. BABYLON.serialize()
  13278. ], ArcRotateCamera.prototype, "radius", void 0);
  13279. __decorate([
  13280. BABYLON.serializeAsVector3()
  13281. ], ArcRotateCamera.prototype, "target", void 0);
  13282. __decorate([
  13283. BABYLON.serialize()
  13284. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13285. __decorate([
  13286. BABYLON.serialize()
  13287. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13288. __decorate([
  13289. BABYLON.serialize()
  13290. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13291. __decorate([
  13292. BABYLON.serialize()
  13293. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13294. __decorate([
  13295. BABYLON.serialize()
  13296. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13297. __decorate([
  13298. BABYLON.serialize()
  13299. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13300. __decorate([
  13301. BABYLON.serialize()
  13302. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13303. __decorate([
  13304. BABYLON.serialize()
  13305. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13306. __decorate([
  13307. BABYLON.serialize()
  13308. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13309. __decorate([
  13310. BABYLON.serialize()
  13311. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13312. __decorate([
  13313. BABYLON.serialize()
  13314. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13315. __decorate([
  13316. BABYLON.serialize()
  13317. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13318. __decorate([
  13319. BABYLON.serialize()
  13320. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13321. return ArcRotateCamera;
  13322. })(BABYLON.TargetCamera);
  13323. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13324. })(BABYLON || (BABYLON = {}));
  13325. var BABYLON;
  13326. (function (BABYLON) {
  13327. var ArcRotateCameraInputsManager = (function (_super) {
  13328. __extends(ArcRotateCameraInputsManager, _super);
  13329. function ArcRotateCameraInputsManager(camera) {
  13330. _super.call(this, camera);
  13331. }
  13332. ArcRotateCameraInputsManager.prototype.add = function (input) {
  13333. _super.prototype.add.call(this, input);
  13334. if (this.camera._attachedElement && input.attachElement) {
  13335. input.attachElement(this.camera._attachedElement, this.camera._noPreventDefault);
  13336. }
  13337. };
  13338. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13339. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13340. return this;
  13341. };
  13342. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13343. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13344. return this;
  13345. };
  13346. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13347. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13348. return this;
  13349. };
  13350. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13351. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13352. return this;
  13353. };
  13354. return ArcRotateCameraInputsManager;
  13355. })(BABYLON.CameraInputsManager);
  13356. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13357. })(BABYLON || (BABYLON = {}));
  13358. var BABYLON;
  13359. (function (BABYLON) {
  13360. var RenderingManager = (function () {
  13361. function RenderingManager(scene) {
  13362. this._renderingGroups = new Array();
  13363. this._scene = scene;
  13364. }
  13365. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13366. if (this._scene._activeParticleSystems.length === 0) {
  13367. return;
  13368. }
  13369. // Particles
  13370. var activeCamera = this._scene.activeCamera;
  13371. var beforeParticlesDate = BABYLON.Tools.Now;
  13372. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13373. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13374. if (particleSystem.renderingGroupId !== index) {
  13375. continue;
  13376. }
  13377. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13378. continue;
  13379. }
  13380. this._clearDepthBuffer();
  13381. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13382. this._scene._activeParticles += particleSystem.render();
  13383. }
  13384. }
  13385. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13386. };
  13387. RenderingManager.prototype._renderSprites = function (index) {
  13388. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13389. return;
  13390. }
  13391. // Sprites
  13392. var activeCamera = this._scene.activeCamera;
  13393. var beforeSpritessDate = BABYLON.Tools.Now;
  13394. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13395. var spriteManager = this._scene.spriteManagers[id];
  13396. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13397. this._clearDepthBuffer();
  13398. spriteManager.render();
  13399. }
  13400. }
  13401. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13402. };
  13403. RenderingManager.prototype._clearDepthBuffer = function () {
  13404. if (this._depthBufferAlreadyCleaned) {
  13405. return;
  13406. }
  13407. this._scene.getEngine().clear(0, false, true);
  13408. this._depthBufferAlreadyCleaned = true;
  13409. };
  13410. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13411. if (this._currentRenderSprites) {
  13412. this._renderSprites(this._currentIndex);
  13413. }
  13414. if (this._currentRenderParticles) {
  13415. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13416. }
  13417. };
  13418. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13419. this._currentActiveMeshes = activeMeshes;
  13420. this._currentRenderParticles = renderParticles;
  13421. this._currentRenderSprites = renderSprites;
  13422. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13423. this._depthBufferAlreadyCleaned = index == 0;
  13424. var renderingGroup = this._renderingGroups[index];
  13425. var needToStepBack = false;
  13426. this._currentIndex = index;
  13427. if (renderingGroup) {
  13428. this._clearDepthBuffer();
  13429. if (!renderingGroup.onBeforeTransparentRendering) {
  13430. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13431. }
  13432. if (!renderingGroup.render(customRenderFunction)) {
  13433. this._renderingGroups.splice(index, 1);
  13434. needToStepBack = true;
  13435. this._renderSpritesAndParticles();
  13436. }
  13437. }
  13438. else {
  13439. this._renderSpritesAndParticles();
  13440. }
  13441. if (needToStepBack) {
  13442. index--;
  13443. }
  13444. }
  13445. };
  13446. RenderingManager.prototype.reset = function () {
  13447. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13448. if (renderingGroup) {
  13449. renderingGroup.prepare();
  13450. }
  13451. });
  13452. };
  13453. RenderingManager.prototype.dispatch = function (subMesh) {
  13454. var mesh = subMesh.getMesh();
  13455. var renderingGroupId = mesh.renderingGroupId || 0;
  13456. if (!this._renderingGroups[renderingGroupId]) {
  13457. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13458. }
  13459. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13460. };
  13461. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13462. return RenderingManager;
  13463. })();
  13464. BABYLON.RenderingManager = RenderingManager;
  13465. })(BABYLON || (BABYLON = {}));
  13466. var BABYLON;
  13467. (function (BABYLON) {
  13468. var RenderingGroup = (function () {
  13469. function RenderingGroup(index, scene) {
  13470. this.index = index;
  13471. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13472. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13473. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13474. this._scene = scene;
  13475. }
  13476. RenderingGroup.prototype.render = function (customRenderFunction) {
  13477. if (customRenderFunction) {
  13478. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13479. return true;
  13480. }
  13481. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13482. if (this.onBeforeTransparentRendering) {
  13483. this.onBeforeTransparentRendering();
  13484. }
  13485. return false;
  13486. }
  13487. var engine = this._scene.getEngine();
  13488. // Opaque
  13489. var subIndex;
  13490. var submesh;
  13491. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13492. submesh = this._opaqueSubMeshes.data[subIndex];
  13493. submesh.render(false);
  13494. }
  13495. // Alpha test
  13496. engine.setAlphaTesting(true);
  13497. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13498. submesh = this._alphaTestSubMeshes.data[subIndex];
  13499. submesh.render(false);
  13500. }
  13501. engine.setAlphaTesting(false);
  13502. if (this.onBeforeTransparentRendering) {
  13503. this.onBeforeTransparentRendering();
  13504. }
  13505. // Transparent
  13506. if (this._transparentSubMeshes.length) {
  13507. // Sorting
  13508. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13509. submesh = this._transparentSubMeshes.data[subIndex];
  13510. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13511. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13512. }
  13513. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13514. sortedArray.sort(function (a, b) {
  13515. // Alpha index first
  13516. if (a._alphaIndex > b._alphaIndex) {
  13517. return 1;
  13518. }
  13519. if (a._alphaIndex < b._alphaIndex) {
  13520. return -1;
  13521. }
  13522. // Then distance to camera
  13523. if (a._distanceToCamera < b._distanceToCamera) {
  13524. return 1;
  13525. }
  13526. if (a._distanceToCamera > b._distanceToCamera) {
  13527. return -1;
  13528. }
  13529. return 0;
  13530. });
  13531. // Rendering
  13532. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13533. submesh = sortedArray[subIndex];
  13534. submesh.render(true);
  13535. }
  13536. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13537. }
  13538. return true;
  13539. };
  13540. RenderingGroup.prototype.prepare = function () {
  13541. this._opaqueSubMeshes.reset();
  13542. this._transparentSubMeshes.reset();
  13543. this._alphaTestSubMeshes.reset();
  13544. };
  13545. RenderingGroup.prototype.dispatch = function (subMesh) {
  13546. var material = subMesh.getMaterial();
  13547. var mesh = subMesh.getMesh();
  13548. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13549. this._transparentSubMeshes.push(subMesh);
  13550. }
  13551. else if (material.needAlphaTesting()) {
  13552. this._alphaTestSubMeshes.push(subMesh);
  13553. }
  13554. else {
  13555. this._opaqueSubMeshes.push(subMesh); // Opaque
  13556. }
  13557. };
  13558. return RenderingGroup;
  13559. })();
  13560. BABYLON.RenderingGroup = RenderingGroup;
  13561. })(BABYLON || (BABYLON = {}));
  13562. var BABYLON;
  13563. (function (BABYLON) {
  13564. /**
  13565. * Represents a scene to be rendered by the engine.
  13566. * @see http://doc.babylonjs.com/page.php?p=21911
  13567. */
  13568. var Scene = (function () {
  13569. /**
  13570. * @constructor
  13571. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  13572. */
  13573. function Scene(engine) {
  13574. // Members
  13575. this.autoClear = true;
  13576. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13577. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13578. this.forceWireframe = false;
  13579. this.forcePointsCloud = false;
  13580. this.forceShowBoundingBoxes = false;
  13581. this.animationsEnabled = true;
  13582. this.constantlyUpdateMeshUnderPointer = false;
  13583. // Animations
  13584. this.animations = [];
  13585. 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
  13586. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  13587. this._startingPointerTime = 0;
  13588. // Fog
  13589. /**
  13590. * is fog enabled on this scene.
  13591. * @type {boolean}
  13592. */
  13593. this.fogEnabled = true;
  13594. this.fogMode = Scene.FOGMODE_NONE;
  13595. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13596. this.fogDensity = 0.1;
  13597. this.fogStart = 0;
  13598. this.fogEnd = 1000.0;
  13599. // Lights
  13600. /**
  13601. * is shadow enabled on this scene.
  13602. * @type {boolean}
  13603. */
  13604. this.shadowsEnabled = true;
  13605. /**
  13606. * is light enabled on this scene.
  13607. * @type {boolean}
  13608. */
  13609. this.lightsEnabled = true;
  13610. /**
  13611. * All of the lights added to this scene.
  13612. * @see BABYLON.Light
  13613. * @type {BABYLON.Light[]}
  13614. */
  13615. this.lights = new Array();
  13616. // Cameras
  13617. /**
  13618. * All of the cameras added to this scene.
  13619. * @see BABYLON.Camera
  13620. * @type {BABYLON.Camera[]}
  13621. */
  13622. this.cameras = new Array();
  13623. this.activeCameras = new Array();
  13624. // Meshes
  13625. /**
  13626. * All of the (abstract) meshes added to this scene.
  13627. * @see BABYLON.AbstractMesh
  13628. * @type {BABYLON.AbstractMesh[]}
  13629. */
  13630. this.meshes = new Array();
  13631. // Geometries
  13632. this._geometries = new Array();
  13633. this.materials = new Array();
  13634. this.multiMaterials = new Array();
  13635. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  13636. // Textures
  13637. this.texturesEnabled = true;
  13638. this.textures = new Array();
  13639. // Particles
  13640. this.particlesEnabled = true;
  13641. this.particleSystems = new Array();
  13642. // Sprites
  13643. this.spritesEnabled = true;
  13644. this.spriteManagers = new Array();
  13645. // Layers
  13646. this.layers = new Array();
  13647. // Skeletons
  13648. this.skeletonsEnabled = true;
  13649. this.skeletons = new Array();
  13650. // Lens flares
  13651. this.lensFlaresEnabled = true;
  13652. this.lensFlareSystems = new Array();
  13653. // Collisions
  13654. this.collisionsEnabled = true;
  13655. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  13656. // Postprocesses
  13657. this.postProcessesEnabled = true;
  13658. // Customs render targets
  13659. this.renderTargetsEnabled = true;
  13660. this.dumpNextRenderTargets = false;
  13661. this.customRenderTargets = new Array();
  13662. // Imported meshes
  13663. this.importedMeshesFiles = new Array();
  13664. // Probes
  13665. this.probesEnabled = true;
  13666. this.reflectionProbes = new Array();
  13667. this._actionManagers = new Array();
  13668. this._meshesForIntersections = new BABYLON.SmartArray(256);
  13669. // Procedural textures
  13670. this.proceduralTexturesEnabled = true;
  13671. this._proceduralTextures = new Array();
  13672. this.soundTracks = new Array();
  13673. this._audioEnabled = true;
  13674. this._headphone = false;
  13675. this._totalVertices = 0;
  13676. this._activeIndices = 0;
  13677. this._activeParticles = 0;
  13678. this._lastFrameDuration = 0;
  13679. this._evaluateActiveMeshesDuration = 0;
  13680. this._renderTargetsDuration = 0;
  13681. this._particlesDuration = 0;
  13682. this._renderDuration = 0;
  13683. this._spritesDuration = 0;
  13684. this._animationRatio = 0;
  13685. this._renderId = 0;
  13686. this._executeWhenReadyTimeoutId = -1;
  13687. this._toBeDisposed = new BABYLON.SmartArray(256);
  13688. this._onReadyCallbacks = new Array();
  13689. this._pendingData = []; //ANY
  13690. this._onBeforeRenderCallbacks = new Array();
  13691. this._onAfterRenderCallbacks = new Array();
  13692. this._activeMeshes = new BABYLON.SmartArray(256);
  13693. this._processedMaterials = new BABYLON.SmartArray(256);
  13694. this._renderTargets = new BABYLON.SmartArray(256);
  13695. this._activeParticleSystems = new BABYLON.SmartArray(256);
  13696. this._activeSkeletons = new BABYLON.SmartArray(32);
  13697. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  13698. this._activeBones = 0;
  13699. this._activeAnimatables = new Array();
  13700. this._transformMatrix = BABYLON.Matrix.Zero();
  13701. this._edgesRenderers = new BABYLON.SmartArray(16);
  13702. this._uniqueIdCounter = 0;
  13703. this._engine = engine;
  13704. engine.scenes.push(this);
  13705. this._renderingManager = new BABYLON.RenderingManager(this);
  13706. this.postProcessManager = new BABYLON.PostProcessManager(this);
  13707. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  13708. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  13709. if (BABYLON.OutlineRenderer) {
  13710. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  13711. }
  13712. this.attachControl();
  13713. this._debugLayer = new BABYLON.DebugLayer(this);
  13714. if (BABYLON.SoundTrack) {
  13715. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  13716. }
  13717. //simplification queue
  13718. if (BABYLON.SimplificationQueue) {
  13719. this.simplificationQueue = new BABYLON.SimplificationQueue();
  13720. }
  13721. //collision coordinator initialization. For now legacy per default.
  13722. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  13723. }
  13724. Object.defineProperty(Scene, "FOGMODE_NONE", {
  13725. get: function () {
  13726. return Scene._FOGMODE_NONE;
  13727. },
  13728. enumerable: true,
  13729. configurable: true
  13730. });
  13731. Object.defineProperty(Scene, "FOGMODE_EXP", {
  13732. get: function () {
  13733. return Scene._FOGMODE_EXP;
  13734. },
  13735. enumerable: true,
  13736. configurable: true
  13737. });
  13738. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  13739. get: function () {
  13740. return Scene._FOGMODE_EXP2;
  13741. },
  13742. enumerable: true,
  13743. configurable: true
  13744. });
  13745. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  13746. get: function () {
  13747. return Scene._FOGMODE_LINEAR;
  13748. },
  13749. enumerable: true,
  13750. configurable: true
  13751. });
  13752. Object.defineProperty(Scene.prototype, "debugLayer", {
  13753. // Properties
  13754. get: function () {
  13755. return this._debugLayer;
  13756. },
  13757. enumerable: true,
  13758. configurable: true
  13759. });
  13760. Object.defineProperty(Scene.prototype, "workerCollisions", {
  13761. get: function () {
  13762. return this._workerCollisions;
  13763. },
  13764. set: function (enabled) {
  13765. enabled = (enabled && !!Worker);
  13766. this._workerCollisions = enabled;
  13767. if (this.collisionCoordinator) {
  13768. this.collisionCoordinator.destroy();
  13769. }
  13770. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  13771. this.collisionCoordinator.init(this);
  13772. },
  13773. enumerable: true,
  13774. configurable: true
  13775. });
  13776. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  13777. get: function () {
  13778. return this._selectionOctree;
  13779. },
  13780. enumerable: true,
  13781. configurable: true
  13782. });
  13783. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  13784. /**
  13785. * The mesh that is currently under the pointer.
  13786. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  13787. */
  13788. get: function () {
  13789. return this._pointerOverMesh;
  13790. },
  13791. enumerable: true,
  13792. configurable: true
  13793. });
  13794. Object.defineProperty(Scene.prototype, "pointerX", {
  13795. /**
  13796. * Current on-screen X position of the pointer
  13797. * @return {number} X position of the pointer
  13798. */
  13799. get: function () {
  13800. return this._pointerX;
  13801. },
  13802. enumerable: true,
  13803. configurable: true
  13804. });
  13805. Object.defineProperty(Scene.prototype, "pointerY", {
  13806. /**
  13807. * Current on-screen Y position of the pointer
  13808. * @return {number} Y position of the pointer
  13809. */
  13810. get: function () {
  13811. return this._pointerY;
  13812. },
  13813. enumerable: true,
  13814. configurable: true
  13815. });
  13816. Scene.prototype.getCachedMaterial = function () {
  13817. return this._cachedMaterial;
  13818. };
  13819. Scene.prototype.getBoundingBoxRenderer = function () {
  13820. return this._boundingBoxRenderer;
  13821. };
  13822. Scene.prototype.getOutlineRenderer = function () {
  13823. return this._outlineRenderer;
  13824. };
  13825. Scene.prototype.getEngine = function () {
  13826. return this._engine;
  13827. };
  13828. Scene.prototype.getTotalVertices = function () {
  13829. return this._totalVertices;
  13830. };
  13831. Scene.prototype.getActiveIndices = function () {
  13832. return this._activeIndices;
  13833. };
  13834. Scene.prototype.getActiveParticles = function () {
  13835. return this._activeParticles;
  13836. };
  13837. Scene.prototype.getActiveBones = function () {
  13838. return this._activeBones;
  13839. };
  13840. // Stats
  13841. Scene.prototype.getLastFrameDuration = function () {
  13842. return this._lastFrameDuration;
  13843. };
  13844. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  13845. return this._evaluateActiveMeshesDuration;
  13846. };
  13847. Scene.prototype.getActiveMeshes = function () {
  13848. return this._activeMeshes;
  13849. };
  13850. Scene.prototype.getRenderTargetsDuration = function () {
  13851. return this._renderTargetsDuration;
  13852. };
  13853. Scene.prototype.getRenderDuration = function () {
  13854. return this._renderDuration;
  13855. };
  13856. Scene.prototype.getParticlesDuration = function () {
  13857. return this._particlesDuration;
  13858. };
  13859. Scene.prototype.getSpritesDuration = function () {
  13860. return this._spritesDuration;
  13861. };
  13862. Scene.prototype.getAnimationRatio = function () {
  13863. return this._animationRatio;
  13864. };
  13865. Scene.prototype.getRenderId = function () {
  13866. return this._renderId;
  13867. };
  13868. Scene.prototype.incrementRenderId = function () {
  13869. this._renderId++;
  13870. };
  13871. Scene.prototype._updatePointerPosition = function (evt) {
  13872. var canvasRect = this._engine.getRenderingCanvasClientRect();
  13873. this._pointerX = evt.clientX - canvasRect.left;
  13874. this._pointerY = evt.clientY - canvasRect.top;
  13875. this._unTranslatedPointerX = this._pointerX;
  13876. this._unTranslatedPointerY = this._pointerY;
  13877. if (this.cameraToUseForPointers) {
  13878. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  13879. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  13880. }
  13881. };
  13882. // Pointers handling
  13883. Scene.prototype.attachControl = function () {
  13884. var _this = this;
  13885. var spritePredicate = function (sprite) {
  13886. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  13887. };
  13888. this._onPointerMove = function (evt) {
  13889. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13890. return;
  13891. }
  13892. var canvas = _this._engine.getRenderingCanvas();
  13893. _this._updatePointerPosition(evt);
  13894. if (!_this.pointerMovePredicate) {
  13895. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  13896. }
  13897. // Meshes
  13898. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  13899. if (pickResult.hit && pickResult.pickedMesh) {
  13900. _this.setPointerOverSprite(null);
  13901. _this.setPointerOverMesh(pickResult.pickedMesh);
  13902. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  13903. canvas.style.cursor = "pointer";
  13904. }
  13905. else {
  13906. canvas.style.cursor = "";
  13907. }
  13908. }
  13909. else {
  13910. _this.setPointerOverMesh(null);
  13911. // Sprites
  13912. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13913. if (pickResult.hit && pickResult.pickedSprite) {
  13914. canvas.style.cursor = "pointer";
  13915. _this.setPointerOverSprite(pickResult.pickedSprite);
  13916. }
  13917. else {
  13918. _this.setPointerOverSprite(null);
  13919. // Restore pointer
  13920. canvas.style.cursor = "";
  13921. }
  13922. }
  13923. if (_this.onPointerMove) {
  13924. _this.onPointerMove(evt, pickResult);
  13925. }
  13926. };
  13927. this._onPointerDown = function (evt) {
  13928. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13929. return;
  13930. }
  13931. _this._updatePointerPosition(evt);
  13932. _this._startingPointerPosition.x = _this._pointerX;
  13933. _this._startingPointerPosition.y = _this._pointerY;
  13934. _this._startingPointerTime = new Date().getTime();
  13935. if (!_this.pointerDownPredicate) {
  13936. _this.pointerDownPredicate = function (mesh) {
  13937. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  13938. };
  13939. }
  13940. // Meshes
  13941. _this._pickedDownMesh = null;
  13942. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  13943. if (pickResult.hit && pickResult.pickedMesh) {
  13944. if (pickResult.pickedMesh.actionManager) {
  13945. _this._pickedDownMesh = pickResult.pickedMesh;
  13946. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  13947. switch (evt.button) {
  13948. case 0:
  13949. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13950. break;
  13951. case 1:
  13952. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13953. break;
  13954. case 2:
  13955. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13956. break;
  13957. }
  13958. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13959. }
  13960. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  13961. var that = _this;
  13962. window.setTimeout(function () {
  13963. 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);
  13964. if (pickResult.hit && pickResult.pickedMesh) {
  13965. if (pickResult.pickedMesh.actionManager) {
  13966. 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)) {
  13967. that._startingPointerTime = 0;
  13968. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13969. }
  13970. }
  13971. }
  13972. }, BABYLON.ActionManager.LongPressDelay);
  13973. }
  13974. }
  13975. }
  13976. if (_this.onPointerDown) {
  13977. _this.onPointerDown(evt, pickResult);
  13978. }
  13979. // Sprites
  13980. _this._pickedDownSprite = null;
  13981. if (_this.spriteManagers.length > 0) {
  13982. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13983. if (pickResult.hit && pickResult.pickedSprite) {
  13984. if (pickResult.pickedSprite.actionManager) {
  13985. _this._pickedDownSprite = pickResult.pickedSprite;
  13986. switch (evt.button) {
  13987. case 0:
  13988. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13989. break;
  13990. case 1:
  13991. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13992. break;
  13993. case 2:
  13994. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13995. break;
  13996. }
  13997. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13998. }
  13999. }
  14000. }
  14001. };
  14002. this._onPointerUp = function (evt) {
  14003. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14004. return;
  14005. }
  14006. _this._updatePointerPosition(evt);
  14007. if (!_this.pointerUpPredicate) {
  14008. _this.pointerUpPredicate = function (mesh) {
  14009. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14010. };
  14011. }
  14012. // Meshes
  14013. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14014. if (pickResult.hit && pickResult.pickedMesh) {
  14015. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14016. _this.onPointerPick(evt, pickResult);
  14017. }
  14018. if (pickResult.pickedMesh.actionManager) {
  14019. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14020. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14021. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14022. }
  14023. }
  14024. }
  14025. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14026. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14027. }
  14028. if (_this.onPointerUp) {
  14029. _this.onPointerUp(evt, pickResult);
  14030. }
  14031. _this._startingPointerTime = 0;
  14032. // Sprites
  14033. if (_this.spriteManagers.length > 0) {
  14034. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14035. if (pickResult.hit && pickResult.pickedSprite) {
  14036. if (pickResult.pickedSprite.actionManager) {
  14037. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14038. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14039. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14040. }
  14041. }
  14042. }
  14043. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14044. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14045. }
  14046. }
  14047. };
  14048. this._onKeyDown = function (evt) {
  14049. if (_this.actionManager) {
  14050. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14051. }
  14052. };
  14053. this._onKeyUp = function (evt) {
  14054. if (_this.actionManager) {
  14055. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14056. }
  14057. };
  14058. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14059. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14060. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14061. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14062. // Wheel
  14063. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14064. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14065. BABYLON.Tools.RegisterTopRootEvents([
  14066. { name: "keydown", handler: this._onKeyDown },
  14067. { name: "keyup", handler: this._onKeyUp }
  14068. ]);
  14069. };
  14070. Scene.prototype.detachControl = function () {
  14071. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14072. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14073. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14074. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14075. // Wheel
  14076. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14077. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14078. BABYLON.Tools.UnregisterTopRootEvents([
  14079. { name: "keydown", handler: this._onKeyDown },
  14080. { name: "keyup", handler: this._onKeyUp }
  14081. ]);
  14082. };
  14083. // Ready
  14084. Scene.prototype.isReady = function () {
  14085. if (this._pendingData.length > 0) {
  14086. return false;
  14087. }
  14088. var index;
  14089. for (index = 0; index < this._geometries.length; index++) {
  14090. var geometry = this._geometries[index];
  14091. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14092. return false;
  14093. }
  14094. }
  14095. for (index = 0; index < this.meshes.length; index++) {
  14096. var mesh = this.meshes[index];
  14097. if (!mesh.isReady()) {
  14098. return false;
  14099. }
  14100. var mat = mesh.material;
  14101. if (mat) {
  14102. if (!mat.isReady(mesh)) {
  14103. return false;
  14104. }
  14105. }
  14106. }
  14107. return true;
  14108. };
  14109. Scene.prototype.resetCachedMaterial = function () {
  14110. this._cachedMaterial = null;
  14111. };
  14112. Scene.prototype.registerBeforeRender = function (func) {
  14113. this._onBeforeRenderCallbacks.push(func);
  14114. };
  14115. Scene.prototype.unregisterBeforeRender = function (func) {
  14116. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14117. if (index > -1) {
  14118. this._onBeforeRenderCallbacks.splice(index, 1);
  14119. }
  14120. };
  14121. Scene.prototype.registerAfterRender = function (func) {
  14122. this._onAfterRenderCallbacks.push(func);
  14123. };
  14124. Scene.prototype.unregisterAfterRender = function (func) {
  14125. var index = this._onAfterRenderCallbacks.indexOf(func);
  14126. if (index > -1) {
  14127. this._onAfterRenderCallbacks.splice(index, 1);
  14128. }
  14129. };
  14130. Scene.prototype._addPendingData = function (data) {
  14131. this._pendingData.push(data);
  14132. };
  14133. Scene.prototype._removePendingData = function (data) {
  14134. var index = this._pendingData.indexOf(data);
  14135. if (index !== -1) {
  14136. this._pendingData.splice(index, 1);
  14137. }
  14138. };
  14139. Scene.prototype.getWaitingItemsCount = function () {
  14140. return this._pendingData.length;
  14141. };
  14142. /**
  14143. * Registers a function to be executed when the scene is ready.
  14144. * @param {Function} func - the function to be executed.
  14145. */
  14146. Scene.prototype.executeWhenReady = function (func) {
  14147. var _this = this;
  14148. this._onReadyCallbacks.push(func);
  14149. if (this._executeWhenReadyTimeoutId !== -1) {
  14150. return;
  14151. }
  14152. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14153. _this._checkIsReady();
  14154. }, 150);
  14155. };
  14156. Scene.prototype._checkIsReady = function () {
  14157. var _this = this;
  14158. if (this.isReady()) {
  14159. this._onReadyCallbacks.forEach(function (func) {
  14160. func();
  14161. });
  14162. this._onReadyCallbacks = [];
  14163. this._executeWhenReadyTimeoutId = -1;
  14164. return;
  14165. }
  14166. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14167. _this._checkIsReady();
  14168. }, 150);
  14169. };
  14170. // Animations
  14171. /**
  14172. * Will start the animation sequence of a given target
  14173. * @param target - the target
  14174. * @param {number} from - from which frame should animation start
  14175. * @param {number} to - till which frame should animation run.
  14176. * @param {boolean} [loop] - should the animation loop
  14177. * @param {number} [speedRatio] - the speed in which to run the animation
  14178. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14179. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14180. * @return {BABYLON.Animatable} the animatable object created for this animation
  14181. * @see BABYLON.Animatable
  14182. * @see http://doc.babylonjs.com/page.php?p=22081
  14183. */
  14184. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14185. if (speedRatio === void 0) { speedRatio = 1.0; }
  14186. this.stopAnimation(target);
  14187. if (!animatable) {
  14188. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14189. }
  14190. // Local animations
  14191. if (target.animations) {
  14192. animatable.appendAnimations(target, target.animations);
  14193. }
  14194. // Children animations
  14195. if (target.getAnimatables) {
  14196. var animatables = target.getAnimatables();
  14197. for (var index = 0; index < animatables.length; index++) {
  14198. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14199. }
  14200. }
  14201. animatable.reset();
  14202. return animatable;
  14203. };
  14204. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14205. if (speedRatio === undefined) {
  14206. speedRatio = 1.0;
  14207. }
  14208. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14209. return animatable;
  14210. };
  14211. Scene.prototype.getAnimatableByTarget = function (target) {
  14212. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14213. if (this._activeAnimatables[index].target === target) {
  14214. return this._activeAnimatables[index];
  14215. }
  14216. }
  14217. return null;
  14218. };
  14219. Object.defineProperty(Scene.prototype, "Animatables", {
  14220. get: function () {
  14221. return this._activeAnimatables;
  14222. },
  14223. enumerable: true,
  14224. configurable: true
  14225. });
  14226. /**
  14227. * Will stop the animation of the given target
  14228. * @param target - the target
  14229. * @see beginAnimation
  14230. */
  14231. Scene.prototype.stopAnimation = function (target) {
  14232. var animatable = this.getAnimatableByTarget(target);
  14233. if (animatable) {
  14234. animatable.stop();
  14235. }
  14236. };
  14237. Scene.prototype._animate = function () {
  14238. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14239. return;
  14240. }
  14241. if (!this._animationStartDate) {
  14242. if (this._pendingData.length > 0) {
  14243. return;
  14244. }
  14245. this._animationStartDate = BABYLON.Tools.Now;
  14246. }
  14247. // Getting time
  14248. var now = BABYLON.Tools.Now;
  14249. var delay = now - this._animationStartDate;
  14250. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14251. this._activeAnimatables[index]._animate(delay);
  14252. }
  14253. };
  14254. // Matrix
  14255. Scene.prototype.getViewMatrix = function () {
  14256. return this._viewMatrix;
  14257. };
  14258. Scene.prototype.getProjectionMatrix = function () {
  14259. return this._projectionMatrix;
  14260. };
  14261. Scene.prototype.getTransformMatrix = function () {
  14262. return this._transformMatrix;
  14263. };
  14264. Scene.prototype.setTransformMatrix = function (view, projection) {
  14265. this._viewMatrix = view;
  14266. this._projectionMatrix = projection;
  14267. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14268. };
  14269. // Methods
  14270. Scene.prototype.addMesh = function (newMesh) {
  14271. newMesh.uniqueId = this._uniqueIdCounter++;
  14272. var position = this.meshes.push(newMesh);
  14273. //notify the collision coordinator
  14274. this.collisionCoordinator.onMeshAdded(newMesh);
  14275. if (this.onNewMeshAdded) {
  14276. this.onNewMeshAdded(newMesh, position, this);
  14277. }
  14278. };
  14279. Scene.prototype.removeMesh = function (toRemove) {
  14280. var index = this.meshes.indexOf(toRemove);
  14281. if (index !== -1) {
  14282. // Remove from the scene if mesh found
  14283. this.meshes.splice(index, 1);
  14284. }
  14285. //notify the collision coordinator
  14286. this.collisionCoordinator.onMeshRemoved(toRemove);
  14287. if (this.onMeshRemoved) {
  14288. this.onMeshRemoved(toRemove);
  14289. }
  14290. return index;
  14291. };
  14292. Scene.prototype.removeSkeleton = function (toRemove) {
  14293. var index = this.skeletons.indexOf(toRemove);
  14294. if (index !== -1) {
  14295. // Remove from the scene if mesh found
  14296. this.skeletons.splice(index, 1);
  14297. }
  14298. return index;
  14299. };
  14300. Scene.prototype.removeLight = function (toRemove) {
  14301. var index = this.lights.indexOf(toRemove);
  14302. if (index !== -1) {
  14303. // Remove from the scene if mesh found
  14304. this.lights.splice(index, 1);
  14305. }
  14306. if (this.onLightRemoved) {
  14307. this.onLightRemoved(toRemove);
  14308. }
  14309. return index;
  14310. };
  14311. Scene.prototype.removeCamera = function (toRemove) {
  14312. var index = this.cameras.indexOf(toRemove);
  14313. if (index !== -1) {
  14314. // Remove from the scene if mesh found
  14315. this.cameras.splice(index, 1);
  14316. }
  14317. // Remove from activeCameras
  14318. var index2 = this.activeCameras.indexOf(toRemove);
  14319. if (index2 !== -1) {
  14320. // Remove from the scene if mesh found
  14321. this.activeCameras.splice(index2, 1);
  14322. }
  14323. // Reset the activeCamera
  14324. if (this.activeCamera === toRemove) {
  14325. if (this.cameras.length > 0) {
  14326. this.activeCamera = this.cameras[0];
  14327. }
  14328. else {
  14329. this.activeCamera = null;
  14330. }
  14331. }
  14332. if (this.onCameraRemoved) {
  14333. this.onCameraRemoved(toRemove);
  14334. }
  14335. return index;
  14336. };
  14337. Scene.prototype.addLight = function (newLight) {
  14338. newLight.uniqueId = this._uniqueIdCounter++;
  14339. var position = this.lights.push(newLight);
  14340. if (this.onNewLightAdded) {
  14341. this.onNewLightAdded(newLight, position, this);
  14342. }
  14343. };
  14344. Scene.prototype.addCamera = function (newCamera) {
  14345. newCamera.uniqueId = this._uniqueIdCounter++;
  14346. var position = this.cameras.push(newCamera);
  14347. if (this.onNewCameraAdded) {
  14348. this.onNewCameraAdded(newCamera, position, this);
  14349. }
  14350. };
  14351. /**
  14352. * Switch active camera
  14353. * @param {Camera} newCamera - new active camera
  14354. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14355. */
  14356. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14357. if (attachControl === void 0) { attachControl = true; }
  14358. var canvas = this._engine.getRenderingCanvas();
  14359. this.activeCamera.detachControl(canvas);
  14360. this.activeCamera = newCamera;
  14361. if (attachControl) {
  14362. newCamera.attachControl(canvas);
  14363. }
  14364. };
  14365. /**
  14366. * sets the active camera of the scene using its ID
  14367. * @param {string} id - the camera's ID
  14368. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14369. * @see activeCamera
  14370. */
  14371. Scene.prototype.setActiveCameraByID = function (id) {
  14372. var camera = this.getCameraByID(id);
  14373. if (camera) {
  14374. this.activeCamera = camera;
  14375. return camera;
  14376. }
  14377. return null;
  14378. };
  14379. /**
  14380. * sets the active camera of the scene using its name
  14381. * @param {string} name - the camera's name
  14382. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14383. * @see activeCamera
  14384. */
  14385. Scene.prototype.setActiveCameraByName = function (name) {
  14386. var camera = this.getCameraByName(name);
  14387. if (camera) {
  14388. this.activeCamera = camera;
  14389. return camera;
  14390. }
  14391. return null;
  14392. };
  14393. /**
  14394. * get a material using its id
  14395. * @param {string} the material's ID
  14396. * @return {BABYLON.Material|null} the material or null if none found.
  14397. */
  14398. Scene.prototype.getMaterialByID = function (id) {
  14399. for (var index = 0; index < this.materials.length; index++) {
  14400. if (this.materials[index].id === id) {
  14401. return this.materials[index];
  14402. }
  14403. }
  14404. return null;
  14405. };
  14406. /**
  14407. * get a material using its name
  14408. * @param {string} the material's name
  14409. * @return {BABYLON.Material|null} the material or null if none found.
  14410. */
  14411. Scene.prototype.getMaterialByName = function (name) {
  14412. for (var index = 0; index < this.materials.length; index++) {
  14413. if (this.materials[index].name === name) {
  14414. return this.materials[index];
  14415. }
  14416. }
  14417. return null;
  14418. };
  14419. Scene.prototype.getLensFlareSystemByName = function (name) {
  14420. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  14421. if (this.lensFlareSystems[index].name === name) {
  14422. return this.lensFlareSystems[index];
  14423. }
  14424. }
  14425. return null;
  14426. };
  14427. Scene.prototype.getCameraByID = function (id) {
  14428. for (var index = 0; index < this.cameras.length; index++) {
  14429. if (this.cameras[index].id === id) {
  14430. return this.cameras[index];
  14431. }
  14432. }
  14433. return null;
  14434. };
  14435. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  14436. for (var index = 0; index < this.cameras.length; index++) {
  14437. if (this.cameras[index].uniqueId === uniqueId) {
  14438. return this.cameras[index];
  14439. }
  14440. }
  14441. return null;
  14442. };
  14443. /**
  14444. * get a camera using its name
  14445. * @param {string} the camera's name
  14446. * @return {BABYLON.Camera|null} the camera or null if none found.
  14447. */
  14448. Scene.prototype.getCameraByName = function (name) {
  14449. for (var index = 0; index < this.cameras.length; index++) {
  14450. if (this.cameras[index].name === name) {
  14451. return this.cameras[index];
  14452. }
  14453. }
  14454. return null;
  14455. };
  14456. /**
  14457. * get a bone using its id
  14458. * @param {string} the bone's id
  14459. * @return {BABYLON.Bone|null} the bone or null if not found
  14460. */
  14461. Scene.prototype.getBoneByID = function (id) {
  14462. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14463. var skeleton = this.skeletons[skeletonIndex];
  14464. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14465. if (skeleton.bones[boneIndex].id === id) {
  14466. return skeleton.bones[boneIndex];
  14467. }
  14468. }
  14469. }
  14470. return null;
  14471. };
  14472. /**
  14473. * get a bone using its id
  14474. * @param {string} the bone's name
  14475. * @return {BABYLON.Bone|null} the bone or null if not found
  14476. */
  14477. Scene.prototype.getBoneByName = function (name) {
  14478. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14479. var skeleton = this.skeletons[skeletonIndex];
  14480. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14481. if (skeleton.bones[boneIndex].name === name) {
  14482. return skeleton.bones[boneIndex];
  14483. }
  14484. }
  14485. }
  14486. return null;
  14487. };
  14488. /**
  14489. * get a light node using its name
  14490. * @param {string} the light's name
  14491. * @return {BABYLON.Light|null} the light or null if none found.
  14492. */
  14493. Scene.prototype.getLightByName = function (name) {
  14494. for (var index = 0; index < this.lights.length; index++) {
  14495. if (this.lights[index].name === name) {
  14496. return this.lights[index];
  14497. }
  14498. }
  14499. return null;
  14500. };
  14501. /**
  14502. * get a light node using its ID
  14503. * @param {string} the light's id
  14504. * @return {BABYLON.Light|null} the light or null if none found.
  14505. */
  14506. Scene.prototype.getLightByID = function (id) {
  14507. for (var index = 0; index < this.lights.length; index++) {
  14508. if (this.lights[index].id === id) {
  14509. return this.lights[index];
  14510. }
  14511. }
  14512. return null;
  14513. };
  14514. /**
  14515. * get a light node using its scene-generated unique ID
  14516. * @param {number} the light's unique id
  14517. * @return {BABYLON.Light|null} the light or null if none found.
  14518. */
  14519. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  14520. for (var index = 0; index < this.lights.length; index++) {
  14521. if (this.lights[index].uniqueId === uniqueId) {
  14522. return this.lights[index];
  14523. }
  14524. }
  14525. return null;
  14526. };
  14527. /**
  14528. * get a particle system by id
  14529. * @param id {number} the particle system id
  14530. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  14531. */
  14532. Scene.prototype.getParticleSystemByID = function (id) {
  14533. for (var index = 0; index < this.particleSystems.length; index++) {
  14534. if (this.particleSystems[index].id === id) {
  14535. return this.particleSystems[index];
  14536. }
  14537. }
  14538. return null;
  14539. };
  14540. /**
  14541. * get a geometry using its ID
  14542. * @param {string} the geometry's id
  14543. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  14544. */
  14545. Scene.prototype.getGeometryByID = function (id) {
  14546. for (var index = 0; index < this._geometries.length; index++) {
  14547. if (this._geometries[index].id === id) {
  14548. return this._geometries[index];
  14549. }
  14550. }
  14551. return null;
  14552. };
  14553. /**
  14554. * add a new geometry to this scene.
  14555. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  14556. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  14557. * @return {boolean} was the geometry added or not
  14558. */
  14559. Scene.prototype.pushGeometry = function (geometry, force) {
  14560. if (!force && this.getGeometryByID(geometry.id)) {
  14561. return false;
  14562. }
  14563. this._geometries.push(geometry);
  14564. //notify the collision coordinator
  14565. this.collisionCoordinator.onGeometryAdded(geometry);
  14566. if (this.onGeometryAdded) {
  14567. this.onGeometryAdded(geometry);
  14568. }
  14569. return true;
  14570. };
  14571. /**
  14572. * Removes an existing geometry
  14573. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  14574. * @return {boolean} was the geometry removed or not
  14575. */
  14576. Scene.prototype.removeGeometry = function (geometry) {
  14577. var index = this._geometries.indexOf(geometry);
  14578. if (index > -1) {
  14579. this._geometries.splice(index, 1);
  14580. //notify the collision coordinator
  14581. this.collisionCoordinator.onGeometryDeleted(geometry);
  14582. if (this.onGeometryRemoved) {
  14583. this.onGeometryRemoved(geometry);
  14584. }
  14585. return true;
  14586. }
  14587. return false;
  14588. };
  14589. Scene.prototype.getGeometries = function () {
  14590. return this._geometries;
  14591. };
  14592. /**
  14593. * Get the first added mesh found of a given ID
  14594. * @param {string} id - the id to search for
  14595. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14596. */
  14597. Scene.prototype.getMeshByID = function (id) {
  14598. for (var index = 0; index < this.meshes.length; index++) {
  14599. if (this.meshes[index].id === id) {
  14600. return this.meshes[index];
  14601. }
  14602. }
  14603. return null;
  14604. };
  14605. /**
  14606. * Get a mesh with its auto-generated unique id
  14607. * @param {number} uniqueId - the unique id to search for
  14608. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14609. */
  14610. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  14611. for (var index = 0; index < this.meshes.length; index++) {
  14612. if (this.meshes[index].uniqueId === uniqueId) {
  14613. return this.meshes[index];
  14614. }
  14615. }
  14616. return null;
  14617. };
  14618. /**
  14619. * Get a the last added mesh found of a given ID
  14620. * @param {string} id - the id to search for
  14621. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14622. */
  14623. Scene.prototype.getLastMeshByID = function (id) {
  14624. for (var index = this.meshes.length - 1; index >= 0; index--) {
  14625. if (this.meshes[index].id === id) {
  14626. return this.meshes[index];
  14627. }
  14628. }
  14629. return null;
  14630. };
  14631. /**
  14632. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  14633. * @param {string} id - the id to search for
  14634. * @return {BABYLON.Node|null} the node found or null if not found at all.
  14635. */
  14636. Scene.prototype.getLastEntryByID = function (id) {
  14637. var index;
  14638. for (index = this.meshes.length - 1; index >= 0; index--) {
  14639. if (this.meshes[index].id === id) {
  14640. return this.meshes[index];
  14641. }
  14642. }
  14643. for (index = this.cameras.length - 1; index >= 0; index--) {
  14644. if (this.cameras[index].id === id) {
  14645. return this.cameras[index];
  14646. }
  14647. }
  14648. for (index = this.lights.length - 1; index >= 0; index--) {
  14649. if (this.lights[index].id === id) {
  14650. return this.lights[index];
  14651. }
  14652. }
  14653. return null;
  14654. };
  14655. Scene.prototype.getNodeByID = function (id) {
  14656. var mesh = this.getMeshByID(id);
  14657. if (mesh) {
  14658. return mesh;
  14659. }
  14660. var light = this.getLightByID(id);
  14661. if (light) {
  14662. return light;
  14663. }
  14664. var camera = this.getCameraByID(id);
  14665. if (camera) {
  14666. return camera;
  14667. }
  14668. var bone = this.getBoneByID(id);
  14669. return bone;
  14670. };
  14671. Scene.prototype.getNodeByName = function (name) {
  14672. var mesh = this.getMeshByName(name);
  14673. if (mesh) {
  14674. return mesh;
  14675. }
  14676. var light = this.getLightByName(name);
  14677. if (light) {
  14678. return light;
  14679. }
  14680. var camera = this.getCameraByName(name);
  14681. if (camera) {
  14682. return camera;
  14683. }
  14684. var bone = this.getBoneByName(name);
  14685. return bone;
  14686. };
  14687. Scene.prototype.getMeshByName = function (name) {
  14688. for (var index = 0; index < this.meshes.length; index++) {
  14689. if (this.meshes[index].name === name) {
  14690. return this.meshes[index];
  14691. }
  14692. }
  14693. return null;
  14694. };
  14695. Scene.prototype.getSoundByName = function (name) {
  14696. var index;
  14697. if (BABYLON.AudioEngine) {
  14698. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  14699. if (this.mainSoundTrack.soundCollection[index].name === name) {
  14700. return this.mainSoundTrack.soundCollection[index];
  14701. }
  14702. }
  14703. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  14704. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  14705. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  14706. return this.soundTracks[sdIndex].soundCollection[index];
  14707. }
  14708. }
  14709. }
  14710. }
  14711. return null;
  14712. };
  14713. Scene.prototype.getLastSkeletonByID = function (id) {
  14714. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  14715. if (this.skeletons[index].id === id) {
  14716. return this.skeletons[index];
  14717. }
  14718. }
  14719. return null;
  14720. };
  14721. Scene.prototype.getSkeletonById = function (id) {
  14722. for (var index = 0; index < this.skeletons.length; index++) {
  14723. if (this.skeletons[index].id === id) {
  14724. return this.skeletons[index];
  14725. }
  14726. }
  14727. return null;
  14728. };
  14729. Scene.prototype.getSkeletonByName = function (name) {
  14730. for (var index = 0; index < this.skeletons.length; index++) {
  14731. if (this.skeletons[index].name === name) {
  14732. return this.skeletons[index];
  14733. }
  14734. }
  14735. return null;
  14736. };
  14737. Scene.prototype.isActiveMesh = function (mesh) {
  14738. return (this._activeMeshes.indexOf(mesh) !== -1);
  14739. };
  14740. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  14741. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  14742. var material = subMesh.getMaterial();
  14743. if (mesh.showSubMeshesBoundingBox) {
  14744. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  14745. }
  14746. if (material) {
  14747. // Render targets
  14748. if (material.getRenderTargetTextures) {
  14749. if (this._processedMaterials.indexOf(material) === -1) {
  14750. this._processedMaterials.push(material);
  14751. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  14752. }
  14753. }
  14754. // Dispatch
  14755. this._activeIndices += subMesh.indexCount;
  14756. this._renderingManager.dispatch(subMesh);
  14757. }
  14758. }
  14759. };
  14760. Scene.prototype._evaluateActiveMeshes = function () {
  14761. this.activeCamera._activeMeshes.reset();
  14762. this._activeMeshes.reset();
  14763. this._renderingManager.reset();
  14764. this._processedMaterials.reset();
  14765. this._activeParticleSystems.reset();
  14766. this._activeSkeletons.reset();
  14767. this._softwareSkinnedMeshes.reset();
  14768. this._boundingBoxRenderer.reset();
  14769. this._edgesRenderers.reset();
  14770. if (!this._frustumPlanes) {
  14771. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14772. }
  14773. else {
  14774. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14775. }
  14776. // Meshes
  14777. var meshes;
  14778. var len;
  14779. if (this._selectionOctree) {
  14780. var selection = this._selectionOctree.select(this._frustumPlanes);
  14781. meshes = selection.data;
  14782. len = selection.length;
  14783. }
  14784. else {
  14785. len = this.meshes.length;
  14786. meshes = this.meshes;
  14787. }
  14788. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  14789. var mesh = meshes[meshIndex];
  14790. if (mesh.isBlocked) {
  14791. continue;
  14792. }
  14793. this._totalVertices += mesh.getTotalVertices();
  14794. if (!mesh.isReady() || !mesh.isEnabled()) {
  14795. continue;
  14796. }
  14797. mesh.computeWorldMatrix();
  14798. // Intersections
  14799. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  14800. this._meshesForIntersections.pushNoDuplicate(mesh);
  14801. }
  14802. // Switch to current LOD
  14803. var meshLOD = mesh.getLOD(this.activeCamera);
  14804. if (!meshLOD) {
  14805. continue;
  14806. }
  14807. mesh._preActivate();
  14808. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  14809. this._activeMeshes.push(mesh);
  14810. this.activeCamera._activeMeshes.push(mesh);
  14811. mesh._activate(this._renderId);
  14812. this._activeMesh(meshLOD);
  14813. }
  14814. }
  14815. // Particle systems
  14816. var beforeParticlesDate = BABYLON.Tools.Now;
  14817. if (this.particlesEnabled) {
  14818. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  14819. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  14820. var particleSystem = this.particleSystems[particleIndex];
  14821. if (!particleSystem.isStarted()) {
  14822. continue;
  14823. }
  14824. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  14825. this._activeParticleSystems.push(particleSystem);
  14826. particleSystem.animate();
  14827. }
  14828. }
  14829. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  14830. }
  14831. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14832. };
  14833. Scene.prototype._activeMesh = function (mesh) {
  14834. if (mesh.skeleton && this.skeletonsEnabled) {
  14835. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  14836. if (!mesh.computeBonesUsingShaders) {
  14837. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  14838. }
  14839. }
  14840. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  14841. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  14842. }
  14843. if (mesh._edgesRenderer) {
  14844. this._edgesRenderers.push(mesh._edgesRenderer);
  14845. }
  14846. if (mesh && mesh.subMeshes) {
  14847. // Submeshes Octrees
  14848. var len;
  14849. var subMeshes;
  14850. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  14851. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  14852. len = intersections.length;
  14853. subMeshes = intersections.data;
  14854. }
  14855. else {
  14856. subMeshes = mesh.subMeshes;
  14857. len = subMeshes.length;
  14858. }
  14859. for (var subIndex = 0; subIndex < len; subIndex++) {
  14860. var subMesh = subMeshes[subIndex];
  14861. this._evaluateSubMesh(subMesh, mesh);
  14862. }
  14863. }
  14864. };
  14865. Scene.prototype.updateTransformMatrix = function (force) {
  14866. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  14867. };
  14868. Scene.prototype._renderForCamera = function (camera) {
  14869. var engine = this._engine;
  14870. this.activeCamera = camera;
  14871. if (!this.activeCamera)
  14872. throw new Error("Active camera not set");
  14873. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14874. // Viewport
  14875. engine.setViewport(this.activeCamera.viewport);
  14876. // Camera
  14877. this.resetCachedMaterial();
  14878. this._renderId++;
  14879. this.updateTransformMatrix();
  14880. if (this.beforeCameraRender) {
  14881. this.beforeCameraRender(this.activeCamera);
  14882. }
  14883. // Meshes
  14884. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  14885. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  14886. this._evaluateActiveMeshes();
  14887. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  14888. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  14889. // Skeletons
  14890. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  14891. var skeleton = this._activeSkeletons.data[skeletonIndex];
  14892. skeleton.prepare();
  14893. }
  14894. // Software skinning
  14895. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  14896. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  14897. mesh.applySkeleton(mesh.skeleton);
  14898. }
  14899. // Render targets
  14900. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14901. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  14902. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  14903. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  14904. var renderTarget = this._renderTargets.data[renderIndex];
  14905. if (renderTarget._shouldRender()) {
  14906. this._renderId++;
  14907. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  14908. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  14909. }
  14910. }
  14911. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  14912. this._renderId++;
  14913. engine.restoreDefaultFramebuffer(); // Restore back buffer
  14914. }
  14915. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14916. // Prepare Frame
  14917. this.postProcessManager._prepareFrame();
  14918. var beforeRenderDate = BABYLON.Tools.Now;
  14919. // Backgrounds
  14920. var layerIndex;
  14921. var layer;
  14922. if (this.layers.length) {
  14923. engine.setDepthBuffer(false);
  14924. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14925. layer = this.layers[layerIndex];
  14926. if (layer.isBackground) {
  14927. layer.render();
  14928. }
  14929. }
  14930. engine.setDepthBuffer(true);
  14931. }
  14932. // Render
  14933. BABYLON.Tools.StartPerformanceCounter("Main render");
  14934. this._renderingManager.render(null, null, true, true);
  14935. BABYLON.Tools.EndPerformanceCounter("Main render");
  14936. // Bounding boxes
  14937. this._boundingBoxRenderer.render();
  14938. // Edges
  14939. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14940. this._edgesRenderers.data[edgesRendererIndex].render();
  14941. }
  14942. // Lens flares
  14943. if (this.lensFlaresEnabled) {
  14944. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14945. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  14946. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  14947. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  14948. lensFlareSystem.render();
  14949. }
  14950. }
  14951. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14952. }
  14953. // Foregrounds
  14954. if (this.layers.length) {
  14955. engine.setDepthBuffer(false);
  14956. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14957. layer = this.layers[layerIndex];
  14958. if (!layer.isBackground) {
  14959. layer.render();
  14960. }
  14961. }
  14962. engine.setDepthBuffer(true);
  14963. }
  14964. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  14965. // Finalize frame
  14966. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  14967. // Update camera
  14968. this.activeCamera._updateFromScene();
  14969. // Reset some special arrays
  14970. this._renderTargets.reset();
  14971. if (this.afterCameraRender) {
  14972. this.afterCameraRender(this.activeCamera);
  14973. }
  14974. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14975. };
  14976. Scene.prototype._processSubCameras = function (camera) {
  14977. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  14978. this._renderForCamera(camera);
  14979. return;
  14980. }
  14981. // rig cameras
  14982. for (var index = 0; index < camera._rigCameras.length; index++) {
  14983. this._renderForCamera(camera._rigCameras[index]);
  14984. }
  14985. this.activeCamera = camera;
  14986. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  14987. // Update camera
  14988. this.activeCamera._updateFromScene();
  14989. };
  14990. Scene.prototype._checkIntersections = function () {
  14991. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14992. var sourceMesh = this._meshesForIntersections.data[index];
  14993. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14994. var action = sourceMesh.actionManager.actions[actionIndex];
  14995. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14996. var parameters = action.getTriggerParameter();
  14997. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  14998. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  14999. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15000. if (areIntersecting && currentIntersectionInProgress === -1) {
  15001. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15002. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15003. sourceMesh._intersectionsInProgress.push(otherMesh);
  15004. }
  15005. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15006. sourceMesh._intersectionsInProgress.push(otherMesh);
  15007. }
  15008. }
  15009. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15010. //They intersected, and now they don't.
  15011. //is this trigger an exit trigger? execute an event.
  15012. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15013. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15014. }
  15015. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15016. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15017. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15018. }
  15019. }
  15020. }
  15021. }
  15022. }
  15023. };
  15024. Scene.prototype.render = function () {
  15025. var startDate = BABYLON.Tools.Now;
  15026. this._particlesDuration = 0;
  15027. this._spritesDuration = 0;
  15028. this._activeParticles = 0;
  15029. this._renderDuration = 0;
  15030. this._renderTargetsDuration = 0;
  15031. this._evaluateActiveMeshesDuration = 0;
  15032. this._totalVertices = 0;
  15033. this._activeIndices = 0;
  15034. this._activeBones = 0;
  15035. this.getEngine().resetDrawCalls();
  15036. this._meshesForIntersections.reset();
  15037. this.resetCachedMaterial();
  15038. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15039. // Actions
  15040. if (this.actionManager) {
  15041. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15042. }
  15043. //Simplification Queue
  15044. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15045. this.simplificationQueue.executeNext();
  15046. }
  15047. // Animations
  15048. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15049. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15050. this._animate();
  15051. // Physics
  15052. if (this._physicsEngine) {
  15053. BABYLON.Tools.StartPerformanceCounter("Physics");
  15054. this._physicsEngine._step(deltaTime / 1000.0);
  15055. BABYLON.Tools.EndPerformanceCounter("Physics");
  15056. }
  15057. // Before render
  15058. if (this.beforeRender) {
  15059. this.beforeRender();
  15060. }
  15061. var callbackIndex;
  15062. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15063. this._onBeforeRenderCallbacks[callbackIndex]();
  15064. }
  15065. // Customs render targets
  15066. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15067. var engine = this.getEngine();
  15068. var currentActiveCamera = this.activeCamera;
  15069. if (this.renderTargetsEnabled) {
  15070. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15071. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15072. var renderTarget = this.customRenderTargets[customIndex];
  15073. if (renderTarget._shouldRender()) {
  15074. this._renderId++;
  15075. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15076. if (!this.activeCamera)
  15077. throw new Error("Active camera not set");
  15078. // Viewport
  15079. engine.setViewport(this.activeCamera.viewport);
  15080. // Camera
  15081. this.updateTransformMatrix();
  15082. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15083. }
  15084. }
  15085. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15086. this._renderId++;
  15087. }
  15088. if (this.customRenderTargets.length > 0) {
  15089. engine.restoreDefaultFramebuffer();
  15090. }
  15091. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15092. this.activeCamera = currentActiveCamera;
  15093. // Procedural textures
  15094. if (this.proceduralTexturesEnabled) {
  15095. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15096. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15097. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15098. if (proceduralTexture._shouldRender()) {
  15099. proceduralTexture.render();
  15100. }
  15101. }
  15102. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15103. }
  15104. // Clear
  15105. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15106. // Shadows
  15107. if (this.shadowsEnabled) {
  15108. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15109. var light = this.lights[lightIndex];
  15110. var shadowGenerator = light.getShadowGenerator();
  15111. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15112. this._renderTargets.push(shadowGenerator.getShadowMap());
  15113. }
  15114. }
  15115. }
  15116. // Depth renderer
  15117. if (this._depthRenderer) {
  15118. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15119. }
  15120. // RenderPipeline
  15121. this.postProcessRenderPipelineManager.update();
  15122. // Multi-cameras?
  15123. if (this.activeCameras.length > 0) {
  15124. var currentRenderId = this._renderId;
  15125. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15126. this._renderId = currentRenderId;
  15127. if (cameraIndex > 0) {
  15128. this._engine.clear(0, false, true);
  15129. }
  15130. this._processSubCameras(this.activeCameras[cameraIndex]);
  15131. }
  15132. }
  15133. else {
  15134. if (!this.activeCamera) {
  15135. throw new Error("No camera defined");
  15136. }
  15137. this._processSubCameras(this.activeCamera);
  15138. }
  15139. // Intersection checks
  15140. this._checkIntersections();
  15141. // Update the audio listener attached to the camera
  15142. if (BABYLON.AudioEngine) {
  15143. this._updateAudioParameters();
  15144. }
  15145. // After render
  15146. if (this.afterRender) {
  15147. this.afterRender();
  15148. }
  15149. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15150. this._onAfterRenderCallbacks[callbackIndex]();
  15151. }
  15152. // Cleaning
  15153. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15154. this._toBeDisposed.data[index].dispose();
  15155. this._toBeDisposed[index] = null;
  15156. }
  15157. this._toBeDisposed.reset();
  15158. if (this.dumpNextRenderTargets) {
  15159. this.dumpNextRenderTargets = false;
  15160. }
  15161. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15162. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15163. };
  15164. Scene.prototype._updateAudioParameters = function () {
  15165. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15166. return;
  15167. }
  15168. var listeningCamera;
  15169. var audioEngine = BABYLON.Engine.audioEngine;
  15170. if (this.activeCameras.length > 0) {
  15171. listeningCamera = this.activeCameras[0];
  15172. }
  15173. else {
  15174. listeningCamera = this.activeCamera;
  15175. }
  15176. if (listeningCamera && audioEngine.canUseWebAudio) {
  15177. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15178. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15179. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15180. cameraDirection.normalize();
  15181. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15182. var i;
  15183. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15184. var sound = this.mainSoundTrack.soundCollection[i];
  15185. if (sound.useCustomAttenuation) {
  15186. sound.updateDistanceFromListener();
  15187. }
  15188. }
  15189. for (i = 0; i < this.soundTracks.length; i++) {
  15190. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15191. sound = this.soundTracks[i].soundCollection[j];
  15192. if (sound.useCustomAttenuation) {
  15193. sound.updateDistanceFromListener();
  15194. }
  15195. }
  15196. }
  15197. }
  15198. };
  15199. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15200. // Audio
  15201. get: function () {
  15202. return this._audioEnabled;
  15203. },
  15204. set: function (value) {
  15205. this._audioEnabled = value;
  15206. if (BABYLON.AudioEngine) {
  15207. if (this._audioEnabled) {
  15208. this._enableAudio();
  15209. }
  15210. else {
  15211. this._disableAudio();
  15212. }
  15213. }
  15214. },
  15215. enumerable: true,
  15216. configurable: true
  15217. });
  15218. Scene.prototype._disableAudio = function () {
  15219. var i;
  15220. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15221. this.mainSoundTrack.soundCollection[i].pause();
  15222. }
  15223. for (i = 0; i < this.soundTracks.length; i++) {
  15224. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15225. this.soundTracks[i].soundCollection[j].pause();
  15226. }
  15227. }
  15228. };
  15229. Scene.prototype._enableAudio = function () {
  15230. var i;
  15231. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15232. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15233. this.mainSoundTrack.soundCollection[i].play();
  15234. }
  15235. }
  15236. for (i = 0; i < this.soundTracks.length; i++) {
  15237. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15238. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15239. this.soundTracks[i].soundCollection[j].play();
  15240. }
  15241. }
  15242. }
  15243. };
  15244. Object.defineProperty(Scene.prototype, "headphone", {
  15245. get: function () {
  15246. return this._headphone;
  15247. },
  15248. set: function (value) {
  15249. this._headphone = value;
  15250. if (BABYLON.AudioEngine) {
  15251. if (this._headphone) {
  15252. this._switchAudioModeForHeadphones();
  15253. }
  15254. else {
  15255. this._switchAudioModeForNormalSpeakers();
  15256. }
  15257. }
  15258. },
  15259. enumerable: true,
  15260. configurable: true
  15261. });
  15262. Scene.prototype._switchAudioModeForHeadphones = function () {
  15263. this.mainSoundTrack.switchPanningModelToHRTF();
  15264. for (var i = 0; i < this.soundTracks.length; i++) {
  15265. this.soundTracks[i].switchPanningModelToHRTF();
  15266. }
  15267. };
  15268. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15269. this.mainSoundTrack.switchPanningModelToEqualPower();
  15270. for (var i = 0; i < this.soundTracks.length; i++) {
  15271. this.soundTracks[i].switchPanningModelToEqualPower();
  15272. }
  15273. };
  15274. Scene.prototype.enableDepthRenderer = function () {
  15275. if (this._depthRenderer) {
  15276. return this._depthRenderer;
  15277. }
  15278. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15279. return this._depthRenderer;
  15280. };
  15281. Scene.prototype.disableDepthRenderer = function () {
  15282. if (!this._depthRenderer) {
  15283. return;
  15284. }
  15285. this._depthRenderer.dispose();
  15286. this._depthRenderer = null;
  15287. };
  15288. Scene.prototype.freezeMaterials = function () {
  15289. for (var i = 0; i < this.materials.length; i++) {
  15290. this.materials[i].freeze();
  15291. }
  15292. };
  15293. Scene.prototype.unfreezeMaterials = function () {
  15294. for (var i = 0; i < this.materials.length; i++) {
  15295. this.materials[i].unfreeze();
  15296. }
  15297. };
  15298. Scene.prototype.dispose = function () {
  15299. this.beforeRender = null;
  15300. this.afterRender = null;
  15301. this.skeletons = [];
  15302. this._boundingBoxRenderer.dispose();
  15303. if (this._depthRenderer) {
  15304. this._depthRenderer.dispose();
  15305. }
  15306. // Debug layer
  15307. this.debugLayer.hide();
  15308. // Events
  15309. if (this.onDispose) {
  15310. this.onDispose();
  15311. }
  15312. this._onBeforeRenderCallbacks = [];
  15313. this._onAfterRenderCallbacks = [];
  15314. this.detachControl();
  15315. // Release sounds & sounds tracks
  15316. if (BABYLON.AudioEngine) {
  15317. this.disposeSounds();
  15318. }
  15319. // Detach cameras
  15320. var canvas = this._engine.getRenderingCanvas();
  15321. var index;
  15322. for (index = 0; index < this.cameras.length; index++) {
  15323. this.cameras[index].detachControl(canvas);
  15324. }
  15325. // Release lights
  15326. while (this.lights.length) {
  15327. this.lights[0].dispose();
  15328. }
  15329. // Release meshes
  15330. while (this.meshes.length) {
  15331. this.meshes[0].dispose(true);
  15332. }
  15333. // Release cameras
  15334. while (this.cameras.length) {
  15335. this.cameras[0].dispose();
  15336. }
  15337. // Release materials
  15338. while (this.materials.length) {
  15339. this.materials[0].dispose();
  15340. }
  15341. // Release particles
  15342. while (this.particleSystems.length) {
  15343. this.particleSystems[0].dispose();
  15344. }
  15345. // Release sprites
  15346. while (this.spriteManagers.length) {
  15347. this.spriteManagers[0].dispose();
  15348. }
  15349. // Release layers
  15350. while (this.layers.length) {
  15351. this.layers[0].dispose();
  15352. }
  15353. // Release textures
  15354. while (this.textures.length) {
  15355. this.textures[0].dispose();
  15356. }
  15357. // Post-processes
  15358. this.postProcessManager.dispose();
  15359. // Physics
  15360. if (this._physicsEngine) {
  15361. this.disablePhysicsEngine();
  15362. }
  15363. // Remove from engine
  15364. index = this._engine.scenes.indexOf(this);
  15365. if (index > -1) {
  15366. this._engine.scenes.splice(index, 1);
  15367. }
  15368. this._engine.wipeCaches();
  15369. };
  15370. // Release sounds & sounds tracks
  15371. Scene.prototype.disposeSounds = function () {
  15372. this.mainSoundTrack.dispose();
  15373. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15374. this.soundTracks[scIndex].dispose();
  15375. }
  15376. };
  15377. // Octrees
  15378. Scene.prototype.getWorldExtends = function () {
  15379. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15380. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15381. for (var index = 0; index < this.meshes.length; index++) {
  15382. var mesh = this.meshes[index];
  15383. mesh.computeWorldMatrix(true);
  15384. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  15385. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  15386. BABYLON.Tools.CheckExtends(minBox, min, max);
  15387. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15388. }
  15389. return {
  15390. min: min,
  15391. max: max
  15392. };
  15393. };
  15394. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  15395. if (maxCapacity === void 0) { maxCapacity = 64; }
  15396. if (maxDepth === void 0) { maxDepth = 2; }
  15397. if (!this._selectionOctree) {
  15398. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  15399. }
  15400. var worldExtends = this.getWorldExtends();
  15401. // Update octree
  15402. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  15403. return this._selectionOctree;
  15404. };
  15405. // Picking
  15406. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  15407. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  15408. var engine = this._engine;
  15409. if (!camera) {
  15410. if (!this.activeCamera)
  15411. throw new Error("Active camera not set");
  15412. camera = this.activeCamera;
  15413. }
  15414. var cameraViewport = camera.viewport;
  15415. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15416. // Moving coordinates to local viewport world
  15417. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15418. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15419. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  15420. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  15421. };
  15422. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  15423. var engine = this._engine;
  15424. if (!camera) {
  15425. if (!this.activeCamera)
  15426. throw new Error("Active camera not set");
  15427. camera = this.activeCamera;
  15428. }
  15429. var cameraViewport = camera.viewport;
  15430. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15431. var identity = BABYLON.Matrix.Identity();
  15432. // Moving coordinates to local viewport world
  15433. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15434. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15435. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  15436. };
  15437. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  15438. var pickingInfo = null;
  15439. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  15440. var mesh = this.meshes[meshIndex];
  15441. if (predicate) {
  15442. if (!predicate(mesh)) {
  15443. continue;
  15444. }
  15445. }
  15446. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  15447. continue;
  15448. }
  15449. var world = mesh.getWorldMatrix();
  15450. var ray = rayFunction(world);
  15451. var result = mesh.intersects(ray, fastCheck);
  15452. if (!result || !result.hit)
  15453. continue;
  15454. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15455. continue;
  15456. pickingInfo = result;
  15457. if (fastCheck) {
  15458. break;
  15459. }
  15460. }
  15461. return pickingInfo || new BABYLON.PickingInfo();
  15462. };
  15463. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  15464. var pickingInfo = null;
  15465. camera = camera || this.activeCamera;
  15466. if (this.spriteManagers.length > 0) {
  15467. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  15468. var spriteManager = this.spriteManagers[spriteIndex];
  15469. if (!spriteManager.isPickable) {
  15470. continue;
  15471. }
  15472. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  15473. if (!result || !result.hit)
  15474. continue;
  15475. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15476. continue;
  15477. pickingInfo = result;
  15478. if (fastCheck) {
  15479. break;
  15480. }
  15481. }
  15482. }
  15483. return pickingInfo || new BABYLON.PickingInfo();
  15484. };
  15485. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  15486. var _this = this;
  15487. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15488. /// <param name="x">X position on screen</param>
  15489. /// <param name="y">Y position on screen</param>
  15490. /// <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>
  15491. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15492. /// <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>
  15493. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  15494. };
  15495. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  15496. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15497. /// <param name="x">X position on screen</param>
  15498. /// <param name="y">Y position on screen</param>
  15499. /// <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>
  15500. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15501. /// <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>
  15502. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  15503. };
  15504. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  15505. var _this = this;
  15506. return this._internalPick(function (world) {
  15507. if (!_this._pickWithRayInverseMatrix) {
  15508. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  15509. }
  15510. world.invertToRef(_this._pickWithRayInverseMatrix);
  15511. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  15512. }, predicate, fastCheck);
  15513. };
  15514. Scene.prototype.setPointerOverMesh = function (mesh) {
  15515. if (this._pointerOverMesh === mesh) {
  15516. return;
  15517. }
  15518. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15519. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15520. }
  15521. this._pointerOverMesh = mesh;
  15522. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15523. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15524. }
  15525. };
  15526. Scene.prototype.getPointerOverMesh = function () {
  15527. return this._pointerOverMesh;
  15528. };
  15529. Scene.prototype.setPointerOverSprite = function (sprite) {
  15530. if (this._pointerOverSprite === sprite) {
  15531. return;
  15532. }
  15533. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15534. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15535. }
  15536. this._pointerOverSprite = sprite;
  15537. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15538. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15539. }
  15540. };
  15541. Scene.prototype.getPointerOverSprite = function () {
  15542. return this._pointerOverSprite;
  15543. };
  15544. // Physics
  15545. Scene.prototype.getPhysicsEngine = function () {
  15546. return this._physicsEngine;
  15547. };
  15548. /**
  15549. * Enables physics to the current scene
  15550. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  15551. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  15552. * @return {boolean} was the physics engine initialized
  15553. */
  15554. Scene.prototype.enablePhysics = function (gravity, plugin) {
  15555. if (this._physicsEngine) {
  15556. return true;
  15557. }
  15558. try {
  15559. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  15560. return true;
  15561. }
  15562. catch (e) {
  15563. BABYLON.Tools.Error(e.message);
  15564. return false;
  15565. }
  15566. };
  15567. Scene.prototype.disablePhysicsEngine = function () {
  15568. if (!this._physicsEngine) {
  15569. return;
  15570. }
  15571. this._physicsEngine.dispose();
  15572. this._physicsEngine = undefined;
  15573. };
  15574. Scene.prototype.isPhysicsEnabled = function () {
  15575. return this._physicsEngine !== undefined;
  15576. };
  15577. /**
  15578. *
  15579. * Sets the gravity of the physics engine (and NOT of the scene)
  15580. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  15581. */
  15582. Scene.prototype.setGravity = function (gravity) {
  15583. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  15584. if (!this._physicsEngine) {
  15585. return;
  15586. }
  15587. this._physicsEngine.setGravity(gravity);
  15588. };
  15589. /**
  15590. * Legacy support, using the new API
  15591. * @Deprecated
  15592. */
  15593. Scene.prototype.createCompoundImpostor = function (parts, options) {
  15594. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  15595. if (parts.parts) {
  15596. options = parts;
  15597. parts = parts.parts;
  15598. }
  15599. var mainMesh = parts[0].mesh;
  15600. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  15601. for (var index = 1; index < parts.length; index++) {
  15602. var mesh = parts[index].mesh;
  15603. if (mesh.parent !== mainMesh) {
  15604. mesh.position = mesh.position.subtract(mainMesh.position);
  15605. mesh.parent = mainMesh;
  15606. }
  15607. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  15608. }
  15609. mainMesh.physicsImpostor.forceUpdate();
  15610. };
  15611. Scene.prototype.deleteCompoundImpostor = function (compound) {
  15612. var mesh = compound.parts[0].mesh;
  15613. mesh.physicsImpostor.dispose(true);
  15614. mesh.physicsImpostor = null;
  15615. };
  15616. // Misc.
  15617. Scene.prototype.createDefaultCameraOrLight = function () {
  15618. // Light
  15619. if (this.lights.length === 0) {
  15620. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  15621. }
  15622. // Camera
  15623. if (!this.activeCamera) {
  15624. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  15625. // Compute position
  15626. var worldExtends = this.getWorldExtends();
  15627. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  15628. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  15629. camera.setTarget(worldCenter);
  15630. this.activeCamera = camera;
  15631. }
  15632. };
  15633. // Tags
  15634. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  15635. if (tagsQuery === undefined) {
  15636. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  15637. return list;
  15638. }
  15639. var listByTags = [];
  15640. forEach = forEach || (function (item) { return; });
  15641. for (var i in list) {
  15642. var item = list[i];
  15643. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  15644. listByTags.push(item);
  15645. forEach(item);
  15646. }
  15647. }
  15648. return listByTags;
  15649. };
  15650. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  15651. return this._getByTags(this.meshes, tagsQuery, forEach);
  15652. };
  15653. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  15654. return this._getByTags(this.cameras, tagsQuery, forEach);
  15655. };
  15656. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  15657. return this._getByTags(this.lights, tagsQuery, forEach);
  15658. };
  15659. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  15660. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  15661. };
  15662. // Statics
  15663. Scene._FOGMODE_NONE = 0;
  15664. Scene._FOGMODE_EXP = 1;
  15665. Scene._FOGMODE_EXP2 = 2;
  15666. Scene._FOGMODE_LINEAR = 3;
  15667. Scene.MinDeltaTime = 1.0;
  15668. Scene.MaxDeltaTime = 1000.0;
  15669. return Scene;
  15670. })();
  15671. BABYLON.Scene = Scene;
  15672. })(BABYLON || (BABYLON = {}));
  15673. var BABYLON;
  15674. (function (BABYLON) {
  15675. var VertexBuffer = (function () {
  15676. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  15677. if (engine instanceof BABYLON.Mesh) {
  15678. this._engine = engine.getScene().getEngine();
  15679. }
  15680. else {
  15681. this._engine = engine;
  15682. }
  15683. this._updatable = updatable;
  15684. this._data = data;
  15685. if (!postponeInternalCreation) {
  15686. this.create();
  15687. }
  15688. this._kind = kind;
  15689. if (stride) {
  15690. this._strideSize = stride;
  15691. return;
  15692. }
  15693. // Deduce stride from kind
  15694. switch (kind) {
  15695. case VertexBuffer.PositionKind:
  15696. this._strideSize = 3;
  15697. break;
  15698. case VertexBuffer.NormalKind:
  15699. this._strideSize = 3;
  15700. break;
  15701. case VertexBuffer.UVKind:
  15702. case VertexBuffer.UV2Kind:
  15703. case VertexBuffer.UV3Kind:
  15704. case VertexBuffer.UV4Kind:
  15705. case VertexBuffer.UV5Kind:
  15706. case VertexBuffer.UV6Kind:
  15707. this._strideSize = 2;
  15708. break;
  15709. case VertexBuffer.ColorKind:
  15710. this._strideSize = 4;
  15711. break;
  15712. case VertexBuffer.MatricesIndicesKind:
  15713. case VertexBuffer.MatricesIndicesExtraKind:
  15714. this._strideSize = 4;
  15715. break;
  15716. case VertexBuffer.MatricesWeightsKind:
  15717. case VertexBuffer.MatricesWeightsExtraKind:
  15718. this._strideSize = 4;
  15719. break;
  15720. }
  15721. }
  15722. // Properties
  15723. VertexBuffer.prototype.isUpdatable = function () {
  15724. return this._updatable;
  15725. };
  15726. VertexBuffer.prototype.getData = function () {
  15727. return this._data;
  15728. };
  15729. VertexBuffer.prototype.getBuffer = function () {
  15730. return this._buffer;
  15731. };
  15732. VertexBuffer.prototype.getStrideSize = function () {
  15733. return this._strideSize;
  15734. };
  15735. // Methods
  15736. VertexBuffer.prototype.create = function (data) {
  15737. if (!data && this._buffer) {
  15738. return; // nothing to do
  15739. }
  15740. data = data || this._data;
  15741. if (!this._buffer) {
  15742. if (this._updatable) {
  15743. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  15744. }
  15745. else {
  15746. this._buffer = this._engine.createVertexBuffer(data);
  15747. }
  15748. }
  15749. if (this._updatable) {
  15750. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  15751. this._data = data;
  15752. }
  15753. };
  15754. VertexBuffer.prototype.update = function (data) {
  15755. this.create(data);
  15756. };
  15757. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  15758. if (!this._buffer) {
  15759. return;
  15760. }
  15761. if (this._updatable) {
  15762. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  15763. this._data = null;
  15764. }
  15765. };
  15766. VertexBuffer.prototype.dispose = function () {
  15767. if (!this._buffer) {
  15768. return;
  15769. }
  15770. if (this._engine._releaseBuffer(this._buffer)) {
  15771. this._buffer = null;
  15772. }
  15773. };
  15774. Object.defineProperty(VertexBuffer, "PositionKind", {
  15775. get: function () {
  15776. return VertexBuffer._PositionKind;
  15777. },
  15778. enumerable: true,
  15779. configurable: true
  15780. });
  15781. Object.defineProperty(VertexBuffer, "NormalKind", {
  15782. get: function () {
  15783. return VertexBuffer._NormalKind;
  15784. },
  15785. enumerable: true,
  15786. configurable: true
  15787. });
  15788. Object.defineProperty(VertexBuffer, "UVKind", {
  15789. get: function () {
  15790. return VertexBuffer._UVKind;
  15791. },
  15792. enumerable: true,
  15793. configurable: true
  15794. });
  15795. Object.defineProperty(VertexBuffer, "UV2Kind", {
  15796. get: function () {
  15797. return VertexBuffer._UV2Kind;
  15798. },
  15799. enumerable: true,
  15800. configurable: true
  15801. });
  15802. Object.defineProperty(VertexBuffer, "UV3Kind", {
  15803. get: function () {
  15804. return VertexBuffer._UV3Kind;
  15805. },
  15806. enumerable: true,
  15807. configurable: true
  15808. });
  15809. Object.defineProperty(VertexBuffer, "UV4Kind", {
  15810. get: function () {
  15811. return VertexBuffer._UV4Kind;
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Object.defineProperty(VertexBuffer, "UV5Kind", {
  15817. get: function () {
  15818. return VertexBuffer._UV5Kind;
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. Object.defineProperty(VertexBuffer, "UV6Kind", {
  15824. get: function () {
  15825. return VertexBuffer._UV6Kind;
  15826. },
  15827. enumerable: true,
  15828. configurable: true
  15829. });
  15830. Object.defineProperty(VertexBuffer, "ColorKind", {
  15831. get: function () {
  15832. return VertexBuffer._ColorKind;
  15833. },
  15834. enumerable: true,
  15835. configurable: true
  15836. });
  15837. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  15838. get: function () {
  15839. return VertexBuffer._MatricesIndicesKind;
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  15845. get: function () {
  15846. return VertexBuffer._MatricesWeightsKind;
  15847. },
  15848. enumerable: true,
  15849. configurable: true
  15850. });
  15851. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  15852. get: function () {
  15853. return VertexBuffer._MatricesIndicesExtraKind;
  15854. },
  15855. enumerable: true,
  15856. configurable: true
  15857. });
  15858. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  15859. get: function () {
  15860. return VertexBuffer._MatricesWeightsExtraKind;
  15861. },
  15862. enumerable: true,
  15863. configurable: true
  15864. });
  15865. // Enums
  15866. VertexBuffer._PositionKind = "position";
  15867. VertexBuffer._NormalKind = "normal";
  15868. VertexBuffer._UVKind = "uv";
  15869. VertexBuffer._UV2Kind = "uv2";
  15870. VertexBuffer._UV3Kind = "uv3";
  15871. VertexBuffer._UV4Kind = "uv4";
  15872. VertexBuffer._UV5Kind = "uv5";
  15873. VertexBuffer._UV6Kind = "uv6";
  15874. VertexBuffer._ColorKind = "color";
  15875. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  15876. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  15877. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  15878. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  15879. return VertexBuffer;
  15880. })();
  15881. BABYLON.VertexBuffer = VertexBuffer;
  15882. })(BABYLON || (BABYLON = {}));
  15883. var BABYLON;
  15884. (function (BABYLON) {
  15885. /**
  15886. * Creates an instance based on a source mesh.
  15887. */
  15888. var InstancedMesh = (function (_super) {
  15889. __extends(InstancedMesh, _super);
  15890. function InstancedMesh(name, source) {
  15891. _super.call(this, name, source.getScene());
  15892. source.instances.push(this);
  15893. this._sourceMesh = source;
  15894. this.position.copyFrom(source.position);
  15895. this.rotation.copyFrom(source.rotation);
  15896. this.scaling.copyFrom(source.scaling);
  15897. if (source.rotationQuaternion) {
  15898. this.rotationQuaternion = source.rotationQuaternion.clone();
  15899. }
  15900. this.infiniteDistance = source.infiniteDistance;
  15901. this.setPivotMatrix(source.getPivotMatrix());
  15902. this.refreshBoundingInfo();
  15903. this._syncSubMeshes();
  15904. }
  15905. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  15906. // Methods
  15907. get: function () {
  15908. return this._sourceMesh.receiveShadows;
  15909. },
  15910. enumerable: true,
  15911. configurable: true
  15912. });
  15913. Object.defineProperty(InstancedMesh.prototype, "material", {
  15914. get: function () {
  15915. return this._sourceMesh.material;
  15916. },
  15917. enumerable: true,
  15918. configurable: true
  15919. });
  15920. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  15921. get: function () {
  15922. return this._sourceMesh.visibility;
  15923. },
  15924. enumerable: true,
  15925. configurable: true
  15926. });
  15927. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  15928. get: function () {
  15929. return this._sourceMesh.skeleton;
  15930. },
  15931. enumerable: true,
  15932. configurable: true
  15933. });
  15934. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  15935. get: function () {
  15936. return this._sourceMesh.renderingGroupId;
  15937. },
  15938. enumerable: true,
  15939. configurable: true
  15940. });
  15941. InstancedMesh.prototype.getTotalVertices = function () {
  15942. return this._sourceMesh.getTotalVertices();
  15943. };
  15944. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  15945. get: function () {
  15946. return this._sourceMesh;
  15947. },
  15948. enumerable: true,
  15949. configurable: true
  15950. });
  15951. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15952. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  15953. };
  15954. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  15955. return this._sourceMesh.isVerticesDataPresent(kind);
  15956. };
  15957. InstancedMesh.prototype.getIndices = function () {
  15958. return this._sourceMesh.getIndices();
  15959. };
  15960. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  15961. get: function () {
  15962. return this._sourceMesh._positions;
  15963. },
  15964. enumerable: true,
  15965. configurable: true
  15966. });
  15967. InstancedMesh.prototype.refreshBoundingInfo = function () {
  15968. var meshBB = this._sourceMesh.getBoundingInfo();
  15969. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  15970. this._updateBoundingInfo();
  15971. };
  15972. InstancedMesh.prototype._preActivate = function () {
  15973. if (this._currentLOD) {
  15974. this._currentLOD._preActivate();
  15975. }
  15976. };
  15977. InstancedMesh.prototype._activate = function (renderId) {
  15978. if (this._currentLOD) {
  15979. this._currentLOD._registerInstanceForRenderId(this, renderId);
  15980. }
  15981. };
  15982. InstancedMesh.prototype.getLOD = function (camera) {
  15983. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  15984. if (this._currentLOD === this.sourceMesh) {
  15985. return this;
  15986. }
  15987. return this._currentLOD;
  15988. };
  15989. InstancedMesh.prototype._syncSubMeshes = function () {
  15990. this.releaseSubMeshes();
  15991. if (this._sourceMesh.subMeshes) {
  15992. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15993. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15994. }
  15995. }
  15996. };
  15997. InstancedMesh.prototype._generatePointsArray = function () {
  15998. return this._sourceMesh._generatePointsArray();
  15999. };
  16000. // Clone
  16001. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16002. var result = this._sourceMesh.createInstance(name);
  16003. // Deep copy
  16004. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16005. // Bounding info
  16006. this.refreshBoundingInfo();
  16007. // Parent
  16008. if (newParent) {
  16009. result.parent = newParent;
  16010. }
  16011. if (!doNotCloneChildren) {
  16012. // Children
  16013. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16014. var mesh = this.getScene().meshes[index];
  16015. if (mesh.parent === this) {
  16016. mesh.clone(mesh.name, result);
  16017. }
  16018. }
  16019. }
  16020. result.computeWorldMatrix(true);
  16021. return result;
  16022. };
  16023. // Dispoe
  16024. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16025. // Remove from mesh
  16026. var index = this._sourceMesh.instances.indexOf(this);
  16027. this._sourceMesh.instances.splice(index, 1);
  16028. _super.prototype.dispose.call(this, doNotRecurse);
  16029. };
  16030. return InstancedMesh;
  16031. })(BABYLON.AbstractMesh);
  16032. BABYLON.InstancedMesh = InstancedMesh;
  16033. })(BABYLON || (BABYLON = {}));
  16034. var BABYLON;
  16035. (function (BABYLON) {
  16036. var _InstancesBatch = (function () {
  16037. function _InstancesBatch() {
  16038. this.mustReturn = false;
  16039. this.visibleInstances = new Array();
  16040. this.renderSelf = new Array();
  16041. }
  16042. return _InstancesBatch;
  16043. })();
  16044. BABYLON._InstancesBatch = _InstancesBatch;
  16045. var Mesh = (function (_super) {
  16046. __extends(Mesh, _super);
  16047. /**
  16048. * @constructor
  16049. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16050. * @param {Scene} scene - The scene to add this mesh to.
  16051. * @param {Node} parent - The parent of this mesh, if it has one
  16052. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16053. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16054. * When false, achieved by calling a clone(), also passing False.
  16055. * This will make creation of children, recursive.
  16056. */
  16057. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  16058. if (parent === void 0) { parent = null; }
  16059. _super.call(this, name, scene);
  16060. // Members
  16061. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16062. this.instances = new Array();
  16063. this._LODLevels = new Array();
  16064. this._onBeforeRenderCallbacks = new Array();
  16065. this._onAfterRenderCallbacks = new Array();
  16066. this._visibleInstances = {};
  16067. this._renderIdForInstances = new Array();
  16068. this._batchCache = new _InstancesBatch();
  16069. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16070. this._sideOrientation = Mesh._DEFAULTSIDE;
  16071. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16072. if (source) {
  16073. // Geometry
  16074. if (source._geometry) {
  16075. source._geometry.applyToMesh(this);
  16076. }
  16077. // Deep copy
  16078. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16079. // Pivot
  16080. this.setPivotMatrix(source.getPivotMatrix());
  16081. this.id = name + "." + source.id;
  16082. // Material
  16083. this.material = source.material;
  16084. var index;
  16085. if (!doNotCloneChildren) {
  16086. // Children
  16087. for (index = 0; index < scene.meshes.length; index++) {
  16088. var mesh = scene.meshes[index];
  16089. if (mesh.parent === source) {
  16090. // doNotCloneChildren is always going to be False
  16091. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16092. }
  16093. }
  16094. }
  16095. // Particles
  16096. for (index = 0; index < scene.particleSystems.length; index++) {
  16097. var system = scene.particleSystems[index];
  16098. if (system.emitter === source) {
  16099. system.clone(system.name, this);
  16100. }
  16101. }
  16102. this.computeWorldMatrix(true);
  16103. }
  16104. // Parent
  16105. if (parent !== null) {
  16106. this.parent = parent;
  16107. }
  16108. }
  16109. Object.defineProperty(Mesh, "FRONTSIDE", {
  16110. get: function () {
  16111. return Mesh._FRONTSIDE;
  16112. },
  16113. enumerable: true,
  16114. configurable: true
  16115. });
  16116. Object.defineProperty(Mesh, "BACKSIDE", {
  16117. get: function () {
  16118. return Mesh._BACKSIDE;
  16119. },
  16120. enumerable: true,
  16121. configurable: true
  16122. });
  16123. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16124. get: function () {
  16125. return Mesh._DOUBLESIDE;
  16126. },
  16127. enumerable: true,
  16128. configurable: true
  16129. });
  16130. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16131. get: function () {
  16132. return Mesh._DEFAULTSIDE;
  16133. },
  16134. enumerable: true,
  16135. configurable: true
  16136. });
  16137. Object.defineProperty(Mesh, "NO_CAP", {
  16138. get: function () {
  16139. return Mesh._NO_CAP;
  16140. },
  16141. enumerable: true,
  16142. configurable: true
  16143. });
  16144. Object.defineProperty(Mesh, "CAP_START", {
  16145. get: function () {
  16146. return Mesh._CAP_START;
  16147. },
  16148. enumerable: true,
  16149. configurable: true
  16150. });
  16151. Object.defineProperty(Mesh, "CAP_END", {
  16152. get: function () {
  16153. return Mesh._CAP_END;
  16154. },
  16155. enumerable: true,
  16156. configurable: true
  16157. });
  16158. Object.defineProperty(Mesh, "CAP_ALL", {
  16159. get: function () {
  16160. return Mesh._CAP_ALL;
  16161. },
  16162. enumerable: true,
  16163. configurable: true
  16164. });
  16165. // Methods
  16166. /**
  16167. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16168. */
  16169. Mesh.prototype.toString = function (fullDetails) {
  16170. var ret = _super.prototype.toString.call(this, fullDetails);
  16171. ret += ", n vertices: " + this.getTotalVertices();
  16172. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16173. if (this.animations) {
  16174. for (var i = 0; i < this.animations.length; i++) {
  16175. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16176. }
  16177. }
  16178. if (fullDetails) {
  16179. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16180. }
  16181. return ret;
  16182. };
  16183. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16184. get: function () {
  16185. return this._LODLevels.length > 0;
  16186. },
  16187. enumerable: true,
  16188. configurable: true
  16189. });
  16190. Mesh.prototype._sortLODLevels = function () {
  16191. this._LODLevels.sort(function (a, b) {
  16192. if (a.distance < b.distance) {
  16193. return 1;
  16194. }
  16195. if (a.distance > b.distance) {
  16196. return -1;
  16197. }
  16198. return 0;
  16199. });
  16200. };
  16201. /**
  16202. * Add a mesh as LOD level triggered at the given distance.
  16203. * @param {number} distance - the distance from the center of the object to show this level
  16204. * @param {Mesh} mesh - the mesh to be added as LOD level
  16205. * @return {Mesh} this mesh (for chaining)
  16206. */
  16207. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16208. if (mesh && mesh._masterMesh) {
  16209. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16210. return this;
  16211. }
  16212. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16213. this._LODLevels.push(level);
  16214. if (mesh) {
  16215. mesh._masterMesh = this;
  16216. }
  16217. this._sortLODLevels();
  16218. return this;
  16219. };
  16220. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16221. for (var index = 0; index < this._LODLevels.length; index++) {
  16222. var level = this._LODLevels[index];
  16223. if (level.distance === distance) {
  16224. return level.mesh;
  16225. }
  16226. }
  16227. return null;
  16228. };
  16229. /**
  16230. * Remove a mesh from the LOD array
  16231. * @param {Mesh} mesh - the mesh to be removed.
  16232. * @return {Mesh} this mesh (for chaining)
  16233. */
  16234. Mesh.prototype.removeLODLevel = function (mesh) {
  16235. for (var index = 0; index < this._LODLevels.length; index++) {
  16236. if (this._LODLevels[index].mesh === mesh) {
  16237. this._LODLevels.splice(index, 1);
  16238. if (mesh) {
  16239. mesh._masterMesh = null;
  16240. }
  16241. }
  16242. }
  16243. this._sortLODLevels();
  16244. return this;
  16245. };
  16246. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16247. if (!this._LODLevels || this._LODLevels.length === 0) {
  16248. return this;
  16249. }
  16250. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  16251. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16252. if (this.onLODLevelSelection) {
  16253. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16254. }
  16255. return this;
  16256. }
  16257. for (var index = 0; index < this._LODLevels.length; index++) {
  16258. var level = this._LODLevels[index];
  16259. if (level.distance < distanceToCamera) {
  16260. if (level.mesh) {
  16261. level.mesh._preActivate();
  16262. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16263. }
  16264. if (this.onLODLevelSelection) {
  16265. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16266. }
  16267. return level.mesh;
  16268. }
  16269. }
  16270. if (this.onLODLevelSelection) {
  16271. this.onLODLevelSelection(distanceToCamera, this, this);
  16272. }
  16273. return this;
  16274. };
  16275. Object.defineProperty(Mesh.prototype, "geometry", {
  16276. get: function () {
  16277. return this._geometry;
  16278. },
  16279. enumerable: true,
  16280. configurable: true
  16281. });
  16282. Mesh.prototype.getTotalVertices = function () {
  16283. if (!this._geometry) {
  16284. return 0;
  16285. }
  16286. return this._geometry.getTotalVertices();
  16287. };
  16288. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16289. if (!this._geometry) {
  16290. return null;
  16291. }
  16292. return this._geometry.getVerticesData(kind, copyWhenShared);
  16293. };
  16294. Mesh.prototype.getVertexBuffer = function (kind) {
  16295. if (!this._geometry) {
  16296. return undefined;
  16297. }
  16298. return this._geometry.getVertexBuffer(kind);
  16299. };
  16300. Mesh.prototype.isVerticesDataPresent = function (kind) {
  16301. if (!this._geometry) {
  16302. if (this._delayInfo) {
  16303. return this._delayInfo.indexOf(kind) !== -1;
  16304. }
  16305. return false;
  16306. }
  16307. return this._geometry.isVerticesDataPresent(kind);
  16308. };
  16309. Mesh.prototype.getVerticesDataKinds = function () {
  16310. if (!this._geometry) {
  16311. var result = [];
  16312. if (this._delayInfo) {
  16313. for (var kind in this._delayInfo) {
  16314. result.push(kind);
  16315. }
  16316. }
  16317. return result;
  16318. }
  16319. return this._geometry.getVerticesDataKinds();
  16320. };
  16321. Mesh.prototype.getTotalIndices = function () {
  16322. if (!this._geometry) {
  16323. return 0;
  16324. }
  16325. return this._geometry.getTotalIndices();
  16326. };
  16327. Mesh.prototype.getIndices = function (copyWhenShared) {
  16328. if (!this._geometry) {
  16329. return [];
  16330. }
  16331. return this._geometry.getIndices(copyWhenShared);
  16332. };
  16333. Object.defineProperty(Mesh.prototype, "isBlocked", {
  16334. get: function () {
  16335. return this._masterMesh !== null && this._masterMesh !== undefined;
  16336. },
  16337. enumerable: true,
  16338. configurable: true
  16339. });
  16340. Mesh.prototype.isReady = function () {
  16341. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16342. return false;
  16343. }
  16344. return _super.prototype.isReady.call(this);
  16345. };
  16346. Mesh.prototype.isDisposed = function () {
  16347. return this._isDisposed;
  16348. };
  16349. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  16350. get: function () {
  16351. return this._sideOrientation;
  16352. },
  16353. set: function (sideO) {
  16354. this._sideOrientation = sideO;
  16355. },
  16356. enumerable: true,
  16357. configurable: true
  16358. });
  16359. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  16360. get: function () {
  16361. return this._areNormalsFrozen;
  16362. },
  16363. enumerable: true,
  16364. configurable: true
  16365. });
  16366. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  16367. Mesh.prototype.freezeNormals = function () {
  16368. this._areNormalsFrozen = true;
  16369. };
  16370. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  16371. Mesh.prototype.unfreezeNormals = function () {
  16372. this._areNormalsFrozen = false;
  16373. };
  16374. // Methods
  16375. Mesh.prototype._preActivate = function () {
  16376. var sceneRenderId = this.getScene().getRenderId();
  16377. if (this._preActivateId === sceneRenderId) {
  16378. return;
  16379. }
  16380. this._preActivateId = sceneRenderId;
  16381. this._visibleInstances = null;
  16382. };
  16383. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  16384. if (!this._visibleInstances) {
  16385. this._visibleInstances = {};
  16386. this._visibleInstances.defaultRenderId = renderId;
  16387. this._visibleInstances.selfDefaultRenderId = this._renderId;
  16388. }
  16389. if (!this._visibleInstances[renderId]) {
  16390. this._visibleInstances[renderId] = new Array();
  16391. }
  16392. this._visibleInstances[renderId].push(instance);
  16393. };
  16394. Mesh.prototype.refreshBoundingInfo = function () {
  16395. if (this._boundingInfo.isLocked) {
  16396. return;
  16397. }
  16398. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16399. if (data) {
  16400. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  16401. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16402. }
  16403. if (this.subMeshes) {
  16404. for (var index = 0; index < this.subMeshes.length; index++) {
  16405. this.subMeshes[index].refreshBoundingInfo();
  16406. }
  16407. }
  16408. this._updateBoundingInfo();
  16409. };
  16410. Mesh.prototype._createGlobalSubMesh = function () {
  16411. var totalVertices = this.getTotalVertices();
  16412. if (!totalVertices || !this.getIndices()) {
  16413. return null;
  16414. }
  16415. this.releaseSubMeshes();
  16416. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  16417. };
  16418. Mesh.prototype.subdivide = function (count) {
  16419. if (count < 1) {
  16420. return;
  16421. }
  16422. var totalIndices = this.getTotalIndices();
  16423. var subdivisionSize = (totalIndices / count) | 0;
  16424. var offset = 0;
  16425. // Ensure that subdivisionSize is a multiple of 3
  16426. while (subdivisionSize % 3 !== 0) {
  16427. subdivisionSize++;
  16428. }
  16429. this.releaseSubMeshes();
  16430. for (var index = 0; index < count; index++) {
  16431. if (offset >= totalIndices) {
  16432. break;
  16433. }
  16434. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  16435. offset += subdivisionSize;
  16436. }
  16437. this.synchronizeInstances();
  16438. };
  16439. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16440. if (!this._geometry) {
  16441. var vertexData = new BABYLON.VertexData();
  16442. vertexData.set(data, kind);
  16443. var scene = this.getScene();
  16444. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  16445. }
  16446. else {
  16447. this._geometry.setVerticesData(kind, data, updatable, stride);
  16448. }
  16449. };
  16450. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16451. if (!this._geometry) {
  16452. return;
  16453. }
  16454. if (!makeItUnique) {
  16455. this._geometry.updateVerticesData(kind, data, updateExtends);
  16456. }
  16457. else {
  16458. this.makeGeometryUnique();
  16459. this.updateVerticesData(kind, data, updateExtends, false);
  16460. }
  16461. };
  16462. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  16463. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  16464. if (!this._geometry) {
  16465. return;
  16466. }
  16467. if (!makeItUnique) {
  16468. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  16469. }
  16470. else {
  16471. this.makeGeometryUnique();
  16472. this.updateVerticesDataDirectly(kind, data, offset, false);
  16473. }
  16474. };
  16475. // Mesh positions update function :
  16476. // updates the mesh positions according to the positionFunction returned values.
  16477. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  16478. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  16479. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  16480. if (computeNormals === void 0) { computeNormals = true; }
  16481. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16482. positionFunction(positions);
  16483. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16484. if (computeNormals) {
  16485. var indices = this.getIndices();
  16486. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16487. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16488. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16489. }
  16490. };
  16491. Mesh.prototype.makeGeometryUnique = function () {
  16492. if (!this._geometry) {
  16493. return;
  16494. }
  16495. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  16496. geometry.applyToMesh(this);
  16497. };
  16498. Mesh.prototype.setIndices = function (indices, totalVertices) {
  16499. if (!this._geometry) {
  16500. var vertexData = new BABYLON.VertexData();
  16501. vertexData.indices = indices;
  16502. var scene = this.getScene();
  16503. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  16504. }
  16505. else {
  16506. this._geometry.setIndices(indices, totalVertices);
  16507. }
  16508. };
  16509. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  16510. var engine = this.getScene().getEngine();
  16511. // Wireframe
  16512. var indexToBind;
  16513. if (this._unIndexed) {
  16514. indexToBind = null;
  16515. }
  16516. else {
  16517. switch (fillMode) {
  16518. case BABYLON.Material.PointFillMode:
  16519. indexToBind = null;
  16520. break;
  16521. case BABYLON.Material.WireFrameFillMode:
  16522. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  16523. break;
  16524. default:
  16525. case BABYLON.Material.TriangleFillMode:
  16526. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  16527. break;
  16528. }
  16529. }
  16530. // VBOs
  16531. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  16532. };
  16533. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  16534. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16535. return;
  16536. }
  16537. if (this.onBeforeDraw) {
  16538. this.onBeforeDraw();
  16539. }
  16540. var engine = this.getScene().getEngine();
  16541. // Draw order
  16542. switch (fillMode) {
  16543. case BABYLON.Material.PointFillMode:
  16544. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16545. break;
  16546. case BABYLON.Material.WireFrameFillMode:
  16547. if (this._unIndexed) {
  16548. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16549. }
  16550. else {
  16551. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  16552. }
  16553. break;
  16554. default:
  16555. if (this._unIndexed) {
  16556. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16557. }
  16558. else {
  16559. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  16560. }
  16561. }
  16562. };
  16563. Mesh.prototype.registerBeforeRender = function (func) {
  16564. this._onBeforeRenderCallbacks.push(func);
  16565. };
  16566. Mesh.prototype.unregisterBeforeRender = function (func) {
  16567. var index = this._onBeforeRenderCallbacks.indexOf(func);
  16568. if (index > -1) {
  16569. this._onBeforeRenderCallbacks.splice(index, 1);
  16570. }
  16571. };
  16572. Mesh.prototype.registerAfterRender = function (func) {
  16573. this._onAfterRenderCallbacks.push(func);
  16574. };
  16575. Mesh.prototype.unregisterAfterRender = function (func) {
  16576. var index = this._onAfterRenderCallbacks.indexOf(func);
  16577. if (index > -1) {
  16578. this._onAfterRenderCallbacks.splice(index, 1);
  16579. }
  16580. };
  16581. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  16582. var scene = this.getScene();
  16583. this._batchCache.mustReturn = false;
  16584. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  16585. this._batchCache.visibleInstances[subMeshId] = null;
  16586. if (this._visibleInstances) {
  16587. var currentRenderId = scene.getRenderId();
  16588. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  16589. var selfRenderId = this._renderId;
  16590. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  16591. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  16592. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  16593. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  16594. }
  16595. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  16596. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  16597. this._batchCache.mustReturn = true;
  16598. return this._batchCache;
  16599. }
  16600. if (currentRenderId !== selfRenderId) {
  16601. this._batchCache.renderSelf[subMeshId] = false;
  16602. }
  16603. }
  16604. this._renderIdForInstances[subMeshId] = currentRenderId;
  16605. }
  16606. return this._batchCache;
  16607. };
  16608. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  16609. var visibleInstances = batch.visibleInstances[subMesh._id];
  16610. var matricesCount = visibleInstances.length + 1;
  16611. var bufferSize = matricesCount * 16 * 4;
  16612. while (this._instancesBufferSize < bufferSize) {
  16613. this._instancesBufferSize *= 2;
  16614. }
  16615. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  16616. if (this._worldMatricesInstancesBuffer) {
  16617. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  16618. }
  16619. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  16620. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  16621. }
  16622. var offset = 0;
  16623. var instancesCount = 0;
  16624. var world = this.getWorldMatrix();
  16625. if (batch.renderSelf[subMesh._id]) {
  16626. world.copyToArray(this._worldMatricesInstancesArray, offset);
  16627. offset += 16;
  16628. instancesCount++;
  16629. }
  16630. if (visibleInstances) {
  16631. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  16632. var instance = visibleInstances[instanceIndex];
  16633. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  16634. offset += 16;
  16635. instancesCount++;
  16636. }
  16637. }
  16638. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  16639. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  16640. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  16641. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  16642. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  16643. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  16644. this._draw(subMesh, fillMode, instancesCount);
  16645. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  16646. };
  16647. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  16648. var scene = this.getScene();
  16649. var engine = scene.getEngine();
  16650. if (hardwareInstancedRendering) {
  16651. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  16652. }
  16653. else {
  16654. if (batch.renderSelf[subMesh._id]) {
  16655. // Draw
  16656. if (onBeforeDraw) {
  16657. onBeforeDraw(false, this.getWorldMatrix());
  16658. }
  16659. this._draw(subMesh, fillMode);
  16660. }
  16661. if (batch.visibleInstances[subMesh._id]) {
  16662. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  16663. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  16664. // World
  16665. var world = instance.getWorldMatrix();
  16666. if (onBeforeDraw) {
  16667. onBeforeDraw(true, world);
  16668. }
  16669. // Draw
  16670. this._draw(subMesh, fillMode);
  16671. }
  16672. }
  16673. }
  16674. };
  16675. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  16676. var scene = this.getScene();
  16677. // Managing instances
  16678. var batch = this._getInstancesRenderList(subMesh._id);
  16679. if (batch.mustReturn) {
  16680. return;
  16681. }
  16682. // Checking geometry state
  16683. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16684. return;
  16685. }
  16686. var callbackIndex;
  16687. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  16688. this._onBeforeRenderCallbacks[callbackIndex](this);
  16689. }
  16690. var engine = scene.getEngine();
  16691. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  16692. // Material
  16693. var effectiveMaterial = subMesh.getMaterial();
  16694. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  16695. return;
  16696. }
  16697. // Outline - step 1
  16698. var savedDepthWrite = engine.getDepthWrite();
  16699. if (this.renderOutline) {
  16700. engine.setDepthWrite(false);
  16701. scene.getOutlineRenderer().render(subMesh, batch);
  16702. engine.setDepthWrite(savedDepthWrite);
  16703. }
  16704. effectiveMaterial._preBind();
  16705. var effect = effectiveMaterial.getEffect();
  16706. // Bind
  16707. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  16708. this._bind(subMesh, effect, fillMode);
  16709. var world = this.getWorldMatrix();
  16710. effectiveMaterial.bind(world, this);
  16711. // Alpha mode
  16712. if (enableAlphaMode) {
  16713. engine.setAlphaMode(effectiveMaterial.alphaMode);
  16714. }
  16715. // Draw
  16716. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  16717. if (isInstance) {
  16718. effectiveMaterial.bindOnlyWorldMatrix(world);
  16719. }
  16720. });
  16721. // Unbind
  16722. effectiveMaterial.unbind();
  16723. // Outline - step 2
  16724. if (this.renderOutline && savedDepthWrite) {
  16725. engine.setDepthWrite(true);
  16726. engine.setColorWrite(false);
  16727. scene.getOutlineRenderer().render(subMesh, batch);
  16728. engine.setColorWrite(true);
  16729. }
  16730. // Overlay
  16731. if (this.renderOverlay) {
  16732. var currentMode = engine.getAlphaMode();
  16733. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16734. scene.getOutlineRenderer().render(subMesh, batch, true);
  16735. engine.setAlphaMode(currentMode);
  16736. }
  16737. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  16738. this._onAfterRenderCallbacks[callbackIndex](this);
  16739. }
  16740. };
  16741. Mesh.prototype.getEmittedParticleSystems = function () {
  16742. var results = new Array();
  16743. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  16744. var particleSystem = this.getScene().particleSystems[index];
  16745. if (particleSystem.emitter === this) {
  16746. results.push(particleSystem);
  16747. }
  16748. }
  16749. return results;
  16750. };
  16751. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  16752. var results = new Array();
  16753. var descendants = this.getDescendants();
  16754. descendants.push(this);
  16755. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  16756. var particleSystem = this.getScene().particleSystems[index];
  16757. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  16758. results.push(particleSystem);
  16759. }
  16760. }
  16761. return results;
  16762. };
  16763. Mesh.prototype._checkDelayState = function () {
  16764. var _this = this;
  16765. var that = this;
  16766. var scene = this.getScene();
  16767. if (this._geometry) {
  16768. this._geometry.load(scene);
  16769. }
  16770. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16771. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  16772. scene._addPendingData(that);
  16773. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  16774. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  16775. if (data instanceof ArrayBuffer) {
  16776. _this._delayLoadingFunction(data, _this);
  16777. }
  16778. else {
  16779. _this._delayLoadingFunction(JSON.parse(data), _this);
  16780. }
  16781. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16782. scene._removePendingData(_this);
  16783. }, function () { }, scene.database, getBinaryData);
  16784. }
  16785. };
  16786. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  16787. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16788. return false;
  16789. }
  16790. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  16791. return false;
  16792. }
  16793. this._checkDelayState();
  16794. return true;
  16795. };
  16796. Mesh.prototype.setMaterialByID = function (id) {
  16797. var materials = this.getScene().materials;
  16798. var index;
  16799. for (index = 0; index < materials.length; index++) {
  16800. if (materials[index].id === id) {
  16801. this.material = materials[index];
  16802. return;
  16803. }
  16804. }
  16805. // Multi
  16806. var multiMaterials = this.getScene().multiMaterials;
  16807. for (index = 0; index < multiMaterials.length; index++) {
  16808. if (multiMaterials[index].id === id) {
  16809. this.material = multiMaterials[index];
  16810. return;
  16811. }
  16812. }
  16813. };
  16814. Mesh.prototype.getAnimatables = function () {
  16815. var results = [];
  16816. if (this.material) {
  16817. results.push(this.material);
  16818. }
  16819. if (this.skeleton) {
  16820. results.push(this.skeleton);
  16821. }
  16822. return results;
  16823. };
  16824. // Geometry
  16825. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  16826. // Position
  16827. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16828. return;
  16829. }
  16830. this._resetPointsArrayCache();
  16831. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16832. var temp = [];
  16833. var index;
  16834. for (index = 0; index < data.length; index += 3) {
  16835. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  16836. }
  16837. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  16838. // Normals
  16839. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16840. return;
  16841. }
  16842. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16843. temp = [];
  16844. for (index = 0; index < data.length; index += 3) {
  16845. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  16846. }
  16847. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  16848. // flip faces?
  16849. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  16850. this.flipFaces();
  16851. }
  16852. };
  16853. // Will apply current transform to mesh and reset world matrix
  16854. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  16855. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  16856. this.scaling.copyFromFloats(1, 1, 1);
  16857. this.position.copyFromFloats(0, 0, 0);
  16858. this.rotation.copyFromFloats(0, 0, 0);
  16859. //only if quaternion is already set
  16860. if (this.rotationQuaternion) {
  16861. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  16862. }
  16863. this._worldMatrix = BABYLON.Matrix.Identity();
  16864. };
  16865. // Cache
  16866. Mesh.prototype._resetPointsArrayCache = function () {
  16867. this._positions = null;
  16868. };
  16869. Mesh.prototype._generatePointsArray = function () {
  16870. if (this._positions)
  16871. return true;
  16872. this._positions = [];
  16873. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16874. if (!data) {
  16875. return false;
  16876. }
  16877. for (var index = 0; index < data.length; index += 3) {
  16878. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  16879. }
  16880. return true;
  16881. };
  16882. // Clone
  16883. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16884. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  16885. };
  16886. // Dispose
  16887. Mesh.prototype.dispose = function (doNotRecurse) {
  16888. if (this._geometry) {
  16889. this._geometry.releaseForMesh(this, true);
  16890. }
  16891. // Instances
  16892. if (this._worldMatricesInstancesBuffer) {
  16893. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  16894. this._worldMatricesInstancesBuffer = null;
  16895. }
  16896. while (this.instances.length) {
  16897. this.instances[0].dispose();
  16898. }
  16899. _super.prototype.dispose.call(this, doNotRecurse);
  16900. };
  16901. // Geometric tools
  16902. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  16903. var _this = this;
  16904. var scene = this.getScene();
  16905. var onload = function (img) {
  16906. // Getting height map data
  16907. var canvas = document.createElement("canvas");
  16908. var context = canvas.getContext("2d");
  16909. var heightMapWidth = img.width;
  16910. var heightMapHeight = img.height;
  16911. canvas.width = heightMapWidth;
  16912. canvas.height = heightMapHeight;
  16913. context.drawImage(img, 0, 0);
  16914. // Create VertexData from map data
  16915. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16916. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  16917. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  16918. //execute success callback, if set
  16919. if (onSuccess) {
  16920. onSuccess(_this);
  16921. }
  16922. };
  16923. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16924. };
  16925. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  16926. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  16927. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  16928. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16929. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  16930. return;
  16931. }
  16932. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16933. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16934. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16935. var position = BABYLON.Vector3.Zero();
  16936. var normal = BABYLON.Vector3.Zero();
  16937. var uv = BABYLON.Vector2.Zero();
  16938. for (var index = 0; index < positions.length; index += 3) {
  16939. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  16940. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  16941. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  16942. // Compute height
  16943. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  16944. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  16945. var pos = (u + v * heightMapWidth) * 4;
  16946. var r = buffer[pos] / 255.0;
  16947. var g = buffer[pos + 1] / 255.0;
  16948. var b = buffer[pos + 2] / 255.0;
  16949. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16950. normal.normalize();
  16951. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  16952. position = position.add(normal);
  16953. position.toArray(positions, index);
  16954. }
  16955. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  16956. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  16957. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16958. };
  16959. Mesh.prototype.convertToFlatShadedMesh = function () {
  16960. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  16961. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16962. var kinds = this.getVerticesDataKinds();
  16963. var vbs = [];
  16964. var data = [];
  16965. var newdata = [];
  16966. var updatableNormals = false;
  16967. var kindIndex;
  16968. var kind;
  16969. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16970. kind = kinds[kindIndex];
  16971. var vertexBuffer = this.getVertexBuffer(kind);
  16972. if (kind === BABYLON.VertexBuffer.NormalKind) {
  16973. updatableNormals = vertexBuffer.isUpdatable();
  16974. kinds.splice(kindIndex, 1);
  16975. kindIndex--;
  16976. continue;
  16977. }
  16978. vbs[kind] = vertexBuffer;
  16979. data[kind] = vbs[kind].getData();
  16980. newdata[kind] = [];
  16981. }
  16982. // Save previous submeshes
  16983. var previousSubmeshes = this.subMeshes.slice(0);
  16984. var indices = this.getIndices();
  16985. var totalIndices = this.getTotalIndices();
  16986. // Generating unique vertices per face
  16987. var index;
  16988. for (index = 0; index < totalIndices; index++) {
  16989. var vertexIndex = indices[index];
  16990. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16991. kind = kinds[kindIndex];
  16992. var stride = vbs[kind].getStrideSize();
  16993. for (var offset = 0; offset < stride; offset++) {
  16994. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16995. }
  16996. }
  16997. }
  16998. // Updating faces & normal
  16999. var normals = [];
  17000. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17001. for (index = 0; index < totalIndices; index += 3) {
  17002. indices[index] = index;
  17003. indices[index + 1] = index + 1;
  17004. indices[index + 2] = index + 2;
  17005. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17006. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17007. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17008. var p1p2 = p1.subtract(p2);
  17009. var p3p2 = p3.subtract(p2);
  17010. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17011. // Store same normals for every vertex
  17012. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17013. normals.push(normal.x);
  17014. normals.push(normal.y);
  17015. normals.push(normal.z);
  17016. }
  17017. }
  17018. this.setIndices(indices);
  17019. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17020. // Updating vertex buffers
  17021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17022. kind = kinds[kindIndex];
  17023. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17024. }
  17025. // Updating submeshes
  17026. this.releaseSubMeshes();
  17027. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17028. var previousOne = previousSubmeshes[submeshIndex];
  17029. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17030. }
  17031. this.synchronizeInstances();
  17032. };
  17033. Mesh.prototype.convertToUnIndexedMesh = function () {
  17034. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17035. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17036. var kinds = this.getVerticesDataKinds();
  17037. var vbs = [];
  17038. var data = [];
  17039. var newdata = [];
  17040. var updatableNormals = false;
  17041. var kindIndex;
  17042. var kind;
  17043. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17044. kind = kinds[kindIndex];
  17045. var vertexBuffer = this.getVertexBuffer(kind);
  17046. vbs[kind] = vertexBuffer;
  17047. data[kind] = vbs[kind].getData();
  17048. newdata[kind] = [];
  17049. }
  17050. // Save previous submeshes
  17051. var previousSubmeshes = this.subMeshes.slice(0);
  17052. var indices = this.getIndices();
  17053. var totalIndices = this.getTotalIndices();
  17054. // Generating unique vertices per face
  17055. var index;
  17056. for (index = 0; index < totalIndices; index++) {
  17057. var vertexIndex = indices[index];
  17058. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17059. kind = kinds[kindIndex];
  17060. var stride = vbs[kind].getStrideSize();
  17061. for (var offset = 0; offset < stride; offset++) {
  17062. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17063. }
  17064. }
  17065. }
  17066. // Updating indices
  17067. for (index = 0; index < totalIndices; index += 3) {
  17068. indices[index] = index;
  17069. indices[index + 1] = index + 1;
  17070. indices[index + 2] = index + 2;
  17071. }
  17072. this.setIndices(indices);
  17073. // Updating vertex buffers
  17074. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17075. kind = kinds[kindIndex];
  17076. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17077. }
  17078. // Updating submeshes
  17079. this.releaseSubMeshes();
  17080. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17081. var previousOne = previousSubmeshes[submeshIndex];
  17082. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17083. }
  17084. this._unIndexed = true;
  17085. this.synchronizeInstances();
  17086. };
  17087. // will inverse faces orientations, and invert normals too if specified
  17088. Mesh.prototype.flipFaces = function (flipNormals) {
  17089. if (flipNormals === void 0) { flipNormals = false; }
  17090. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17091. var i;
  17092. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17093. for (i = 0; i < vertex_data.normals.length; i++) {
  17094. vertex_data.normals[i] *= -1;
  17095. }
  17096. }
  17097. var temp;
  17098. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17099. // reassign indices
  17100. temp = vertex_data.indices[i + 1];
  17101. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17102. vertex_data.indices[i + 2] = temp;
  17103. }
  17104. vertex_data.applyToMesh(this);
  17105. };
  17106. // Instances
  17107. Mesh.prototype.createInstance = function (name) {
  17108. return new BABYLON.InstancedMesh(name, this);
  17109. };
  17110. Mesh.prototype.synchronizeInstances = function () {
  17111. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17112. var instance = this.instances[instanceIndex];
  17113. instance._syncSubMeshes();
  17114. }
  17115. };
  17116. /**
  17117. * Simplify the mesh according to the given array of settings.
  17118. * Function will return immediately and will simplify async.
  17119. * @param settings a collection of simplification settings.
  17120. * @param parallelProcessing should all levels calculate parallel or one after the other.
  17121. * @param type the type of simplification to run.
  17122. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  17123. */
  17124. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  17125. if (parallelProcessing === void 0) { parallelProcessing = true; }
  17126. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  17127. this.getScene().simplificationQueue.addTask({
  17128. settings: settings,
  17129. parallelProcessing: parallelProcessing,
  17130. mesh: this,
  17131. simplificationType: simplificationType,
  17132. successCallback: successCallback
  17133. });
  17134. };
  17135. /**
  17136. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  17137. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  17138. * This should be used together with the simplification to avoid disappearing triangles.
  17139. * @param successCallback an optional success callback to be called after the optimization finished.
  17140. */
  17141. Mesh.prototype.optimizeIndices = function (successCallback) {
  17142. var _this = this;
  17143. var indices = this.getIndices();
  17144. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17145. var vectorPositions = [];
  17146. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  17147. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  17148. }
  17149. var dupes = [];
  17150. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  17151. var realPos = vectorPositions.length - 1 - iteration;
  17152. var testedPosition = vectorPositions[realPos];
  17153. for (var j = 0; j < realPos; ++j) {
  17154. var againstPosition = vectorPositions[j];
  17155. if (testedPosition.equals(againstPosition)) {
  17156. dupes[realPos] = j;
  17157. break;
  17158. }
  17159. }
  17160. }, function () {
  17161. for (var i = 0; i < indices.length; ++i) {
  17162. indices[i] = dupes[indices[i]] || indices[i];
  17163. }
  17164. //indices are now reordered
  17165. var originalSubMeshes = _this.subMeshes.slice(0);
  17166. _this.setIndices(indices);
  17167. _this.subMeshes = originalSubMeshes;
  17168. if (successCallback) {
  17169. successCallback(_this);
  17170. }
  17171. });
  17172. };
  17173. // Statics
  17174. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  17175. var mesh = new Mesh(parsedMesh.name, scene);
  17176. mesh.id = parsedMesh.id;
  17177. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17178. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17179. if (parsedMesh.rotationQuaternion) {
  17180. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17181. }
  17182. else if (parsedMesh.rotation) {
  17183. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17184. }
  17185. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17186. if (parsedMesh.localMatrix) {
  17187. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17188. }
  17189. else if (parsedMesh.pivotMatrix) {
  17190. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17191. }
  17192. mesh.setEnabled(parsedMesh.isEnabled);
  17193. mesh.isVisible = parsedMesh.isVisible;
  17194. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17195. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17196. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17197. if (parsedMesh.applyFog !== undefined) {
  17198. mesh.applyFog = parsedMesh.applyFog;
  17199. }
  17200. if (parsedMesh.pickable !== undefined) {
  17201. mesh.isPickable = parsedMesh.pickable;
  17202. }
  17203. if (parsedMesh.alphaIndex !== undefined) {
  17204. mesh.alphaIndex = parsedMesh.alphaIndex;
  17205. }
  17206. mesh.receiveShadows = parsedMesh.receiveShadows;
  17207. mesh.billboardMode = parsedMesh.billboardMode;
  17208. if (parsedMesh.visibility !== undefined) {
  17209. mesh.visibility = parsedMesh.visibility;
  17210. }
  17211. mesh.checkCollisions = parsedMesh.checkCollisions;
  17212. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17213. // freezeWorldMatrix
  17214. if (parsedMesh.freezeWorldMatrix) {
  17215. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  17216. }
  17217. // Parent
  17218. if (parsedMesh.parentId) {
  17219. mesh._waitingParentId = parsedMesh.parentId;
  17220. }
  17221. // Actions
  17222. if (parsedMesh.actions !== undefined) {
  17223. mesh._waitingActions = parsedMesh.actions;
  17224. }
  17225. // Geometry
  17226. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17227. if (parsedMesh.delayLoadingFile) {
  17228. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17229. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17230. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17231. if (parsedMesh._binaryInfo) {
  17232. mesh._binaryInfo = parsedMesh._binaryInfo;
  17233. }
  17234. mesh._delayInfo = [];
  17235. if (parsedMesh.hasUVs) {
  17236. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17237. }
  17238. if (parsedMesh.hasUVs2) {
  17239. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17240. }
  17241. if (parsedMesh.hasUVs3) {
  17242. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  17243. }
  17244. if (parsedMesh.hasUVs4) {
  17245. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  17246. }
  17247. if (parsedMesh.hasUVs5) {
  17248. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  17249. }
  17250. if (parsedMesh.hasUVs6) {
  17251. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  17252. }
  17253. if (parsedMesh.hasColors) {
  17254. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17255. }
  17256. if (parsedMesh.hasMatricesIndices) {
  17257. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17258. }
  17259. if (parsedMesh.hasMatricesWeights) {
  17260. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17261. }
  17262. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  17263. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17264. mesh._checkDelayState();
  17265. }
  17266. }
  17267. else {
  17268. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  17269. }
  17270. // Material
  17271. if (parsedMesh.materialId) {
  17272. mesh.setMaterialByID(parsedMesh.materialId);
  17273. }
  17274. else {
  17275. mesh.material = null;
  17276. }
  17277. // Skeleton
  17278. if (parsedMesh.skeletonId > -1) {
  17279. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17280. if (parsedMesh.numBoneInfluencers) {
  17281. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  17282. }
  17283. }
  17284. // Animations
  17285. if (parsedMesh.animations) {
  17286. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17287. var parsedAnimation = parsedMesh.animations[animationIndex];
  17288. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17289. }
  17290. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  17291. }
  17292. if (parsedMesh.autoAnimate) {
  17293. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  17294. }
  17295. // Layer Mask
  17296. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17297. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17298. }
  17299. else {
  17300. mesh.layerMask = 0x0FFFFFFF;
  17301. }
  17302. // Instances
  17303. if (parsedMesh.instances) {
  17304. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17305. var parsedInstance = parsedMesh.instances[index];
  17306. var instance = mesh.createInstance(parsedInstance.name);
  17307. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17308. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17309. if (parsedInstance.rotationQuaternion) {
  17310. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17311. }
  17312. else if (parsedInstance.rotation) {
  17313. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17314. }
  17315. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17316. instance.checkCollisions = mesh.checkCollisions;
  17317. if (parsedMesh.animations) {
  17318. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17319. parsedAnimation = parsedMesh.animations[animationIndex];
  17320. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17321. }
  17322. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  17323. }
  17324. }
  17325. }
  17326. return mesh;
  17327. };
  17328. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  17329. return BABYLON.MeshBuilder.CreateRibbon(name, {
  17330. pathArray: pathArray,
  17331. closeArray: closeArray,
  17332. closePath: closePath,
  17333. offset: offset,
  17334. updatable: updatable,
  17335. sideOrientation: sideOrientation,
  17336. instance: instance
  17337. }, scene);
  17338. };
  17339. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  17340. var options = {
  17341. radius: radius,
  17342. tessellation: tessellation,
  17343. sideOrientation: sideOrientation,
  17344. updatable: updatable
  17345. };
  17346. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  17347. };
  17348. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  17349. var options = {
  17350. size: size,
  17351. sideOrientation: sideOrientation,
  17352. updatable: updatable
  17353. };
  17354. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  17355. };
  17356. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  17357. var options = {
  17358. segments: segments,
  17359. diameterX: diameter,
  17360. diameterY: diameter,
  17361. diameterZ: diameter,
  17362. sideOrientation: sideOrientation,
  17363. updatable: updatable
  17364. };
  17365. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  17366. };
  17367. // Cylinder and cone
  17368. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  17369. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  17370. if (scene !== undefined) {
  17371. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  17372. updatable = scene;
  17373. }
  17374. scene = subdivisions;
  17375. subdivisions = 1;
  17376. }
  17377. var options = {
  17378. height: height,
  17379. diameterTop: diameterTop,
  17380. diameterBottom: diameterBottom,
  17381. tessellation: tessellation,
  17382. subdivisions: subdivisions,
  17383. sideOrientation: sideOrientation,
  17384. updatable: updatable
  17385. };
  17386. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  17387. };
  17388. // Torus (Code from SharpDX.org)
  17389. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  17390. var options = {
  17391. diameter: diameter,
  17392. thickness: thickness,
  17393. tessellation: tessellation,
  17394. sideOrientation: sideOrientation,
  17395. updatable: updatable
  17396. };
  17397. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  17398. };
  17399. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  17400. var options = {
  17401. radius: radius,
  17402. tube: tube,
  17403. radialSegments: radialSegments,
  17404. tubularSegments: tubularSegments,
  17405. p: p,
  17406. q: q,
  17407. sideOrientation: sideOrientation,
  17408. updatable: updatable
  17409. };
  17410. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  17411. };
  17412. // Lines
  17413. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  17414. var options = {
  17415. points: points,
  17416. updatable: updatable,
  17417. instance: instance
  17418. };
  17419. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  17420. };
  17421. // Dashed Lines
  17422. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  17423. var options = {
  17424. points: points,
  17425. dashSize: dashSize,
  17426. gapSize: gapSize,
  17427. dashNb: dashNb,
  17428. updatable: updatable
  17429. };
  17430. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  17431. };
  17432. // Extrusion
  17433. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  17434. var options = {
  17435. shape: shape,
  17436. path: path,
  17437. scale: scale,
  17438. rotation: rotation,
  17439. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17440. sideOrientation: sideOrientation,
  17441. instance: instance,
  17442. updatable: updatable
  17443. };
  17444. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  17445. };
  17446. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  17447. var options = {
  17448. shape: shape,
  17449. path: path,
  17450. scaleFunction: scaleFunction,
  17451. rotationFunction: rotationFunction,
  17452. ribbonCloseArray: ribbonCloseArray,
  17453. ribbonClosePath: ribbonClosePath,
  17454. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17455. sideOrientation: sideOrientation,
  17456. instance: instance,
  17457. updatable: updatable
  17458. };
  17459. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  17460. };
  17461. // Lathe
  17462. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  17463. var options = {
  17464. shape: shape,
  17465. radius: radius,
  17466. tessellation: tessellation,
  17467. sideOrientation: sideOrientation,
  17468. updatable: updatable
  17469. };
  17470. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  17471. };
  17472. // Plane & ground
  17473. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  17474. var options = {
  17475. size: size,
  17476. width: size,
  17477. height: size,
  17478. sideOrientation: sideOrientation,
  17479. updatable: updatable
  17480. };
  17481. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  17482. };
  17483. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  17484. var options = {
  17485. width: width,
  17486. height: height,
  17487. subdivisions: subdivisions,
  17488. updatable: updatable
  17489. };
  17490. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  17491. };
  17492. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  17493. var options = {
  17494. xmin: xmin,
  17495. zmin: zmin,
  17496. xmax: xmax,
  17497. zmax: zmax,
  17498. subdivisions: subdivisions,
  17499. precision: precision,
  17500. updatable: updatable
  17501. };
  17502. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  17503. };
  17504. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  17505. var options = {
  17506. width: width,
  17507. height: height,
  17508. subdivisions: subdivisions,
  17509. minHeight: minHeight,
  17510. maxHeight: maxHeight,
  17511. updatable: updatable,
  17512. onReady: onReady
  17513. };
  17514. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  17515. };
  17516. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  17517. var options = {
  17518. path: path,
  17519. radius: radius,
  17520. tessellation: tessellation,
  17521. radiusFunction: radiusFunction,
  17522. arc: 1,
  17523. cap: cap,
  17524. updatable: updatable,
  17525. sideOrientation: sideOrientation,
  17526. instance: instance
  17527. };
  17528. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  17529. };
  17530. Mesh.CreatePolyhedron = function (name, options, scene) {
  17531. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  17532. };
  17533. Mesh.CreateIcoSphere = function (name, options, scene) {
  17534. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  17535. };
  17536. // Decals
  17537. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  17538. var options = {
  17539. position: position,
  17540. normal: normal,
  17541. size: size,
  17542. angle: angle
  17543. };
  17544. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  17545. };
  17546. // Skeletons
  17547. /**
  17548. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  17549. */
  17550. Mesh.prototype.setPositionsForCPUSkinning = function () {
  17551. var source;
  17552. if (!this._sourcePositions) {
  17553. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17554. this._sourcePositions = new Float32Array(source);
  17555. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  17556. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  17557. }
  17558. }
  17559. return this._sourcePositions;
  17560. };
  17561. /**
  17562. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  17563. */
  17564. Mesh.prototype.setNormalsForCPUSkinning = function () {
  17565. var source;
  17566. if (!this._sourceNormals) {
  17567. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17568. this._sourceNormals = new Float32Array(source);
  17569. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  17570. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  17571. }
  17572. }
  17573. return this._sourceNormals;
  17574. };
  17575. /**
  17576. * Update the vertex buffers by applying transformation from the bones
  17577. * @param {skeleton} skeleton to apply
  17578. */
  17579. Mesh.prototype.applySkeleton = function (skeleton) {
  17580. if (!this.geometry) {
  17581. return;
  17582. }
  17583. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  17584. return;
  17585. }
  17586. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  17587. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17588. return this;
  17589. }
  17590. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17591. return this;
  17592. }
  17593. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17594. return this;
  17595. }
  17596. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17597. return this;
  17598. }
  17599. if (!this._sourcePositions) {
  17600. this.setPositionsForCPUSkinning();
  17601. }
  17602. if (!this._sourceNormals) {
  17603. this.setNormalsForCPUSkinning();
  17604. }
  17605. // positionsData checks for not being Float32Array will only pass at most once
  17606. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17607. if (!(positionsData instanceof Float32Array)) {
  17608. positionsData = new Float32Array(positionsData);
  17609. }
  17610. // normalsData checks for not being Float32Array will only pass at most once
  17611. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17612. if (!(normalsData instanceof Float32Array)) {
  17613. normalsData = new Float32Array(normalsData);
  17614. }
  17615. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17616. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17617. var needExtras = this.numBoneInfluencers > 4;
  17618. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  17619. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  17620. var skeletonMatrices = skeleton.getTransformMatrices(this);
  17621. var tempVector3 = BABYLON.Vector3.Zero();
  17622. var finalMatrix = new BABYLON.Matrix();
  17623. var tempMatrix = new BABYLON.Matrix();
  17624. var matWeightIdx = 0;
  17625. var inf;
  17626. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  17627. var weight;
  17628. for (inf = 0; inf < 4; inf++) {
  17629. weight = matricesWeightsData[matWeightIdx + inf];
  17630. if (weight > 0) {
  17631. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  17632. finalMatrix.addToSelf(tempMatrix);
  17633. }
  17634. else
  17635. break;
  17636. }
  17637. if (needExtras) {
  17638. for (inf = 0; inf < 4; inf++) {
  17639. weight = matricesWeightsExtraData[matWeightIdx + inf];
  17640. if (weight > 0) {
  17641. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  17642. finalMatrix.addToSelf(tempMatrix);
  17643. }
  17644. else
  17645. break;
  17646. }
  17647. }
  17648. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  17649. tempVector3.toArray(positionsData, index);
  17650. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  17651. tempVector3.toArray(normalsData, index);
  17652. finalMatrix.reset();
  17653. }
  17654. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  17655. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  17656. return this;
  17657. };
  17658. // Tools
  17659. Mesh.MinMax = function (meshes) {
  17660. var minVector = null;
  17661. var maxVector = null;
  17662. for (var i in meshes) {
  17663. var mesh = meshes[i];
  17664. var boundingBox = mesh.getBoundingInfo().boundingBox;
  17665. if (!minVector) {
  17666. minVector = boundingBox.minimumWorld;
  17667. maxVector = boundingBox.maximumWorld;
  17668. continue;
  17669. }
  17670. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  17671. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  17672. }
  17673. return {
  17674. min: minVector,
  17675. max: maxVector
  17676. };
  17677. };
  17678. Mesh.Center = function (meshesOrMinMaxVector) {
  17679. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  17680. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  17681. };
  17682. /**
  17683. * Merge the array of meshes into a single mesh for performance reasons.
  17684. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  17685. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  17686. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  17687. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  17688. */
  17689. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  17690. if (disposeSource === void 0) { disposeSource = true; }
  17691. var index;
  17692. if (!allow32BitsIndices) {
  17693. var totalVertices = 0;
  17694. // Counting vertices
  17695. for (index = 0; index < meshes.length; index++) {
  17696. if (meshes[index]) {
  17697. totalVertices += meshes[index].getTotalVertices();
  17698. if (totalVertices > 65536) {
  17699. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  17700. return null;
  17701. }
  17702. }
  17703. }
  17704. }
  17705. // Merge
  17706. var vertexData;
  17707. var otherVertexData;
  17708. var source;
  17709. for (index = 0; index < meshes.length; index++) {
  17710. if (meshes[index]) {
  17711. meshes[index].computeWorldMatrix(true);
  17712. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  17713. otherVertexData.transform(meshes[index].getWorldMatrix());
  17714. if (vertexData) {
  17715. vertexData.merge(otherVertexData);
  17716. }
  17717. else {
  17718. vertexData = otherVertexData;
  17719. source = meshes[index];
  17720. }
  17721. }
  17722. }
  17723. if (!meshSubclass) {
  17724. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  17725. }
  17726. vertexData.applyToMesh(meshSubclass);
  17727. // Setting properties
  17728. meshSubclass.material = source.material;
  17729. meshSubclass.checkCollisions = source.checkCollisions;
  17730. // Cleaning
  17731. if (disposeSource) {
  17732. for (index = 0; index < meshes.length; index++) {
  17733. if (meshes[index]) {
  17734. meshes[index].dispose();
  17735. }
  17736. }
  17737. }
  17738. return meshSubclass;
  17739. };
  17740. // Consts
  17741. Mesh._FRONTSIDE = 0;
  17742. Mesh._BACKSIDE = 1;
  17743. Mesh._DOUBLESIDE = 2;
  17744. Mesh._DEFAULTSIDE = 0;
  17745. Mesh._NO_CAP = 0;
  17746. Mesh._CAP_START = 1;
  17747. Mesh._CAP_END = 2;
  17748. Mesh._CAP_ALL = 3;
  17749. return Mesh;
  17750. })(BABYLON.AbstractMesh);
  17751. BABYLON.Mesh = Mesh;
  17752. })(BABYLON || (BABYLON = {}));
  17753. var BABYLON;
  17754. (function (BABYLON) {
  17755. var SubMesh = (function () {
  17756. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  17757. if (createBoundingBox === void 0) { createBoundingBox = true; }
  17758. this.materialIndex = materialIndex;
  17759. this.verticesStart = verticesStart;
  17760. this.verticesCount = verticesCount;
  17761. this.indexStart = indexStart;
  17762. this.indexCount = indexCount;
  17763. this._renderId = 0;
  17764. this._mesh = mesh;
  17765. this._renderingMesh = renderingMesh || mesh;
  17766. mesh.subMeshes.push(this);
  17767. this._trianglePlanes = [];
  17768. this._id = mesh.subMeshes.length - 1;
  17769. if (createBoundingBox) {
  17770. this.refreshBoundingInfo();
  17771. mesh.computeWorldMatrix(true);
  17772. }
  17773. }
  17774. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  17775. get: function () {
  17776. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  17777. },
  17778. enumerable: true,
  17779. configurable: true
  17780. });
  17781. SubMesh.prototype.getBoundingInfo = function () {
  17782. if (this.IsGlobal) {
  17783. return this._mesh.getBoundingInfo();
  17784. }
  17785. return this._boundingInfo;
  17786. };
  17787. SubMesh.prototype.getMesh = function () {
  17788. return this._mesh;
  17789. };
  17790. SubMesh.prototype.getRenderingMesh = function () {
  17791. return this._renderingMesh;
  17792. };
  17793. SubMesh.prototype.getMaterial = function () {
  17794. var rootMaterial = this._renderingMesh.material;
  17795. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  17796. var multiMaterial = rootMaterial;
  17797. return multiMaterial.getSubMaterial(this.materialIndex);
  17798. }
  17799. if (!rootMaterial) {
  17800. return this._mesh.getScene().defaultMaterial;
  17801. }
  17802. return rootMaterial;
  17803. };
  17804. // Methods
  17805. SubMesh.prototype.refreshBoundingInfo = function () {
  17806. this._lastColliderWorldVertices = null;
  17807. if (this.IsGlobal) {
  17808. return;
  17809. }
  17810. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17811. if (!data) {
  17812. this._boundingInfo = this._mesh._boundingInfo;
  17813. return;
  17814. }
  17815. var indices = this._renderingMesh.getIndices();
  17816. var extend;
  17817. //is this the only submesh?
  17818. if (this.indexStart === 0 && this.indexCount === indices.length) {
  17819. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  17820. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  17821. }
  17822. else {
  17823. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  17824. }
  17825. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17826. };
  17827. SubMesh.prototype._checkCollision = function (collider) {
  17828. return this.getBoundingInfo()._checkCollision(collider);
  17829. };
  17830. SubMesh.prototype.updateBoundingInfo = function (world) {
  17831. if (!this.getBoundingInfo()) {
  17832. this.refreshBoundingInfo();
  17833. }
  17834. this.getBoundingInfo().update(world);
  17835. };
  17836. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  17837. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  17838. };
  17839. SubMesh.prototype.render = function (enableAlphaMode) {
  17840. this._renderingMesh.render(this, enableAlphaMode);
  17841. };
  17842. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  17843. if (!this._linesIndexBuffer) {
  17844. var linesIndices = [];
  17845. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  17846. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  17847. }
  17848. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  17849. this.linesIndexCount = linesIndices.length;
  17850. }
  17851. return this._linesIndexBuffer;
  17852. };
  17853. SubMesh.prototype.canIntersects = function (ray) {
  17854. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  17855. };
  17856. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  17857. var intersectInfo = null;
  17858. // Triangles test
  17859. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  17860. var p0 = positions[indices[index]];
  17861. var p1 = positions[indices[index + 1]];
  17862. var p2 = positions[indices[index + 2]];
  17863. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  17864. if (currentIntersectInfo) {
  17865. if (currentIntersectInfo.distance < 0) {
  17866. continue;
  17867. }
  17868. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17869. intersectInfo = currentIntersectInfo;
  17870. intersectInfo.faceId = index / 3;
  17871. if (fastCheck) {
  17872. break;
  17873. }
  17874. }
  17875. }
  17876. }
  17877. return intersectInfo;
  17878. };
  17879. // Clone
  17880. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  17881. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  17882. if (!this.IsGlobal) {
  17883. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  17884. }
  17885. return result;
  17886. };
  17887. // Dispose
  17888. SubMesh.prototype.dispose = function () {
  17889. if (this._linesIndexBuffer) {
  17890. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  17891. this._linesIndexBuffer = null;
  17892. }
  17893. // Remove from mesh
  17894. var index = this._mesh.subMeshes.indexOf(this);
  17895. this._mesh.subMeshes.splice(index, 1);
  17896. };
  17897. // Statics
  17898. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  17899. var minVertexIndex = Number.MAX_VALUE;
  17900. var maxVertexIndex = -Number.MAX_VALUE;
  17901. renderingMesh = renderingMesh || mesh;
  17902. var indices = renderingMesh.getIndices();
  17903. for (var index = startIndex; index < startIndex + indexCount; index++) {
  17904. var vertexIndex = indices[index];
  17905. if (vertexIndex < minVertexIndex)
  17906. minVertexIndex = vertexIndex;
  17907. if (vertexIndex > maxVertexIndex)
  17908. maxVertexIndex = vertexIndex;
  17909. }
  17910. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  17911. };
  17912. return SubMesh;
  17913. })();
  17914. BABYLON.SubMesh = SubMesh;
  17915. })(BABYLON || (BABYLON = {}));
  17916. var BABYLON;
  17917. (function (BABYLON) {
  17918. var MeshBuilder = (function () {
  17919. function MeshBuilder() {
  17920. }
  17921. /**
  17922. * Creates a box mesh.
  17923. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  17924. * The parameter "size" sets the size (float) of each box side (default 1).
  17925. * You can set some different box dimensions by using the parameters "width", "height" and "depth" (all by default have the same value than "size").
  17926. * 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).
  17927. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  17928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17929. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17930. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17931. */
  17932. MeshBuilder.CreateBox = function (name, options, scene) {
  17933. var box = new BABYLON.Mesh(name, scene);
  17934. var vertexData = BABYLON.VertexData.CreateBox(options);
  17935. vertexData.applyToMesh(box, options.updatable);
  17936. return box;
  17937. };
  17938. /**
  17939. * Creates a sphere mesh.
  17940. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  17941. * The parameter "diameter" sets the diameter size (float) of the sphere (default 1).
  17942. * 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").
  17943. * The parameter "segments" sets the sphere number of horizontal stripes (positive integer, default 32).
  17944. * 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
  17945. * 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).
  17946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17947. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17948. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17949. */
  17950. MeshBuilder.CreateSphere = function (name, options, scene) {
  17951. var sphere = new BABYLON.Mesh(name, scene);
  17952. var vertexData = BABYLON.VertexData.CreateSphere(options);
  17953. vertexData.applyToMesh(sphere, options.updatable);
  17954. return sphere;
  17955. };
  17956. /**
  17957. * Creates a plane polygonal mesh. By default, this is a disc.
  17958. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  17959. * The parameter "radius" sets the radius size (float) of the polygon (default 0.5).
  17960. * 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.
  17961. * 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
  17962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17964. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17965. */
  17966. MeshBuilder.CreateDisc = function (name, options, scene) {
  17967. var disc = new BABYLON.Mesh(name, scene);
  17968. var vertexData = BABYLON.VertexData.CreateDisc(options);
  17969. vertexData.applyToMesh(disc, options.updatable);
  17970. return disc;
  17971. };
  17972. /**
  17973. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  17974. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  17975. * The parameter "radius" sets the radius size (float) of the icosphere (default 1).
  17976. * 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").
  17977. * The parameter "subdivisions" sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  17978. * 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.
  17979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17981. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17982. */
  17983. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  17984. var sphere = new BABYLON.Mesh(name, scene);
  17985. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  17986. vertexData.applyToMesh(sphere, options.updatable);
  17987. return sphere;
  17988. };
  17989. ;
  17990. /**
  17991. * Creates a ribbon mesh.
  17992. * 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.
  17993. *
  17994. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  17995. * The parameter "pathArray" is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  17996. * The parameter "closeArray" (boolean, default false) creates a seam between the first and the last paths of the path array.
  17997. * The parameter "closePath" (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  17998. * The 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
  17999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18000. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18001. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18002. */
  18003. MeshBuilder.CreateRibbon = function (name, options, scene) {
  18004. var pathArray = options.pathArray;
  18005. var closeArray = options.closeArray;
  18006. var closePath = options.closePath;
  18007. var offset = options.offset;
  18008. var sideOrientation = options.sideOrientation;
  18009. var instance = options.instance;
  18010. var updatable = options.updatable;
  18011. if (instance) {
  18012. // positionFunction : ribbon case
  18013. // only pathArray and sideOrientation parameters are taken into account for positions update
  18014. var positionFunction = function (positions) {
  18015. var minlg = pathArray[0].length;
  18016. var i = 0;
  18017. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  18018. for (var si = 1; si <= ns; si++) {
  18019. for (var p = 0; p < pathArray.length; p++) {
  18020. var path = pathArray[p];
  18021. var l = path.length;
  18022. minlg = (minlg < l) ? minlg : l;
  18023. var j = 0;
  18024. while (j < minlg) {
  18025. positions[i] = path[j].x;
  18026. positions[i + 1] = path[j].y;
  18027. positions[i + 2] = path[j].z;
  18028. j++;
  18029. i += 3;
  18030. }
  18031. if (instance._closePath) {
  18032. positions[i] = path[0].x;
  18033. positions[i + 1] = path[0].y;
  18034. positions[i + 2] = path[0].z;
  18035. i += 3;
  18036. }
  18037. }
  18038. }
  18039. };
  18040. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18041. positionFunction(positions);
  18042. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18043. if (!(instance.areNormalsFrozen)) {
  18044. var indices = instance.getIndices();
  18045. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18046. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18047. if (instance._closePath) {
  18048. var indexFirst = 0;
  18049. var indexLast = 0;
  18050. for (var p = 0; p < pathArray.length; p++) {
  18051. indexFirst = instance._idx[p] * 3;
  18052. if (p + 1 < pathArray.length) {
  18053. indexLast = (instance._idx[p + 1] - 1) * 3;
  18054. }
  18055. else {
  18056. indexLast = normals.length - 3;
  18057. }
  18058. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  18059. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  18060. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  18061. normals[indexLast] = normals[indexFirst];
  18062. normals[indexLast + 1] = normals[indexFirst + 1];
  18063. normals[indexLast + 2] = normals[indexFirst + 2];
  18064. }
  18065. }
  18066. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18067. }
  18068. return instance;
  18069. }
  18070. else {
  18071. var ribbon = new BABYLON.Mesh(name, scene);
  18072. ribbon.sideOrientation = sideOrientation;
  18073. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  18074. if (closePath) {
  18075. ribbon._idx = vertexData._idx;
  18076. }
  18077. ribbon._closePath = closePath;
  18078. ribbon._closeArray = closeArray;
  18079. vertexData.applyToMesh(ribbon, updatable);
  18080. return ribbon;
  18081. }
  18082. };
  18083. /**
  18084. * Creates a cylinder or a cone mesh.
  18085. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  18086. * The parameter "height" sets the height size (float) of the cylinder/cone (float, default 2).
  18087. * The parameter "diameter" sets the diameter of the top and bottom cap at once (float, default 1).
  18088. * 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.
  18089. * The parameter "tessellation" sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18090. * The parameter "subdivisions" sets the number of rings along the cylinder height (positive integer, default 1).
  18091. * The parameter "hasRings" (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  18092. * The parameter "enclose" (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  18093. * The parameter "arc" (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  18094. * 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).
  18095. * 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
  18096. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  18097. * 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
  18098. * 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.
  18099. * If enclose is false, a ring surface is one element.
  18100. * If enclose true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  18101. * 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
  18102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18104. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18105. */
  18106. MeshBuilder.CreateCylinder = function (name, options, scene) {
  18107. var cylinder = new BABYLON.Mesh(name, scene);
  18108. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  18109. vertexData.applyToMesh(cylinder, options.updatable);
  18110. return cylinder;
  18111. };
  18112. /**
  18113. * Creates a torus mesh.
  18114. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  18115. * The parameter "diameter" sets the diameter size (float) of the torus (default 1).
  18116. * The parameter "thickness" sets the diameter size of the tube of the torus (float, default 0.5).
  18117. * The parameter "tessellation" sets the number of torus sides (postive integer, default 16).
  18118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18119. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18120. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18121. */
  18122. MeshBuilder.CreateTorus = function (name, options, scene) {
  18123. var torus = new BABYLON.Mesh(name, scene);
  18124. var vertexData = BABYLON.VertexData.CreateTorus(options);
  18125. vertexData.applyToMesh(torus, options.updatable);
  18126. return torus;
  18127. };
  18128. /**
  18129. * Creates a torus knot mesh.
  18130. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  18131. * The parameter "radius" sets the global radius size (float) of the torus knot (default 2).
  18132. * The parameter "radialSegments" sets the number of sides on each tube segments (positive integer, default 32).
  18133. * The parameter "tubularSegments" sets the number of tubes to decompose the knot into (positive integer, default 32).
  18134. * The parameters "p" and "q" are the number of windings on each axis (positive integers, default 2 and 3).
  18135. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18137. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18138. */
  18139. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  18140. var torusKnot = new BABYLON.Mesh(name, scene);
  18141. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  18142. vertexData.applyToMesh(torusKnot, options.updatable);
  18143. return torusKnot;
  18144. };
  18145. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  18146. var instance = options.instance;
  18147. var lines = options.lines;
  18148. if (instance) {
  18149. var positionFunction = function (positions) {
  18150. var i = 0;
  18151. for (var l = 0; l < lines.length; l++) {
  18152. var points = lines[l];
  18153. for (var p = 0; p < points.length; p++) {
  18154. positions[i] = points[p].x;
  18155. positions[i + 1] = points[p].y;
  18156. positions[i + 2] = points[p].z;
  18157. i += 3;
  18158. }
  18159. }
  18160. };
  18161. instance.updateMeshPositions(positionFunction, false);
  18162. return instance;
  18163. }
  18164. // line system creation
  18165. var lineSystem = new BABYLON.LinesMesh(name, scene);
  18166. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  18167. vertexData.applyToMesh(lineSystem, options.updatable);
  18168. return lineSystem;
  18169. };
  18170. MeshBuilder.CreateLines = function (name, options, scene) {
  18171. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  18172. return lines;
  18173. };
  18174. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  18175. var points = options.points;
  18176. var instance = options.instance;
  18177. var gapSize = options.gapSize;
  18178. var dashNb = options.dashNb;
  18179. var dashSize = options.dashSize;
  18180. if (instance) {
  18181. var positionFunction = function (positions) {
  18182. var curvect = BABYLON.Vector3.Zero();
  18183. var nbSeg = positions.length / 6;
  18184. var lg = 0;
  18185. var nb = 0;
  18186. var shft = 0;
  18187. var dashshft = 0;
  18188. var curshft = 0;
  18189. var p = 0;
  18190. var i = 0;
  18191. var j = 0;
  18192. for (i = 0; i < points.length - 1; i++) {
  18193. points[i + 1].subtractToRef(points[i], curvect);
  18194. lg += curvect.length();
  18195. }
  18196. shft = lg / nbSeg;
  18197. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  18198. for (i = 0; i < points.length - 1; i++) {
  18199. points[i + 1].subtractToRef(points[i], curvect);
  18200. nb = Math.floor(curvect.length() / shft);
  18201. curvect.normalize();
  18202. j = 0;
  18203. while (j < nb && p < positions.length) {
  18204. curshft = shft * j;
  18205. positions[p] = points[i].x + curshft * curvect.x;
  18206. positions[p + 1] = points[i].y + curshft * curvect.y;
  18207. positions[p + 2] = points[i].z + curshft * curvect.z;
  18208. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  18209. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  18210. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  18211. p += 6;
  18212. j++;
  18213. }
  18214. }
  18215. while (p < positions.length) {
  18216. positions[p] = points[i].x;
  18217. positions[p + 1] = points[i].y;
  18218. positions[p + 2] = points[i].z;
  18219. p += 3;
  18220. }
  18221. };
  18222. instance.updateMeshPositions(positionFunction, false);
  18223. return instance;
  18224. }
  18225. // dashed lines creation
  18226. var dashedLines = new BABYLON.LinesMesh(name, scene);
  18227. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  18228. vertexData.applyToMesh(dashedLines, options.updatable);
  18229. dashedLines.dashSize = dashSize;
  18230. dashedLines.gapSize = gapSize;
  18231. return dashedLines;
  18232. };
  18233. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  18234. var path = options.path;
  18235. var shape = options.shape;
  18236. var scale = options.scale || 1;
  18237. var rotation = options.rotation || 0;
  18238. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18239. var updatable = options.updatable;
  18240. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18241. var instance = options.instance;
  18242. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  18243. };
  18244. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  18245. var path = options.path;
  18246. var shape = options.shape;
  18247. var scaleFunction = options.scaleFunction || (function () { return 1; });
  18248. var rotationFunction = options.rotationFunction || (function () { return 0; });
  18249. var ribbonCloseArray = options.ribbonCloseArray || false;
  18250. var ribbonClosePath = options.ribbonClosePath || false;
  18251. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18252. var updatable = options.updatable;
  18253. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18254. var instance = options.instance;
  18255. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  18256. };
  18257. MeshBuilder.CreateLathe = function (name, options, scene) {
  18258. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  18259. var closed = (options.closed === undefined) ? true : options.closed;
  18260. var shape = options.shape;
  18261. var radius = options.radius || 1;
  18262. var tessellation = options.tessellation || 64;
  18263. var updatable = options.updatable;
  18264. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18265. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  18266. var pi2 = Math.PI * 2;
  18267. var paths = new Array();
  18268. var i = 0;
  18269. var p = 0;
  18270. var step = pi2 / tessellation * arc;
  18271. var rotated;
  18272. var path = new Array();
  18273. ;
  18274. for (i = 0; i <= tessellation; i++) {
  18275. var path = [];
  18276. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  18277. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  18278. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  18279. }
  18280. for (p = 0; p < shape.length; p++) {
  18281. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  18282. path.push(rotated);
  18283. }
  18284. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  18285. 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));
  18286. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  18287. }
  18288. paths.push(path);
  18289. }
  18290. // lathe ribbon
  18291. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  18292. return lathe;
  18293. };
  18294. MeshBuilder.CreatePlane = function (name, options, scene) {
  18295. var plane = new BABYLON.Mesh(name, scene);
  18296. var vertexData = BABYLON.VertexData.CreatePlane(options);
  18297. vertexData.applyToMesh(plane, options.updatable);
  18298. if (options.sourcePlane) {
  18299. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  18300. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  18301. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  18302. plane.rotate(vectorProduct, product);
  18303. }
  18304. return plane;
  18305. };
  18306. MeshBuilder.CreateGround = function (name, options, scene) {
  18307. var ground = new BABYLON.GroundMesh(name, scene);
  18308. ground._setReady(false);
  18309. ground._subdivisions = options.subdivisions || 1;
  18310. ground._width = options.width || 1;
  18311. ground._height = options.height || 1;
  18312. ground._maxX = ground._width / 2;
  18313. ground._maxZ = ground._height / 2;
  18314. ground._minX = -ground._maxX;
  18315. ground._minZ = -ground._maxZ;
  18316. var vertexData = BABYLON.VertexData.CreateGround(options);
  18317. vertexData.applyToMesh(ground, options.updatable);
  18318. ground._setReady(true);
  18319. return ground;
  18320. };
  18321. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  18322. var tiledGround = new BABYLON.Mesh(name, scene);
  18323. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  18324. vertexData.applyToMesh(tiledGround, options.updatable);
  18325. return tiledGround;
  18326. };
  18327. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  18328. var width = options.width || 10;
  18329. var height = options.height || 10;
  18330. var subdivisions = options.subdivisions || 1;
  18331. var minHeight = options.minHeight;
  18332. var maxHeight = options.maxHeight || 10;
  18333. var updatable = options.updatable;
  18334. var onReady = options.onReady;
  18335. var ground = new BABYLON.GroundMesh(name, scene);
  18336. ground._subdivisions = subdivisions;
  18337. ground._width = width;
  18338. ground._height = height;
  18339. ground._maxX = ground._width / 2;
  18340. ground._maxZ = ground._height / 2;
  18341. ground._minX = -ground._maxX;
  18342. ground._minZ = -ground._maxZ;
  18343. ground._setReady(false);
  18344. var onload = function (img) {
  18345. // Getting height map data
  18346. var canvas = document.createElement("canvas");
  18347. var context = canvas.getContext("2d");
  18348. var bufferWidth = img.width;
  18349. var bufferHeight = img.height;
  18350. canvas.width = bufferWidth;
  18351. canvas.height = bufferHeight;
  18352. context.drawImage(img, 0, 0);
  18353. // Create VertexData from map data
  18354. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18355. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  18356. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  18357. width: width, height: height,
  18358. subdivisions: subdivisions,
  18359. minHeight: minHeight, maxHeight: maxHeight,
  18360. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  18361. });
  18362. vertexData.applyToMesh(ground, updatable);
  18363. ground._setReady(true);
  18364. //execute ready callback, if set
  18365. if (onReady) {
  18366. onReady(ground);
  18367. }
  18368. };
  18369. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18370. return ground;
  18371. };
  18372. MeshBuilder.CreateTube = function (name, options, scene) {
  18373. var path = options.path;
  18374. var radius = options.radius || 1;
  18375. var tessellation = options.tessellation || 64;
  18376. var radiusFunction = options.radiusFunction;
  18377. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  18378. var updatable = options.updatable;
  18379. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18380. var instance = options.instance;
  18381. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  18382. // tube geometry
  18383. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  18384. var tangents = path3D.getTangents();
  18385. var normals = path3D.getNormals();
  18386. var distances = path3D.getDistances();
  18387. var pi2 = Math.PI * 2;
  18388. var step = pi2 / tessellation * arc;
  18389. var returnRadius = function () { return radius; };
  18390. var radiusFunctionFinal = radiusFunction || returnRadius;
  18391. var circlePath;
  18392. var rad;
  18393. var normal;
  18394. var rotated;
  18395. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  18396. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  18397. for (var i = 0; i < path.length; i++) {
  18398. rad = radiusFunctionFinal(i, distances[i]); // current radius
  18399. circlePath = Array(); // current circle array
  18400. normal = normals[i]; // current normal
  18401. for (var t = 0; t < tessellation; t++) {
  18402. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  18403. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  18404. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  18405. rotated.scaleInPlace(rad).addInPlace(path[i]);
  18406. circlePath[t] = rotated;
  18407. }
  18408. circlePaths[index] = circlePath;
  18409. index++;
  18410. }
  18411. // cap
  18412. var capPath = function (nbPoints, pathIndex) {
  18413. var pointCap = Array();
  18414. for (var i = 0; i < nbPoints; i++) {
  18415. pointCap.push(path[pathIndex]);
  18416. }
  18417. return pointCap;
  18418. };
  18419. switch (cap) {
  18420. case BABYLON.Mesh.NO_CAP:
  18421. break;
  18422. case BABYLON.Mesh.CAP_START:
  18423. circlePaths[0] = capPath(tessellation, 0);
  18424. circlePaths[1] = circlePaths[2].slice(0);
  18425. break;
  18426. case BABYLON.Mesh.CAP_END:
  18427. circlePaths[index] = circlePaths[index - 1].slice(0);
  18428. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  18429. break;
  18430. case BABYLON.Mesh.CAP_ALL:
  18431. circlePaths[0] = capPath(tessellation, 0);
  18432. circlePaths[1] = circlePaths[2].slice(0);
  18433. circlePaths[index] = circlePaths[index - 1].slice(0);
  18434. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  18435. break;
  18436. default:
  18437. break;
  18438. }
  18439. return circlePaths;
  18440. };
  18441. var path3D;
  18442. var pathArray;
  18443. if (instance) {
  18444. var arc = options.arc || instance.arc;
  18445. path3D = (instance.path3D).update(path);
  18446. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  18447. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  18448. instance.path3D = path3D;
  18449. instance.pathArray = pathArray;
  18450. instance.arc = arc;
  18451. return instance;
  18452. }
  18453. // tube creation
  18454. path3D = new BABYLON.Path3D(path);
  18455. var newPathArray = new Array();
  18456. cap = (cap < 0 || cap > 3) ? 0 : cap;
  18457. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  18458. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  18459. tube.pathArray = pathArray;
  18460. tube.path3D = path3D;
  18461. tube.tessellation = tessellation;
  18462. tube.cap = cap;
  18463. tube.arc = options.arc;
  18464. return tube;
  18465. };
  18466. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  18467. var polyhedron = new BABYLON.Mesh(name, scene);
  18468. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  18469. vertexData.applyToMesh(polyhedron, options.updatable);
  18470. return polyhedron;
  18471. };
  18472. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  18473. var indices = sourceMesh.getIndices();
  18474. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18475. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18476. var position = options.position || BABYLON.Vector3.Zero();
  18477. var normal = options.normal || BABYLON.Vector3.Up();
  18478. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  18479. var angle = options.angle || 0;
  18480. // Getting correct rotation
  18481. if (!normal) {
  18482. var target = new BABYLON.Vector3(0, 0, 1);
  18483. var camera = sourceMesh.getScene().activeCamera;
  18484. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  18485. normal = camera.globalPosition.subtract(cameraWorldTarget);
  18486. }
  18487. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  18488. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  18489. var pitch = Math.atan2(normal.y, len);
  18490. // Matrix
  18491. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  18492. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  18493. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  18494. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  18495. var vertexData = new BABYLON.VertexData();
  18496. vertexData.indices = [];
  18497. vertexData.positions = [];
  18498. vertexData.normals = [];
  18499. vertexData.uvs = [];
  18500. var currentVertexDataIndex = 0;
  18501. var extractDecalVector3 = function (indexId) {
  18502. var vertexId = indices[indexId];
  18503. var result = new BABYLON.PositionNormalVertex();
  18504. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  18505. // Send vector to decal local world
  18506. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  18507. // Get normal
  18508. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  18509. return result;
  18510. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  18511. var clip = function (vertices, axis) {
  18512. if (vertices.length === 0) {
  18513. return vertices;
  18514. }
  18515. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  18516. var clipVertices = function (v0, v1) {
  18517. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  18518. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  18519. };
  18520. var result = new Array();
  18521. for (var index = 0; index < vertices.length; index += 3) {
  18522. var v1Out;
  18523. var v2Out;
  18524. var v3Out;
  18525. var total = 0;
  18526. var nV1, nV2, nV3, nV4;
  18527. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  18528. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  18529. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  18530. v1Out = d1 > 0;
  18531. v2Out = d2 > 0;
  18532. v3Out = d3 > 0;
  18533. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  18534. switch (total) {
  18535. case 0:
  18536. result.push(vertices[index]);
  18537. result.push(vertices[index + 1]);
  18538. result.push(vertices[index + 2]);
  18539. break;
  18540. case 1:
  18541. if (v1Out) {
  18542. nV1 = vertices[index + 1];
  18543. nV2 = vertices[index + 2];
  18544. nV3 = clipVertices(vertices[index], nV1);
  18545. nV4 = clipVertices(vertices[index], nV2);
  18546. }
  18547. if (v2Out) {
  18548. nV1 = vertices[index];
  18549. nV2 = vertices[index + 2];
  18550. nV3 = clipVertices(vertices[index + 1], nV1);
  18551. nV4 = clipVertices(vertices[index + 1], nV2);
  18552. result.push(nV3);
  18553. result.push(nV2.clone());
  18554. result.push(nV1.clone());
  18555. result.push(nV2.clone());
  18556. result.push(nV3.clone());
  18557. result.push(nV4);
  18558. break;
  18559. }
  18560. if (v3Out) {
  18561. nV1 = vertices[index];
  18562. nV2 = vertices[index + 1];
  18563. nV3 = clipVertices(vertices[index + 2], nV1);
  18564. nV4 = clipVertices(vertices[index + 2], nV2);
  18565. }
  18566. result.push(nV1.clone());
  18567. result.push(nV2.clone());
  18568. result.push(nV3);
  18569. result.push(nV4);
  18570. result.push(nV3.clone());
  18571. result.push(nV2.clone());
  18572. break;
  18573. case 2:
  18574. if (!v1Out) {
  18575. nV1 = vertices[index].clone();
  18576. nV2 = clipVertices(nV1, vertices[index + 1]);
  18577. nV3 = clipVertices(nV1, vertices[index + 2]);
  18578. result.push(nV1);
  18579. result.push(nV2);
  18580. result.push(nV3);
  18581. }
  18582. if (!v2Out) {
  18583. nV1 = vertices[index + 1].clone();
  18584. nV2 = clipVertices(nV1, vertices[index + 2]);
  18585. nV3 = clipVertices(nV1, vertices[index]);
  18586. result.push(nV1);
  18587. result.push(nV2);
  18588. result.push(nV3);
  18589. }
  18590. if (!v3Out) {
  18591. nV1 = vertices[index + 2].clone();
  18592. nV2 = clipVertices(nV1, vertices[index]);
  18593. nV3 = clipVertices(nV1, vertices[index + 1]);
  18594. result.push(nV1);
  18595. result.push(nV2);
  18596. result.push(nV3);
  18597. }
  18598. break;
  18599. case 3:
  18600. break;
  18601. }
  18602. }
  18603. return result;
  18604. };
  18605. for (var index = 0; index < indices.length; index += 3) {
  18606. var faceVertices = new Array();
  18607. faceVertices.push(extractDecalVector3(index));
  18608. faceVertices.push(extractDecalVector3(index + 1));
  18609. faceVertices.push(extractDecalVector3(index + 2));
  18610. // Clip
  18611. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  18612. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  18613. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  18614. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  18615. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  18616. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  18617. if (faceVertices.length === 0) {
  18618. continue;
  18619. }
  18620. // Add UVs and get back to world
  18621. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  18622. var vertex = faceVertices[vIndex];
  18623. //TODO check for Int32Array
  18624. vertexData.indices.push(currentVertexDataIndex);
  18625. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  18626. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  18627. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  18628. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  18629. currentVertexDataIndex++;
  18630. }
  18631. }
  18632. // Return mesh
  18633. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  18634. vertexData.applyToMesh(decal);
  18635. decal.position = position.clone();
  18636. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  18637. return decal;
  18638. };
  18639. // Privates
  18640. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  18641. // extrusion geometry
  18642. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  18643. var tangents = path3D.getTangents();
  18644. var normals = path3D.getNormals();
  18645. var binormals = path3D.getBinormals();
  18646. var distances = path3D.getDistances();
  18647. var angle = 0;
  18648. var returnScale = function () { return scale; };
  18649. var returnRotation = function () { return rotation; };
  18650. var rotate = custom ? rotateFunction : returnRotation;
  18651. var scl = custom ? scaleFunction : returnScale;
  18652. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  18653. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  18654. for (var i = 0; i < curve.length; i++) {
  18655. var shapePath = new Array();
  18656. var angleStep = rotate(i, distances[i]);
  18657. var scaleRatio = scl(i, distances[i]);
  18658. for (var p = 0; p < shape.length; p++) {
  18659. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  18660. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  18661. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  18662. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  18663. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  18664. shapePath[p] = rotated;
  18665. }
  18666. shapePaths[index] = shapePath;
  18667. angle += angleStep;
  18668. index++;
  18669. }
  18670. // cap
  18671. var capPath = function (shapePath) {
  18672. var pointCap = Array();
  18673. var barycenter = BABYLON.Vector3.Zero();
  18674. var i;
  18675. for (i = 0; i < shapePath.length; i++) {
  18676. barycenter.addInPlace(shapePath[i]);
  18677. }
  18678. barycenter.scaleInPlace(1 / shapePath.length);
  18679. for (i = 0; i < shapePath.length; i++) {
  18680. pointCap.push(barycenter);
  18681. }
  18682. return pointCap;
  18683. };
  18684. switch (cap) {
  18685. case BABYLON.Mesh.NO_CAP:
  18686. break;
  18687. case BABYLON.Mesh.CAP_START:
  18688. shapePaths[0] = capPath(shapePaths[2]);
  18689. shapePaths[1] = shapePaths[2].slice(0);
  18690. break;
  18691. case BABYLON.Mesh.CAP_END:
  18692. shapePaths[index] = shapePaths[index - 1];
  18693. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  18694. break;
  18695. case BABYLON.Mesh.CAP_ALL:
  18696. shapePaths[0] = capPath(shapePaths[2]);
  18697. shapePaths[1] = shapePaths[2].slice(0);
  18698. shapePaths[index] = shapePaths[index - 1];
  18699. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  18700. break;
  18701. default:
  18702. break;
  18703. }
  18704. return shapePaths;
  18705. };
  18706. var path3D;
  18707. var pathArray;
  18708. if (instance) {
  18709. path3D = (instance.path3D).update(curve);
  18710. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  18711. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  18712. return instance;
  18713. }
  18714. // extruded shape creation
  18715. path3D = new BABYLON.Path3D(curve);
  18716. var newShapePaths = new Array();
  18717. cap = (cap < 0 || cap > 3) ? 0 : cap;
  18718. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  18719. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  18720. extrudedGeneric.pathArray = pathArray;
  18721. extrudedGeneric.path3D = path3D;
  18722. extrudedGeneric.cap = cap;
  18723. return extrudedGeneric;
  18724. };
  18725. return MeshBuilder;
  18726. })();
  18727. BABYLON.MeshBuilder = MeshBuilder;
  18728. })(BABYLON || (BABYLON = {}));
  18729. var BABYLON;
  18730. (function (BABYLON) {
  18731. var BaseTexture = (function () {
  18732. function BaseTexture(scene) {
  18733. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18734. this.hasAlpha = false;
  18735. this.getAlphaFromRGB = false;
  18736. this.level = 1;
  18737. this.isCube = false;
  18738. this.isRenderTarget = false;
  18739. this.animations = new Array();
  18740. this.coordinatesIndex = 0;
  18741. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18742. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18743. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18744. this.anisotropicFilteringLevel = 4;
  18745. this._scene = scene;
  18746. this._scene.textures.push(this);
  18747. }
  18748. BaseTexture.prototype.getScene = function () {
  18749. return this._scene;
  18750. };
  18751. BaseTexture.prototype.getTextureMatrix = function () {
  18752. return null;
  18753. };
  18754. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18755. return null;
  18756. };
  18757. BaseTexture.prototype.getInternalTexture = function () {
  18758. return this._texture;
  18759. };
  18760. BaseTexture.prototype.isReady = function () {
  18761. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18762. return true;
  18763. }
  18764. if (this._texture) {
  18765. return this._texture.isReady;
  18766. }
  18767. return false;
  18768. };
  18769. BaseTexture.prototype.getSize = function () {
  18770. if (this._texture._width) {
  18771. return { width: this._texture._width, height: this._texture._height };
  18772. }
  18773. if (this._texture._size) {
  18774. return { width: this._texture._size, height: this._texture._size };
  18775. }
  18776. return { width: 0, height: 0 };
  18777. };
  18778. BaseTexture.prototype.getBaseSize = function () {
  18779. if (!this.isReady())
  18780. return { width: 0, height: 0 };
  18781. if (this._texture._size) {
  18782. return { width: this._texture._size, height: this._texture._size };
  18783. }
  18784. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  18785. };
  18786. BaseTexture.prototype.scale = function (ratio) {
  18787. };
  18788. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18789. get: function () {
  18790. return false;
  18791. },
  18792. enumerable: true,
  18793. configurable: true
  18794. });
  18795. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18796. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18797. for (var index = 0; index < texturesCache.length; index++) {
  18798. var texturesCacheEntry = texturesCache[index];
  18799. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18800. texturesCache.splice(index, 1);
  18801. return;
  18802. }
  18803. }
  18804. };
  18805. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18806. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18807. for (var index = 0; index < texturesCache.length; index++) {
  18808. var texturesCacheEntry = texturesCache[index];
  18809. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18810. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18811. texturesCacheEntry.references++;
  18812. return texturesCacheEntry;
  18813. }
  18814. }
  18815. }
  18816. return null;
  18817. };
  18818. BaseTexture.prototype.delayLoad = function () {
  18819. };
  18820. BaseTexture.prototype.clone = function () {
  18821. return null;
  18822. };
  18823. BaseTexture.prototype.releaseInternalTexture = function () {
  18824. if (this._texture) {
  18825. this._scene.getEngine().releaseInternalTexture(this._texture);
  18826. delete this._texture;
  18827. }
  18828. };
  18829. BaseTexture.prototype.dispose = function () {
  18830. // Animations
  18831. this.getScene().stopAnimation(this);
  18832. // Remove from scene
  18833. var index = this._scene.textures.indexOf(this);
  18834. if (index >= 0) {
  18835. this._scene.textures.splice(index, 1);
  18836. }
  18837. if (this._texture === undefined) {
  18838. return;
  18839. }
  18840. // Release
  18841. this.releaseInternalTexture();
  18842. // Callback
  18843. if (this.onDispose) {
  18844. this.onDispose();
  18845. }
  18846. };
  18847. BaseTexture.prototype.serialize = function () {
  18848. var serializationObject = {};
  18849. if (!this.name) {
  18850. return null;
  18851. }
  18852. serializationObject.name = this.name;
  18853. serializationObject.hasAlpha = this.hasAlpha;
  18854. serializationObject.level = this.level;
  18855. serializationObject.coordinatesIndex = this.coordinatesIndex;
  18856. serializationObject.coordinatesMode = this.coordinatesMode;
  18857. serializationObject.wrapU = this.wrapU;
  18858. serializationObject.wrapV = this.wrapV;
  18859. // Animations
  18860. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18861. return serializationObject;
  18862. };
  18863. return BaseTexture;
  18864. })();
  18865. BABYLON.BaseTexture = BaseTexture;
  18866. })(BABYLON || (BABYLON = {}));
  18867. var BABYLON;
  18868. (function (BABYLON) {
  18869. var Texture = (function (_super) {
  18870. __extends(Texture, _super);
  18871. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  18872. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18873. if (onLoad === void 0) { onLoad = null; }
  18874. if (onError === void 0) { onError = null; }
  18875. if (buffer === void 0) { buffer = null; }
  18876. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18877. _super.call(this, scene);
  18878. this.uOffset = 0;
  18879. this.vOffset = 0;
  18880. this.uScale = 1.0;
  18881. this.vScale = 1.0;
  18882. this.uAng = 0;
  18883. this.vAng = 0;
  18884. this.wAng = 0;
  18885. this.name = url;
  18886. this.url = url;
  18887. this._noMipmap = noMipmap;
  18888. this._invertY = invertY;
  18889. this._samplingMode = samplingMode;
  18890. this._buffer = buffer;
  18891. this._deleteBuffer = deleteBuffer;
  18892. if (!url) {
  18893. return;
  18894. }
  18895. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  18896. if (!this._texture) {
  18897. if (!scene.useDelayedTextureLoading) {
  18898. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  18899. if (deleteBuffer) {
  18900. delete this._buffer;
  18901. }
  18902. }
  18903. else {
  18904. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18905. this._delayedOnLoad = onLoad;
  18906. this._delayedOnError = onError;
  18907. }
  18908. }
  18909. else {
  18910. BABYLON.Tools.SetImmediate(function () {
  18911. if (onLoad) {
  18912. onLoad();
  18913. }
  18914. });
  18915. }
  18916. }
  18917. Texture.prototype.delayLoad = function () {
  18918. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18919. return;
  18920. }
  18921. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18922. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18923. if (!this._texture) {
  18924. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  18925. if (this._deleteBuffer) {
  18926. delete this._buffer;
  18927. }
  18928. }
  18929. };
  18930. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18931. if (!this._texture) {
  18932. return;
  18933. }
  18934. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18935. };
  18936. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18937. x *= this.uScale;
  18938. y *= this.vScale;
  18939. x -= 0.5 * this.uScale;
  18940. y -= 0.5 * this.vScale;
  18941. z -= 0.5;
  18942. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  18943. t.x += 0.5 * this.uScale + this.uOffset;
  18944. t.y += 0.5 * this.vScale + this.vOffset;
  18945. t.z += 0.5;
  18946. };
  18947. Texture.prototype.getTextureMatrix = function () {
  18948. if (this.uOffset === this._cachedUOffset &&
  18949. this.vOffset === this._cachedVOffset &&
  18950. this.uScale === this._cachedUScale &&
  18951. this.vScale === this._cachedVScale &&
  18952. this.uAng === this._cachedUAng &&
  18953. this.vAng === this._cachedVAng &&
  18954. this.wAng === this._cachedWAng) {
  18955. return this._cachedTextureMatrix;
  18956. }
  18957. this._cachedUOffset = this.uOffset;
  18958. this._cachedVOffset = this.vOffset;
  18959. this._cachedUScale = this.uScale;
  18960. this._cachedVScale = this.vScale;
  18961. this._cachedUAng = this.uAng;
  18962. this._cachedVAng = this.vAng;
  18963. this._cachedWAng = this.wAng;
  18964. if (!this._cachedTextureMatrix) {
  18965. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18966. this._rowGenerationMatrix = new BABYLON.Matrix();
  18967. this._t0 = BABYLON.Vector3.Zero();
  18968. this._t1 = BABYLON.Vector3.Zero();
  18969. this._t2 = BABYLON.Vector3.Zero();
  18970. }
  18971. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  18972. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  18973. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  18974. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  18975. this._t1.subtractInPlace(this._t0);
  18976. this._t2.subtractInPlace(this._t0);
  18977. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18978. this._cachedTextureMatrix.m[0] = this._t1.x;
  18979. this._cachedTextureMatrix.m[1] = this._t1.y;
  18980. this._cachedTextureMatrix.m[2] = this._t1.z;
  18981. this._cachedTextureMatrix.m[4] = this._t2.x;
  18982. this._cachedTextureMatrix.m[5] = this._t2.y;
  18983. this._cachedTextureMatrix.m[6] = this._t2.z;
  18984. this._cachedTextureMatrix.m[8] = this._t0.x;
  18985. this._cachedTextureMatrix.m[9] = this._t0.y;
  18986. this._cachedTextureMatrix.m[10] = this._t0.z;
  18987. return this._cachedTextureMatrix;
  18988. };
  18989. Texture.prototype.getReflectionTextureMatrix = function () {
  18990. if (this.uOffset === this._cachedUOffset &&
  18991. this.vOffset === this._cachedVOffset &&
  18992. this.uScale === this._cachedUScale &&
  18993. this.vScale === this._cachedVScale &&
  18994. this.coordinatesMode === this._cachedCoordinatesMode) {
  18995. return this._cachedTextureMatrix;
  18996. }
  18997. if (!this._cachedTextureMatrix) {
  18998. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18999. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19000. }
  19001. this._cachedCoordinatesMode = this.coordinatesMode;
  19002. switch (this.coordinatesMode) {
  19003. case Texture.PLANAR_MODE:
  19004. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19005. this._cachedTextureMatrix[0] = this.uScale;
  19006. this._cachedTextureMatrix[5] = this.vScale;
  19007. this._cachedTextureMatrix[12] = this.uOffset;
  19008. this._cachedTextureMatrix[13] = this.vOffset;
  19009. break;
  19010. case Texture.PROJECTION_MODE:
  19011. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19012. this._projectionModeMatrix.m[0] = 0.5;
  19013. this._projectionModeMatrix.m[5] = -0.5;
  19014. this._projectionModeMatrix.m[10] = 0.0;
  19015. this._projectionModeMatrix.m[12] = 0.5;
  19016. this._projectionModeMatrix.m[13] = 0.5;
  19017. this._projectionModeMatrix.m[14] = 1.0;
  19018. this._projectionModeMatrix.m[15] = 1.0;
  19019. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19020. break;
  19021. default:
  19022. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19023. break;
  19024. }
  19025. return this._cachedTextureMatrix;
  19026. };
  19027. Texture.prototype.clone = function () {
  19028. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  19029. // Base texture
  19030. newTexture.hasAlpha = this.hasAlpha;
  19031. newTexture.level = this.level;
  19032. newTexture.wrapU = this.wrapU;
  19033. newTexture.wrapV = this.wrapV;
  19034. newTexture.coordinatesIndex = this.coordinatesIndex;
  19035. newTexture.coordinatesMode = this.coordinatesMode;
  19036. // Texture
  19037. newTexture.uOffset = this.uOffset;
  19038. newTexture.vOffset = this.vOffset;
  19039. newTexture.uScale = this.uScale;
  19040. newTexture.vScale = this.vScale;
  19041. newTexture.uAng = this.uAng;
  19042. newTexture.vAng = this.vAng;
  19043. newTexture.wAng = this.wAng;
  19044. return newTexture;
  19045. };
  19046. Texture.prototype.serialize = function () {
  19047. if (!this.name) {
  19048. return null;
  19049. }
  19050. var serializationObject = _super.prototype.serialize.call(this);
  19051. serializationObject.uOffset = this.uOffset;
  19052. serializationObject.vOffset = this.vOffset;
  19053. serializationObject.uScale = this.uScale;
  19054. serializationObject.vScale = this.vScale;
  19055. serializationObject.uAng = this.uAng;
  19056. serializationObject.vAng = this.vAng;
  19057. serializationObject.wAng = this.wAng;
  19058. return serializationObject;
  19059. };
  19060. // Statics
  19061. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  19062. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19063. if (onLoad === void 0) { onLoad = null; }
  19064. if (onError === void 0) { onError = null; }
  19065. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  19066. };
  19067. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19068. if (parsedTexture.isCube) {
  19069. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19070. }
  19071. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19072. return null;
  19073. }
  19074. var texture;
  19075. if (parsedTexture.mirrorPlane) {
  19076. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19077. texture._waitingRenderList = parsedTexture.renderList;
  19078. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19079. }
  19080. else if (parsedTexture.isRenderTarget) {
  19081. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19082. texture._waitingRenderList = parsedTexture.renderList;
  19083. }
  19084. else {
  19085. if (parsedTexture.base64String) {
  19086. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19087. }
  19088. else {
  19089. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19090. }
  19091. }
  19092. texture.name = parsedTexture.name;
  19093. texture.hasAlpha = parsedTexture.hasAlpha;
  19094. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19095. texture.level = parsedTexture.level;
  19096. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19097. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19098. texture.uOffset = parsedTexture.uOffset;
  19099. texture.vOffset = parsedTexture.vOffset;
  19100. texture.uScale = parsedTexture.uScale;
  19101. texture.vScale = parsedTexture.vScale;
  19102. texture.uAng = parsedTexture.uAng;
  19103. texture.vAng = parsedTexture.vAng;
  19104. texture.wAng = parsedTexture.wAng;
  19105. texture.wrapU = parsedTexture.wrapU;
  19106. texture.wrapV = parsedTexture.wrapV;
  19107. // Animations
  19108. if (parsedTexture.animations) {
  19109. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19110. var parsedAnimation = parsedTexture.animations[animationIndex];
  19111. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19112. }
  19113. }
  19114. return texture;
  19115. };
  19116. // Constants
  19117. Texture.NEAREST_SAMPLINGMODE = 1;
  19118. Texture.BILINEAR_SAMPLINGMODE = 2;
  19119. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19120. Texture.EXPLICIT_MODE = 0;
  19121. Texture.SPHERICAL_MODE = 1;
  19122. Texture.PLANAR_MODE = 2;
  19123. Texture.CUBIC_MODE = 3;
  19124. Texture.PROJECTION_MODE = 4;
  19125. Texture.SKYBOX_MODE = 5;
  19126. Texture.INVCUBIC_MODE = 6;
  19127. Texture.EQUIRECTANGULAR_MODE = 7;
  19128. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19129. Texture.CLAMP_ADDRESSMODE = 0;
  19130. Texture.WRAP_ADDRESSMODE = 1;
  19131. Texture.MIRROR_ADDRESSMODE = 2;
  19132. return Texture;
  19133. })(BABYLON.BaseTexture);
  19134. BABYLON.Texture = Texture;
  19135. })(BABYLON || (BABYLON = {}));
  19136. var BABYLON;
  19137. (function (BABYLON) {
  19138. var CubeTexture = (function (_super) {
  19139. __extends(CubeTexture, _super);
  19140. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  19141. _super.call(this, scene);
  19142. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  19143. this.name = rootUrl;
  19144. this.url = rootUrl;
  19145. this._noMipmap = noMipmap;
  19146. this.hasAlpha = false;
  19147. if (!rootUrl && !files) {
  19148. return;
  19149. }
  19150. this._texture = this._getFromCache(rootUrl, noMipmap);
  19151. if (!files) {
  19152. if (!extensions) {
  19153. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  19154. }
  19155. files = [];
  19156. for (var index = 0; index < extensions.length; index++) {
  19157. files.push(rootUrl + extensions[index]);
  19158. }
  19159. this._extensions = extensions;
  19160. }
  19161. this._files = files;
  19162. if (!this._texture) {
  19163. if (!scene.useDelayedTextureLoading) {
  19164. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  19165. }
  19166. else {
  19167. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19168. }
  19169. }
  19170. this.isCube = true;
  19171. this._textureMatrix = BABYLON.Matrix.Identity();
  19172. }
  19173. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  19174. return new CubeTexture("", scene, null, noMipmap, files);
  19175. };
  19176. CubeTexture.prototype.clone = function () {
  19177. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  19178. // Base texture
  19179. newTexture.level = this.level;
  19180. newTexture.wrapU = this.wrapU;
  19181. newTexture.wrapV = this.wrapV;
  19182. newTexture.coordinatesIndex = this.coordinatesIndex;
  19183. newTexture.coordinatesMode = this.coordinatesMode;
  19184. return newTexture;
  19185. };
  19186. // Methods
  19187. CubeTexture.prototype.delayLoad = function () {
  19188. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19189. return;
  19190. }
  19191. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19192. this._texture = this._getFromCache(this.url, this._noMipmap);
  19193. if (!this._texture) {
  19194. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  19195. }
  19196. };
  19197. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  19198. return this._textureMatrix;
  19199. };
  19200. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  19201. var texture = null;
  19202. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19203. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19204. texture.name = parsedTexture.name;
  19205. texture.hasAlpha = parsedTexture.hasAlpha;
  19206. texture.level = parsedTexture.level;
  19207. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19208. }
  19209. return texture;
  19210. };
  19211. CubeTexture.prototype.serialize = function () {
  19212. if (!this.name) {
  19213. return null;
  19214. }
  19215. var serializationObject = {};
  19216. serializationObject.name = this.name;
  19217. serializationObject.hasAlpha = this.hasAlpha;
  19218. serializationObject.isCube = true;
  19219. serializationObject.level = this.level;
  19220. serializationObject.coordinatesMode = this.coordinatesMode;
  19221. return serializationObject;
  19222. };
  19223. return CubeTexture;
  19224. })(BABYLON.BaseTexture);
  19225. BABYLON.CubeTexture = CubeTexture;
  19226. })(BABYLON || (BABYLON = {}));
  19227. var BABYLON;
  19228. (function (BABYLON) {
  19229. var RenderTargetTexture = (function (_super) {
  19230. __extends(RenderTargetTexture, _super);
  19231. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  19232. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  19233. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  19234. if (isCube === void 0) { isCube = false; }
  19235. _super.call(this, null, scene, !generateMipMaps);
  19236. this.isCube = isCube;
  19237. this.renderList = new Array();
  19238. this.renderParticles = true;
  19239. this.renderSprites = false;
  19240. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  19241. this._currentRefreshId = -1;
  19242. this._refreshRate = 1;
  19243. this.name = name;
  19244. this.isRenderTarget = true;
  19245. this._size = size;
  19246. this._generateMipMaps = generateMipMaps;
  19247. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  19248. if (isCube) {
  19249. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  19250. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  19251. this._textureMatrix = BABYLON.Matrix.Identity();
  19252. }
  19253. else {
  19254. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  19255. }
  19256. // Rendering groups
  19257. this._renderingManager = new BABYLON.RenderingManager(scene);
  19258. }
  19259. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  19260. get: function () {
  19261. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  19262. },
  19263. enumerable: true,
  19264. configurable: true
  19265. });
  19266. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  19267. get: function () {
  19268. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  19269. },
  19270. enumerable: true,
  19271. configurable: true
  19272. });
  19273. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  19274. get: function () {
  19275. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  19276. },
  19277. enumerable: true,
  19278. configurable: true
  19279. });
  19280. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  19281. this._currentRefreshId = -1;
  19282. };
  19283. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  19284. get: function () {
  19285. return this._refreshRate;
  19286. },
  19287. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  19288. set: function (value) {
  19289. this._refreshRate = value;
  19290. this.resetRefreshCounter();
  19291. },
  19292. enumerable: true,
  19293. configurable: true
  19294. });
  19295. RenderTargetTexture.prototype._shouldRender = function () {
  19296. if (this._currentRefreshId === -1) {
  19297. this._currentRefreshId = 1;
  19298. return true;
  19299. }
  19300. if (this.refreshRate === this._currentRefreshId) {
  19301. this._currentRefreshId = 1;
  19302. return true;
  19303. }
  19304. this._currentRefreshId++;
  19305. return false;
  19306. };
  19307. RenderTargetTexture.prototype.isReady = function () {
  19308. if (!this.getScene().renderTargetsEnabled) {
  19309. return false;
  19310. }
  19311. return _super.prototype.isReady.call(this);
  19312. };
  19313. RenderTargetTexture.prototype.getRenderSize = function () {
  19314. return this._size;
  19315. };
  19316. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  19317. get: function () {
  19318. return true;
  19319. },
  19320. enumerable: true,
  19321. configurable: true
  19322. });
  19323. RenderTargetTexture.prototype.scale = function (ratio) {
  19324. var newSize = this._size * ratio;
  19325. this.resize(newSize, this._generateMipMaps);
  19326. };
  19327. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  19328. if (this.isCube) {
  19329. return this._textureMatrix;
  19330. }
  19331. return _super.prototype.getReflectionTextureMatrix.call(this);
  19332. };
  19333. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  19334. this.releaseInternalTexture();
  19335. if (this.isCube) {
  19336. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  19337. }
  19338. else {
  19339. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  19340. }
  19341. };
  19342. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  19343. var scene = this.getScene();
  19344. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  19345. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  19346. }
  19347. if (this._waitingRenderList) {
  19348. this.renderList = [];
  19349. for (var index = 0; index < this._waitingRenderList.length; index++) {
  19350. var id = this._waitingRenderList[index];
  19351. this.renderList.push(scene.getMeshByID(id));
  19352. }
  19353. delete this._waitingRenderList;
  19354. }
  19355. if (this.renderList && this.renderList.length === 0) {
  19356. return;
  19357. }
  19358. // Prepare renderingManager
  19359. this._renderingManager.reset();
  19360. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  19361. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  19362. var mesh = currentRenderList[meshIndex];
  19363. if (mesh) {
  19364. if (!mesh.isReady()) {
  19365. // Reset _currentRefreshId
  19366. this.resetRefreshCounter();
  19367. continue;
  19368. }
  19369. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  19370. mesh._activate(scene.getRenderId());
  19371. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19372. var subMesh = mesh.subMeshes[subIndex];
  19373. scene._activeIndices += subMesh.indexCount;
  19374. this._renderingManager.dispatch(subMesh);
  19375. }
  19376. }
  19377. }
  19378. }
  19379. if (this.isCube) {
  19380. for (var face = 0; face < 6; face++) {
  19381. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  19382. scene.incrementRenderId();
  19383. }
  19384. }
  19385. else {
  19386. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  19387. }
  19388. if (this.onAfterUnbind) {
  19389. this.onAfterUnbind();
  19390. }
  19391. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  19392. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  19393. }
  19394. scene.resetCachedMaterial();
  19395. };
  19396. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  19397. var scene = this.getScene();
  19398. var engine = scene.getEngine();
  19399. // Bind
  19400. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  19401. if (this.isCube) {
  19402. engine.bindFramebuffer(this._texture, faceIndex);
  19403. }
  19404. else {
  19405. engine.bindFramebuffer(this._texture);
  19406. }
  19407. }
  19408. if (this.onBeforeRender) {
  19409. this.onBeforeRender(faceIndex);
  19410. }
  19411. // Clear
  19412. if (this.onClear) {
  19413. this.onClear(engine);
  19414. }
  19415. else {
  19416. engine.clear(scene.clearColor, true, true);
  19417. }
  19418. if (!this._doNotChangeAspectRatio) {
  19419. scene.updateTransformMatrix(true);
  19420. }
  19421. // Render
  19422. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  19423. if (useCameraPostProcess) {
  19424. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  19425. }
  19426. if (!this._doNotChangeAspectRatio) {
  19427. scene.updateTransformMatrix(true);
  19428. }
  19429. if (this.onAfterRender) {
  19430. this.onAfterRender(faceIndex);
  19431. }
  19432. // Dump ?
  19433. if (dumpForDebug) {
  19434. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  19435. }
  19436. // Unbind
  19437. if (!this.isCube || faceIndex === 5) {
  19438. if (this.isCube) {
  19439. if (faceIndex === 5) {
  19440. engine.generateMipMapsForCubemap(this._texture);
  19441. }
  19442. }
  19443. engine.unBindFramebuffer(this._texture, this.isCube);
  19444. }
  19445. };
  19446. RenderTargetTexture.prototype.clone = function () {
  19447. var textureSize = this.getSize();
  19448. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19449. // Base texture
  19450. newTexture.hasAlpha = this.hasAlpha;
  19451. newTexture.level = this.level;
  19452. // RenderTarget Texture
  19453. newTexture.coordinatesMode = this.coordinatesMode;
  19454. newTexture.renderList = this.renderList.slice(0);
  19455. return newTexture;
  19456. };
  19457. RenderTargetTexture.prototype.serialize = function () {
  19458. if (!this.name) {
  19459. return null;
  19460. }
  19461. var serializationObject = _super.prototype.serialize.call(this);
  19462. serializationObject.renderTargetSize = this.getRenderSize();
  19463. serializationObject.renderList = [];
  19464. for (var index = 0; index < this.renderList.length; index++) {
  19465. serializationObject.renderList.push(this.renderList[index].id);
  19466. }
  19467. return serializationObject;
  19468. };
  19469. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  19470. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  19471. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  19472. return RenderTargetTexture;
  19473. })(BABYLON.Texture);
  19474. BABYLON.RenderTargetTexture = RenderTargetTexture;
  19475. })(BABYLON || (BABYLON = {}));
  19476. var BABYLON;
  19477. (function (BABYLON) {
  19478. var ProceduralTexture = (function (_super) {
  19479. __extends(ProceduralTexture, _super);
  19480. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  19481. if (generateMipMaps === void 0) { generateMipMaps = true; }
  19482. if (isCube === void 0) { isCube = false; }
  19483. _super.call(this, null, scene, !generateMipMaps);
  19484. this.isCube = isCube;
  19485. this.isEnabled = true;
  19486. this._currentRefreshId = -1;
  19487. this._refreshRate = 1;
  19488. this._vertexDeclaration = [2];
  19489. this._vertexStrideSize = 2 * 4;
  19490. this._uniforms = new Array();
  19491. this._samplers = new Array();
  19492. this._textures = new Array();
  19493. this._floats = new Array();
  19494. this._floatsArrays = {};
  19495. this._colors3 = new Array();
  19496. this._colors4 = new Array();
  19497. this._vectors2 = new Array();
  19498. this._vectors3 = new Array();
  19499. this._matrices = new Array();
  19500. this._fallbackTextureUsed = false;
  19501. scene._proceduralTextures.push(this);
  19502. this.name = name;
  19503. this.isRenderTarget = true;
  19504. this._size = size;
  19505. this._generateMipMaps = generateMipMaps;
  19506. this.setFragment(fragment);
  19507. this._fallbackTexture = fallbackTexture;
  19508. if (isCube) {
  19509. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  19510. this.setFloat("face", 0);
  19511. }
  19512. else {
  19513. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  19514. }
  19515. // VBO
  19516. var vertices = [];
  19517. vertices.push(1, 1);
  19518. vertices.push(-1, 1);
  19519. vertices.push(-1, -1);
  19520. vertices.push(1, -1);
  19521. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19522. // Indices
  19523. var indices = [];
  19524. indices.push(0);
  19525. indices.push(1);
  19526. indices.push(2);
  19527. indices.push(0);
  19528. indices.push(2);
  19529. indices.push(3);
  19530. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19531. }
  19532. ProceduralTexture.prototype.reset = function () {
  19533. if (this._effect === undefined) {
  19534. return;
  19535. }
  19536. var engine = this.getScene().getEngine();
  19537. engine._releaseEffect(this._effect);
  19538. };
  19539. ProceduralTexture.prototype.isReady = function () {
  19540. var _this = this;
  19541. var engine = this.getScene().getEngine();
  19542. var shaders;
  19543. if (!this._fragment) {
  19544. return false;
  19545. }
  19546. if (this._fallbackTextureUsed) {
  19547. return true;
  19548. }
  19549. if (this._fragment.fragmentElement !== undefined) {
  19550. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  19551. }
  19552. else {
  19553. shaders = { vertex: "procedural", fragment: this._fragment };
  19554. }
  19555. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  19556. _this.releaseInternalTexture();
  19557. if (_this._fallbackTexture) {
  19558. _this._texture = _this._fallbackTexture._texture;
  19559. _this._texture.references++;
  19560. }
  19561. _this._fallbackTextureUsed = true;
  19562. });
  19563. return this._effect.isReady();
  19564. };
  19565. ProceduralTexture.prototype.resetRefreshCounter = function () {
  19566. this._currentRefreshId = -1;
  19567. };
  19568. ProceduralTexture.prototype.setFragment = function (fragment) {
  19569. this._fragment = fragment;
  19570. };
  19571. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  19572. get: function () {
  19573. return this._refreshRate;
  19574. },
  19575. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  19576. set: function (value) {
  19577. this._refreshRate = value;
  19578. this.resetRefreshCounter();
  19579. },
  19580. enumerable: true,
  19581. configurable: true
  19582. });
  19583. ProceduralTexture.prototype._shouldRender = function () {
  19584. if (!this.isEnabled || !this.isReady() || !this._texture) {
  19585. return false;
  19586. }
  19587. if (this._fallbackTextureUsed) {
  19588. return false;
  19589. }
  19590. if (this._currentRefreshId === -1) {
  19591. this._currentRefreshId = 1;
  19592. return true;
  19593. }
  19594. if (this.refreshRate === this._currentRefreshId) {
  19595. this._currentRefreshId = 1;
  19596. return true;
  19597. }
  19598. this._currentRefreshId++;
  19599. return false;
  19600. };
  19601. ProceduralTexture.prototype.getRenderSize = function () {
  19602. return this._size;
  19603. };
  19604. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  19605. if (this._fallbackTextureUsed) {
  19606. return;
  19607. }
  19608. this.releaseInternalTexture();
  19609. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  19610. };
  19611. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  19612. if (this._uniforms.indexOf(uniformName) === -1) {
  19613. this._uniforms.push(uniformName);
  19614. }
  19615. };
  19616. ProceduralTexture.prototype.setTexture = function (name, texture) {
  19617. if (this._samplers.indexOf(name) === -1) {
  19618. this._samplers.push(name);
  19619. }
  19620. this._textures[name] = texture;
  19621. return this;
  19622. };
  19623. ProceduralTexture.prototype.setFloat = function (name, value) {
  19624. this._checkUniform(name);
  19625. this._floats[name] = value;
  19626. return this;
  19627. };
  19628. ProceduralTexture.prototype.setFloats = function (name, value) {
  19629. this._checkUniform(name);
  19630. this._floatsArrays[name] = value;
  19631. return this;
  19632. };
  19633. ProceduralTexture.prototype.setColor3 = function (name, value) {
  19634. this._checkUniform(name);
  19635. this._colors3[name] = value;
  19636. return this;
  19637. };
  19638. ProceduralTexture.prototype.setColor4 = function (name, value) {
  19639. this._checkUniform(name);
  19640. this._colors4[name] = value;
  19641. return this;
  19642. };
  19643. ProceduralTexture.prototype.setVector2 = function (name, value) {
  19644. this._checkUniform(name);
  19645. this._vectors2[name] = value;
  19646. return this;
  19647. };
  19648. ProceduralTexture.prototype.setVector3 = function (name, value) {
  19649. this._checkUniform(name);
  19650. this._vectors3[name] = value;
  19651. return this;
  19652. };
  19653. ProceduralTexture.prototype.setMatrix = function (name, value) {
  19654. this._checkUniform(name);
  19655. this._matrices[name] = value;
  19656. return this;
  19657. };
  19658. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  19659. var scene = this.getScene();
  19660. var engine = scene.getEngine();
  19661. // Render
  19662. engine.enableEffect(this._effect);
  19663. engine.setState(false);
  19664. // Texture
  19665. for (var name in this._textures) {
  19666. this._effect.setTexture(name, this._textures[name]);
  19667. }
  19668. // Float
  19669. for (name in this._floats) {
  19670. this._effect.setFloat(name, this._floats[name]);
  19671. }
  19672. // Floats
  19673. for (name in this._floatsArrays) {
  19674. this._effect.setArray(name, this._floatsArrays[name]);
  19675. }
  19676. // Color3
  19677. for (name in this._colors3) {
  19678. this._effect.setColor3(name, this._colors3[name]);
  19679. }
  19680. // Color4
  19681. for (name in this._colors4) {
  19682. var color = this._colors4[name];
  19683. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19684. }
  19685. // Vector2
  19686. for (name in this._vectors2) {
  19687. this._effect.setVector2(name, this._vectors2[name]);
  19688. }
  19689. // Vector3
  19690. for (name in this._vectors3) {
  19691. this._effect.setVector3(name, this._vectors3[name]);
  19692. }
  19693. // Matrix
  19694. for (name in this._matrices) {
  19695. this._effect.setMatrix(name, this._matrices[name]);
  19696. }
  19697. // VBOs
  19698. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19699. if (this.isCube) {
  19700. for (var face = 0; face < 6; face++) {
  19701. engine.bindFramebuffer(this._texture, face);
  19702. this._effect.setFloat("face", face);
  19703. // Clear
  19704. engine.clear(scene.clearColor, true, true);
  19705. // Draw order
  19706. engine.draw(true, 0, 6);
  19707. // Mipmaps
  19708. if (face === 5) {
  19709. engine.generateMipMapsForCubemap(this._texture);
  19710. }
  19711. }
  19712. }
  19713. else {
  19714. engine.bindFramebuffer(this._texture);
  19715. // Clear
  19716. engine.clear(scene.clearColor, true, true);
  19717. // Draw order
  19718. engine.draw(true, 0, 6);
  19719. }
  19720. // Unbind
  19721. engine.unBindFramebuffer(this._texture, this.isCube);
  19722. if (this.onGenerated) {
  19723. this.onGenerated();
  19724. }
  19725. };
  19726. ProceduralTexture.prototype.clone = function () {
  19727. var textureSize = this.getSize();
  19728. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  19729. // Base texture
  19730. newTexture.hasAlpha = this.hasAlpha;
  19731. newTexture.level = this.level;
  19732. // RenderTarget Texture
  19733. newTexture.coordinatesMode = this.coordinatesMode;
  19734. return newTexture;
  19735. };
  19736. ProceduralTexture.prototype.dispose = function () {
  19737. var index = this.getScene()._proceduralTextures.indexOf(this);
  19738. if (index >= 0) {
  19739. this.getScene()._proceduralTextures.splice(index, 1);
  19740. }
  19741. _super.prototype.dispose.call(this);
  19742. };
  19743. return ProceduralTexture;
  19744. })(BABYLON.Texture);
  19745. BABYLON.ProceduralTexture = ProceduralTexture;
  19746. })(BABYLON || (BABYLON = {}));
  19747. var BABYLON;
  19748. (function (BABYLON) {
  19749. var MirrorTexture = (function (_super) {
  19750. __extends(MirrorTexture, _super);
  19751. function MirrorTexture(name, size, scene, generateMipMaps) {
  19752. var _this = this;
  19753. _super.call(this, name, size, scene, generateMipMaps, true);
  19754. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  19755. this._transformMatrix = BABYLON.Matrix.Zero();
  19756. this._mirrorMatrix = BABYLON.Matrix.Zero();
  19757. this.onBeforeRender = function () {
  19758. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  19759. _this._savedViewMatrix = scene.getViewMatrix();
  19760. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  19761. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  19762. scene.clipPlane = _this.mirrorPlane;
  19763. scene.getEngine().cullBackFaces = false;
  19764. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  19765. };
  19766. this.onAfterRender = function () {
  19767. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  19768. scene.getEngine().cullBackFaces = true;
  19769. scene._mirroredCameraPosition = null;
  19770. delete scene.clipPlane;
  19771. };
  19772. }
  19773. MirrorTexture.prototype.clone = function () {
  19774. var textureSize = this.getSize();
  19775. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19776. // Base texture
  19777. newTexture.hasAlpha = this.hasAlpha;
  19778. newTexture.level = this.level;
  19779. // Mirror Texture
  19780. newTexture.mirrorPlane = this.mirrorPlane.clone();
  19781. newTexture.renderList = this.renderList.slice(0);
  19782. return newTexture;
  19783. };
  19784. MirrorTexture.prototype.serialize = function () {
  19785. if (!this.name) {
  19786. return null;
  19787. }
  19788. var serializationObject = _super.prototype.serialize.call(this);
  19789. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  19790. return serializationObject;
  19791. };
  19792. return MirrorTexture;
  19793. })(BABYLON.RenderTargetTexture);
  19794. BABYLON.MirrorTexture = MirrorTexture;
  19795. })(BABYLON || (BABYLON = {}));
  19796. var BABYLON;
  19797. (function (BABYLON) {
  19798. /**
  19799. * Creates a refraction texture used by refraction channel of the standard material.
  19800. * @param name the texture name
  19801. * @param size size of the underlying texture
  19802. * @param scene root scene
  19803. */
  19804. var RefractionTexture = (function (_super) {
  19805. __extends(RefractionTexture, _super);
  19806. function RefractionTexture(name, size, scene, generateMipMaps) {
  19807. var _this = this;
  19808. _super.call(this, name, size, scene, generateMipMaps, true);
  19809. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  19810. this.depth = 2.0;
  19811. this.onBeforeRender = function () {
  19812. scene.clipPlane = _this.refractionPlane;
  19813. };
  19814. this.onAfterRender = function () {
  19815. delete scene.clipPlane;
  19816. };
  19817. }
  19818. RefractionTexture.prototype.clone = function () {
  19819. var textureSize = this.getSize();
  19820. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19821. // Base texture
  19822. newTexture.hasAlpha = this.hasAlpha;
  19823. newTexture.level = this.level;
  19824. // Refraction Texture
  19825. newTexture.refractionPlane = this.refractionPlane.clone();
  19826. newTexture.renderList = this.renderList.slice(0);
  19827. newTexture.depth = this.depth;
  19828. return newTexture;
  19829. };
  19830. RefractionTexture.prototype.serialize = function () {
  19831. if (!this.name) {
  19832. return null;
  19833. }
  19834. var serializationObject = _super.prototype.serialize.call(this);
  19835. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  19836. serializationObject.depth = this.depth;
  19837. return serializationObject;
  19838. };
  19839. return RefractionTexture;
  19840. })(BABYLON.RenderTargetTexture);
  19841. BABYLON.RefractionTexture = RefractionTexture;
  19842. })(BABYLON || (BABYLON = {}));
  19843. var BABYLON;
  19844. (function (BABYLON) {
  19845. var DynamicTexture = (function (_super) {
  19846. __extends(DynamicTexture, _super);
  19847. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  19848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19849. _super.call(this, null, scene, !generateMipMaps);
  19850. this.name = name;
  19851. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19852. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19853. this._generateMipMaps = generateMipMaps;
  19854. if (options.getContext) {
  19855. this._canvas = options;
  19856. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  19857. }
  19858. else {
  19859. this._canvas = document.createElement("canvas");
  19860. if (options.width) {
  19861. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  19862. }
  19863. else {
  19864. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  19865. }
  19866. }
  19867. var textureSize = this.getSize();
  19868. this._canvas.width = textureSize.width;
  19869. this._canvas.height = textureSize.height;
  19870. this._context = this._canvas.getContext("2d");
  19871. }
  19872. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  19873. get: function () {
  19874. return true;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. DynamicTexture.prototype.scale = function (ratio) {
  19880. var textureSize = this.getSize();
  19881. textureSize.width *= ratio;
  19882. textureSize.height *= ratio;
  19883. this._canvas.width = textureSize.width;
  19884. this._canvas.height = textureSize.height;
  19885. this.releaseInternalTexture();
  19886. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  19887. };
  19888. DynamicTexture.prototype.getContext = function () {
  19889. return this._context;
  19890. };
  19891. DynamicTexture.prototype.clear = function () {
  19892. var size = this.getSize();
  19893. this._context.fillRect(0, 0, size.width, size.height);
  19894. };
  19895. DynamicTexture.prototype.update = function (invertY) {
  19896. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  19897. };
  19898. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  19899. if (update === void 0) { update = true; }
  19900. var size = this.getSize();
  19901. if (clearColor) {
  19902. this._context.fillStyle = clearColor;
  19903. this._context.fillRect(0, 0, size.width, size.height);
  19904. }
  19905. this._context.font = font;
  19906. if (x === null) {
  19907. var textSize = this._context.measureText(text);
  19908. x = (size.width - textSize.width) / 2;
  19909. }
  19910. this._context.fillStyle = color;
  19911. this._context.fillText(text, x, y);
  19912. if (update) {
  19913. this.update(invertY);
  19914. }
  19915. };
  19916. DynamicTexture.prototype.clone = function () {
  19917. var textureSize = this.getSize();
  19918. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19919. // Base texture
  19920. newTexture.hasAlpha = this.hasAlpha;
  19921. newTexture.level = this.level;
  19922. // Dynamic Texture
  19923. newTexture.wrapU = this.wrapU;
  19924. newTexture.wrapV = this.wrapV;
  19925. return newTexture;
  19926. };
  19927. return DynamicTexture;
  19928. })(BABYLON.Texture);
  19929. BABYLON.DynamicTexture = DynamicTexture;
  19930. })(BABYLON || (BABYLON = {}));
  19931. var BABYLON;
  19932. (function (BABYLON) {
  19933. var VideoTexture = (function (_super) {
  19934. __extends(VideoTexture, _super);
  19935. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  19936. var _this = this;
  19937. if (generateMipMaps === void 0) { generateMipMaps = false; }
  19938. if (invertY === void 0) { invertY = false; }
  19939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19940. _super.call(this, null, scene, !generateMipMaps, invertY);
  19941. this._autoLaunch = true;
  19942. this.name = name;
  19943. this.video = document.createElement("video");
  19944. this.video.autoplay = false;
  19945. this.video.loop = true;
  19946. this.video.addEventListener("canplaythrough", function () {
  19947. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  19948. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19949. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19950. }
  19951. else {
  19952. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19953. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19954. generateMipMaps = false;
  19955. }
  19956. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  19957. _this._texture.isReady = true;
  19958. });
  19959. urls.forEach(function (url) {
  19960. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  19961. var source = document.createElement("source");
  19962. source.src = url;
  19963. _this.video.appendChild(source);
  19964. });
  19965. this._lastUpdate = BABYLON.Tools.Now;
  19966. }
  19967. VideoTexture.prototype.update = function () {
  19968. if (this._autoLaunch) {
  19969. this._autoLaunch = false;
  19970. this.video.play();
  19971. }
  19972. var now = BABYLON.Tools.Now;
  19973. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  19974. return false;
  19975. }
  19976. this._lastUpdate = now;
  19977. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  19978. return true;
  19979. };
  19980. return VideoTexture;
  19981. })(BABYLON.Texture);
  19982. BABYLON.VideoTexture = VideoTexture;
  19983. })(BABYLON || (BABYLON = {}));
  19984. var BABYLON;
  19985. (function (BABYLON) {
  19986. var CustomProceduralTexture = (function (_super) {
  19987. __extends(CustomProceduralTexture, _super);
  19988. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  19989. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  19990. this._animate = true;
  19991. this._time = 0;
  19992. this._texturePath = texturePath;
  19993. //Try to load json
  19994. this.loadJson(texturePath);
  19995. this.refreshRate = 1;
  19996. }
  19997. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  19998. var _this = this;
  19999. var that = this;
  20000. function noConfigFile() {
  20001. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  20002. try {
  20003. that.setFragment(that._texturePath);
  20004. }
  20005. catch (ex) {
  20006. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  20007. }
  20008. }
  20009. var configFileUrl = jsonUrl + "/config.json";
  20010. var xhr = new XMLHttpRequest();
  20011. xhr.open("GET", configFileUrl, true);
  20012. xhr.addEventListener("load", function () {
  20013. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  20014. try {
  20015. _this._config = JSON.parse(xhr.response);
  20016. _this.updateShaderUniforms();
  20017. _this.updateTextures();
  20018. _this.setFragment(_this._texturePath + "/custom");
  20019. _this._animate = _this._config.animate;
  20020. _this.refreshRate = _this._config.refreshrate;
  20021. }
  20022. catch (ex) {
  20023. noConfigFile();
  20024. }
  20025. }
  20026. else {
  20027. noConfigFile();
  20028. }
  20029. }, false);
  20030. xhr.addEventListener("error", function () {
  20031. noConfigFile();
  20032. }, false);
  20033. try {
  20034. xhr.send();
  20035. }
  20036. catch (ex) {
  20037. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  20038. }
  20039. };
  20040. CustomProceduralTexture.prototype.isReady = function () {
  20041. if (!_super.prototype.isReady.call(this)) {
  20042. return false;
  20043. }
  20044. for (var name in this._textures) {
  20045. var texture = this._textures[name];
  20046. if (!texture.isReady()) {
  20047. return false;
  20048. }
  20049. }
  20050. return true;
  20051. };
  20052. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  20053. if (this._animate) {
  20054. this._time += this.getScene().getAnimationRatio() * 0.03;
  20055. this.updateShaderUniforms();
  20056. }
  20057. _super.prototype.render.call(this, useCameraPostProcess);
  20058. };
  20059. CustomProceduralTexture.prototype.updateTextures = function () {
  20060. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  20061. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  20062. }
  20063. };
  20064. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  20065. if (this._config) {
  20066. for (var j = 0; j < this._config.uniforms.length; j++) {
  20067. var uniform = this._config.uniforms[j];
  20068. switch (uniform.type) {
  20069. case "float":
  20070. this.setFloat(uniform.name, uniform.value);
  20071. break;
  20072. case "color3":
  20073. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  20074. break;
  20075. case "color4":
  20076. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  20077. break;
  20078. case "vector2":
  20079. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  20080. break;
  20081. case "vector3":
  20082. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  20083. break;
  20084. }
  20085. }
  20086. }
  20087. this.setFloat("time", this._time);
  20088. };
  20089. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  20090. get: function () {
  20091. return this._animate;
  20092. },
  20093. set: function (value) {
  20094. this._animate = value;
  20095. },
  20096. enumerable: true,
  20097. configurable: true
  20098. });
  20099. return CustomProceduralTexture;
  20100. })(BABYLON.ProceduralTexture);
  20101. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  20102. })(BABYLON || (BABYLON = {}));
  20103. var BABYLON;
  20104. (function (BABYLON) {
  20105. var EffectFallbacks = (function () {
  20106. function EffectFallbacks() {
  20107. this._defines = {};
  20108. this._currentRank = 32;
  20109. this._maxRank = -1;
  20110. }
  20111. EffectFallbacks.prototype.addFallback = function (rank, define) {
  20112. if (!this._defines[rank]) {
  20113. if (rank < this._currentRank) {
  20114. this._currentRank = rank;
  20115. }
  20116. if (rank > this._maxRank) {
  20117. this._maxRank = rank;
  20118. }
  20119. this._defines[rank] = new Array();
  20120. }
  20121. this._defines[rank].push(define);
  20122. };
  20123. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  20124. this._meshRank = rank;
  20125. this._mesh = mesh;
  20126. if (rank > this._maxRank) {
  20127. this._maxRank = rank;
  20128. }
  20129. };
  20130. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  20131. get: function () {
  20132. return this._currentRank <= this._maxRank;
  20133. },
  20134. enumerable: true,
  20135. configurable: true
  20136. });
  20137. EffectFallbacks.prototype.reduce = function (currentDefines) {
  20138. var currentFallbacks = this._defines[this._currentRank];
  20139. for (var index = 0; index < currentFallbacks.length; index++) {
  20140. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  20141. }
  20142. if (this._mesh && this._currentRank === this._meshRank) {
  20143. this._mesh.computeBonesUsingShaders = false;
  20144. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  20145. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  20146. }
  20147. this._currentRank++;
  20148. return currentDefines;
  20149. };
  20150. return EffectFallbacks;
  20151. })();
  20152. BABYLON.EffectFallbacks = EffectFallbacks;
  20153. var Effect = (function () {
  20154. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  20155. var _this = this;
  20156. this._isReady = false;
  20157. this._compilationError = "";
  20158. this._valueCache = [];
  20159. this._engine = engine;
  20160. this.name = baseName;
  20161. this.defines = defines;
  20162. this._uniformsNames = uniformsNames.concat(samplers);
  20163. this._samplers = samplers;
  20164. this._attributesNames = attributesNames;
  20165. this.onError = onError;
  20166. this.onCompiled = onCompiled;
  20167. var vertexSource;
  20168. var fragmentSource;
  20169. if (baseName.vertexElement) {
  20170. vertexSource = document.getElementById(baseName.vertexElement);
  20171. if (!vertexSource) {
  20172. vertexSource = baseName.vertexElement;
  20173. }
  20174. }
  20175. else {
  20176. vertexSource = baseName.vertex || baseName;
  20177. }
  20178. if (baseName.fragmentElement) {
  20179. fragmentSource = document.getElementById(baseName.fragmentElement);
  20180. if (!fragmentSource) {
  20181. fragmentSource = baseName.fragmentElement;
  20182. }
  20183. }
  20184. else {
  20185. fragmentSource = baseName.fragment || baseName;
  20186. }
  20187. this._loadVertexShader(vertexSource, function (vertexCode) {
  20188. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  20189. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  20190. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  20191. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  20192. });
  20193. });
  20194. });
  20195. });
  20196. }
  20197. // Properties
  20198. Effect.prototype.isReady = function () {
  20199. return this._isReady;
  20200. };
  20201. Effect.prototype.getProgram = function () {
  20202. return this._program;
  20203. };
  20204. Effect.prototype.getAttributesNames = function () {
  20205. return this._attributesNames;
  20206. };
  20207. Effect.prototype.getAttributeLocation = function (index) {
  20208. return this._attributes[index];
  20209. };
  20210. Effect.prototype.getAttributeLocationByName = function (name) {
  20211. var index = this._attributesNames.indexOf(name);
  20212. return this._attributes[index];
  20213. };
  20214. Effect.prototype.getAttributesCount = function () {
  20215. return this._attributes.length;
  20216. };
  20217. Effect.prototype.getUniformIndex = function (uniformName) {
  20218. return this._uniformsNames.indexOf(uniformName);
  20219. };
  20220. Effect.prototype.getUniform = function (uniformName) {
  20221. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  20222. };
  20223. Effect.prototype.getSamplers = function () {
  20224. return this._samplers;
  20225. };
  20226. Effect.prototype.getCompilationError = function () {
  20227. return this._compilationError;
  20228. };
  20229. // Methods
  20230. Effect.prototype._loadVertexShader = function (vertex, callback) {
  20231. // DOM element ?
  20232. if (vertex instanceof HTMLElement) {
  20233. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  20234. callback(vertexCode);
  20235. return;
  20236. }
  20237. // Is in local store ?
  20238. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  20239. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  20240. return;
  20241. }
  20242. var vertexShaderUrl;
  20243. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  20244. vertexShaderUrl = vertex;
  20245. }
  20246. else {
  20247. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  20248. }
  20249. // Vertex shader
  20250. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  20251. };
  20252. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  20253. // DOM element ?
  20254. if (fragment instanceof HTMLElement) {
  20255. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  20256. callback(fragmentCode);
  20257. return;
  20258. }
  20259. // Is in local store ?
  20260. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  20261. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  20262. return;
  20263. }
  20264. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  20265. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  20266. return;
  20267. }
  20268. var fragmentShaderUrl;
  20269. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  20270. fragmentShaderUrl = fragment;
  20271. }
  20272. else {
  20273. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  20274. }
  20275. // Fragment shader
  20276. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  20277. };
  20278. Effect.prototype._dumpShadersName = function () {
  20279. if (this.name.vertexElement) {
  20280. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  20281. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  20282. }
  20283. else if (this.name.vertex) {
  20284. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  20285. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  20286. }
  20287. else {
  20288. BABYLON.Tools.Error("Vertex shader:" + this.name);
  20289. BABYLON.Tools.Error("Fragment shader:" + this.name);
  20290. }
  20291. };
  20292. Effect.prototype._processIncludes = function (sourceCode, callback) {
  20293. var _this = this;
  20294. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  20295. var match = regex.exec(sourceCode);
  20296. var returnValue = new String(sourceCode);
  20297. while (match != null) {
  20298. var includeFile = match[1];
  20299. if (Effect.IncludesShadersStore[includeFile]) {
  20300. // Substitution
  20301. var includeContent = Effect.IncludesShadersStore[includeFile];
  20302. if (match[2]) {
  20303. var splits = match[3].split(",");
  20304. for (var index = 0; index < splits.length; index += 2) {
  20305. var source = new RegExp(splits[index], "g");
  20306. var dest = splits[index + 1];
  20307. includeContent = includeContent.replace(source, dest);
  20308. }
  20309. }
  20310. if (match[4]) {
  20311. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  20312. }
  20313. // Replace
  20314. returnValue = returnValue.replace(match[0], includeContent);
  20315. }
  20316. else {
  20317. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  20318. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  20319. Effect.IncludesShadersStore[includeFile] = fileContent;
  20320. _this._processIncludes(returnValue, callback);
  20321. });
  20322. return;
  20323. }
  20324. match = regex.exec(sourceCode);
  20325. }
  20326. callback(returnValue);
  20327. };
  20328. Effect.prototype._processPrecision = function (source) {
  20329. if (source.indexOf("precision highp float") === -1) {
  20330. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  20331. source = "precision mediump float;\n" + source;
  20332. }
  20333. else {
  20334. source = "precision highp float;\n" + source;
  20335. }
  20336. }
  20337. else {
  20338. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  20339. source = source.replace("precision highp float", "precision mediump float");
  20340. }
  20341. }
  20342. return source;
  20343. };
  20344. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  20345. try {
  20346. var engine = this._engine;
  20347. // Precision
  20348. vertexSourceCode = this._processPrecision(vertexSourceCode);
  20349. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  20350. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  20351. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  20352. this._attributes = engine.getAttributes(this._program, attributesNames);
  20353. for (var index = 0; index < this._samplers.length; index++) {
  20354. var sampler = this.getUniform(this._samplers[index]);
  20355. if (sampler == null) {
  20356. this._samplers.splice(index, 1);
  20357. index--;
  20358. }
  20359. }
  20360. engine.bindSamplers(this);
  20361. this._isReady = true;
  20362. if (this.onCompiled) {
  20363. this.onCompiled(this);
  20364. }
  20365. }
  20366. catch (e) {
  20367. // Is it a problem with precision?
  20368. if (e.message.indexOf("highp") !== -1) {
  20369. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  20370. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  20371. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  20372. return;
  20373. }
  20374. // Let's go through fallbacks then
  20375. if (fallbacks && fallbacks.isMoreFallbacks) {
  20376. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  20377. this._dumpShadersName();
  20378. defines = fallbacks.reduce(defines);
  20379. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  20380. }
  20381. else {
  20382. BABYLON.Tools.Error("Unable to compile effect: ");
  20383. this._dumpShadersName();
  20384. BABYLON.Tools.Error("Defines: " + defines);
  20385. BABYLON.Tools.Error("Error: " + e.message);
  20386. this._compilationError = e.message;
  20387. if (this.onError) {
  20388. this.onError(this, this._compilationError);
  20389. }
  20390. }
  20391. }
  20392. };
  20393. Object.defineProperty(Effect.prototype, "isSupported", {
  20394. get: function () {
  20395. return this._compilationError === "";
  20396. },
  20397. enumerable: true,
  20398. configurable: true
  20399. });
  20400. Effect.prototype._bindTexture = function (channel, texture) {
  20401. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  20402. };
  20403. Effect.prototype.setTexture = function (channel, texture) {
  20404. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  20405. };
  20406. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  20407. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  20408. };
  20409. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  20410. if (!this._valueCache[uniformName]) {
  20411. this._valueCache[uniformName] = new BABYLON.Matrix();
  20412. }
  20413. for (var index = 0; index < 16; index++) {
  20414. this._valueCache[uniformName].m[index] = matrix.m[index];
  20415. }
  20416. };
  20417. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  20418. if (!this._valueCache[uniformName]) {
  20419. this._valueCache[uniformName] = [x, y];
  20420. return;
  20421. }
  20422. this._valueCache[uniformName][0] = x;
  20423. this._valueCache[uniformName][1] = y;
  20424. };
  20425. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  20426. if (!this._valueCache[uniformName]) {
  20427. this._valueCache[uniformName] = [x, y, z];
  20428. return;
  20429. }
  20430. this._valueCache[uniformName][0] = x;
  20431. this._valueCache[uniformName][1] = y;
  20432. this._valueCache[uniformName][2] = z;
  20433. };
  20434. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  20435. if (!this._valueCache[uniformName]) {
  20436. this._valueCache[uniformName] = [x, y, z, w];
  20437. return;
  20438. }
  20439. this._valueCache[uniformName][0] = x;
  20440. this._valueCache[uniformName][1] = y;
  20441. this._valueCache[uniformName][2] = z;
  20442. this._valueCache[uniformName][3] = w;
  20443. };
  20444. Effect.prototype.setArray = function (uniformName, array) {
  20445. this._engine.setArray(this.getUniform(uniformName), array);
  20446. return this;
  20447. };
  20448. Effect.prototype.setArray2 = function (uniformName, array) {
  20449. this._engine.setArray2(this.getUniform(uniformName), array);
  20450. return this;
  20451. };
  20452. Effect.prototype.setArray3 = function (uniformName, array) {
  20453. this._engine.setArray3(this.getUniform(uniformName), array);
  20454. return this;
  20455. };
  20456. Effect.prototype.setArray4 = function (uniformName, array) {
  20457. this._engine.setArray4(this.getUniform(uniformName), array);
  20458. return this;
  20459. };
  20460. Effect.prototype.setMatrices = function (uniformName, matrices) {
  20461. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  20462. return this;
  20463. };
  20464. Effect.prototype.setMatrix = function (uniformName, matrix) {
  20465. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  20466. // return this;
  20467. // this._cacheMatrix(uniformName, matrix);
  20468. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  20469. return this;
  20470. };
  20471. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  20472. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  20473. return this;
  20474. };
  20475. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  20476. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  20477. return this;
  20478. };
  20479. Effect.prototype.setFloat = function (uniformName, value) {
  20480. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  20481. return this;
  20482. this._valueCache[uniformName] = value;
  20483. this._engine.setFloat(this.getUniform(uniformName), value);
  20484. return this;
  20485. };
  20486. Effect.prototype.setBool = function (uniformName, bool) {
  20487. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  20488. return this;
  20489. this._valueCache[uniformName] = bool;
  20490. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  20491. return this;
  20492. };
  20493. Effect.prototype.setVector2 = function (uniformName, vector2) {
  20494. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  20495. return this;
  20496. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  20497. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  20498. return this;
  20499. };
  20500. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  20501. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  20502. return this;
  20503. this._cacheFloat2(uniformName, x, y);
  20504. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  20505. return this;
  20506. };
  20507. Effect.prototype.setVector3 = function (uniformName, vector3) {
  20508. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  20509. return this;
  20510. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  20511. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  20512. return this;
  20513. };
  20514. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  20515. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  20516. return this;
  20517. this._cacheFloat3(uniformName, x, y, z);
  20518. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  20519. return this;
  20520. };
  20521. Effect.prototype.setVector4 = function (uniformName, vector4) {
  20522. 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)
  20523. return this;
  20524. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  20525. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  20526. return this;
  20527. };
  20528. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  20529. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  20530. return this;
  20531. this._cacheFloat4(uniformName, x, y, z, w);
  20532. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  20533. return this;
  20534. };
  20535. Effect.prototype.setColor3 = function (uniformName, color3) {
  20536. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  20537. return this;
  20538. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  20539. this._engine.setColor3(this.getUniform(uniformName), color3);
  20540. return this;
  20541. };
  20542. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  20543. 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)
  20544. return this;
  20545. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  20546. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  20547. return this;
  20548. };
  20549. // Statics
  20550. Effect.ShadersStore = {};
  20551. Effect.IncludesShadersStore = {};
  20552. return Effect;
  20553. })();
  20554. BABYLON.Effect = Effect;
  20555. })(BABYLON || (BABYLON = {}));
  20556. var BABYLON;
  20557. (function (BABYLON) {
  20558. var maxSimultaneousLights = 4;
  20559. var MaterialHelper = (function () {
  20560. function MaterialHelper() {
  20561. }
  20562. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  20563. var lightIndex = 0;
  20564. var needNormals = false;
  20565. for (var index = 0; index < scene.lights.length; index++) {
  20566. var light = scene.lights[index];
  20567. if (!light.isEnabled()) {
  20568. continue;
  20569. }
  20570. // Excluded check
  20571. if (light._excludedMeshesIds.length > 0) {
  20572. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  20573. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  20574. if (excludedMesh) {
  20575. light.excludedMeshes.push(excludedMesh);
  20576. }
  20577. }
  20578. light._excludedMeshesIds = [];
  20579. }
  20580. // Included check
  20581. if (light._includedOnlyMeshesIds.length > 0) {
  20582. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  20583. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  20584. if (includedOnlyMesh) {
  20585. light.includedOnlyMeshes.push(includedOnlyMesh);
  20586. }
  20587. }
  20588. light._includedOnlyMeshesIds = [];
  20589. }
  20590. if (!light.canAffectMesh(mesh)) {
  20591. continue;
  20592. }
  20593. needNormals = true;
  20594. defines["LIGHT" + lightIndex] = true;
  20595. var type;
  20596. if (light instanceof BABYLON.SpotLight) {
  20597. type = "SPOTLIGHT" + lightIndex;
  20598. }
  20599. else if (light instanceof BABYLON.HemisphericLight) {
  20600. type = "HEMILIGHT" + lightIndex;
  20601. }
  20602. else if (light instanceof BABYLON.PointLight) {
  20603. type = "POINTLIGHT" + lightIndex;
  20604. }
  20605. else {
  20606. type = "DIRLIGHT" + lightIndex;
  20607. }
  20608. defines[type] = true;
  20609. // Specular
  20610. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  20611. defines["SPECULARTERM"] = true;
  20612. }
  20613. // Shadows
  20614. if (scene.shadowsEnabled) {
  20615. var shadowGenerator = light.getShadowGenerator();
  20616. if (mesh && mesh.receiveShadows && shadowGenerator) {
  20617. defines["SHADOW" + lightIndex] = true;
  20618. defines["SHADOWS"] = true;
  20619. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  20620. defines["SHADOWVSM" + lightIndex] = true;
  20621. }
  20622. if (shadowGenerator.usePoissonSampling) {
  20623. defines["SHADOWPCF" + lightIndex] = true;
  20624. }
  20625. }
  20626. }
  20627. lightIndex++;
  20628. if (lightIndex === maxSimultaneousLights)
  20629. break;
  20630. }
  20631. return needNormals;
  20632. };
  20633. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  20634. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  20635. if (!defines["LIGHT" + lightIndex]) {
  20636. continue;
  20637. }
  20638. if (lightIndex > 0) {
  20639. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  20640. }
  20641. if (defines["SHADOW" + lightIndex]) {
  20642. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  20643. }
  20644. if (defines["SHADOWPCF" + lightIndex]) {
  20645. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  20646. }
  20647. if (defines["SHADOWVSM" + lightIndex]) {
  20648. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  20649. }
  20650. }
  20651. };
  20652. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  20653. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  20654. fallbacks.addCPUSkinningFallback(0, mesh);
  20655. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20656. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20657. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  20658. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  20659. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  20660. }
  20661. }
  20662. };
  20663. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  20664. if (defines["INSTANCES"]) {
  20665. attribs.push("world0");
  20666. attribs.push("world1");
  20667. attribs.push("world2");
  20668. attribs.push("world3");
  20669. }
  20670. };
  20671. // Bindings
  20672. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  20673. var shadowGenerator = light.getShadowGenerator();
  20674. if (mesh.receiveShadows && shadowGenerator) {
  20675. if (!light.needCube()) {
  20676. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  20677. }
  20678. else {
  20679. if (!depthValuesAlreadySet) {
  20680. depthValuesAlreadySet = true;
  20681. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  20682. }
  20683. }
  20684. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  20685. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  20686. }
  20687. return depthValuesAlreadySet;
  20688. };
  20689. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  20690. if (light instanceof BABYLON.PointLight) {
  20691. // Point Light
  20692. light.transferToEffect(effect, "vLightData" + lightIndex);
  20693. }
  20694. else if (light instanceof BABYLON.DirectionalLight) {
  20695. // Directional Light
  20696. light.transferToEffect(effect, "vLightData" + lightIndex);
  20697. }
  20698. else if (light instanceof BABYLON.SpotLight) {
  20699. // Spot Light
  20700. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  20701. }
  20702. else if (light instanceof BABYLON.HemisphericLight) {
  20703. // Hemispheric Light
  20704. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  20705. }
  20706. };
  20707. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  20708. var lightIndex = 0;
  20709. var depthValuesAlreadySet = false;
  20710. for (var index = 0; index < scene.lights.length; index++) {
  20711. var light = scene.lights[index];
  20712. if (!light.isEnabled()) {
  20713. continue;
  20714. }
  20715. if (!light.canAffectMesh(mesh)) {
  20716. continue;
  20717. }
  20718. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  20719. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  20720. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  20721. if (defines["SPECULARTERM"]) {
  20722. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  20723. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  20724. }
  20725. // Shadows
  20726. if (scene.shadowsEnabled) {
  20727. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  20728. }
  20729. lightIndex++;
  20730. if (lightIndex === maxSimultaneousLights)
  20731. break;
  20732. }
  20733. };
  20734. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  20735. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  20736. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  20737. effect.setColor3("vFogColor", scene.fogColor);
  20738. }
  20739. };
  20740. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  20741. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  20742. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  20743. }
  20744. };
  20745. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  20746. if (defines["LOGARITHMICDEPTH"]) {
  20747. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  20748. }
  20749. };
  20750. MaterialHelper.BindClipPlane = function (effect, scene) {
  20751. if (scene.clipPlane) {
  20752. var clipPlane = scene.clipPlane;
  20753. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20754. }
  20755. };
  20756. return MaterialHelper;
  20757. })();
  20758. BABYLON.MaterialHelper = MaterialHelper;
  20759. })(BABYLON || (BABYLON = {}));
  20760. var BABYLON;
  20761. (function (BABYLON) {
  20762. var FresnelParameters = (function () {
  20763. function FresnelParameters() {
  20764. this.isEnabled = true;
  20765. this.leftColor = BABYLON.Color3.White();
  20766. this.rightColor = BABYLON.Color3.Black();
  20767. this.bias = 0;
  20768. this.power = 1;
  20769. }
  20770. FresnelParameters.prototype.clone = function () {
  20771. var newFresnelParameters = new FresnelParameters();
  20772. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  20773. return new FresnelParameters;
  20774. };
  20775. FresnelParameters.prototype.serialize = function () {
  20776. var serializationObject = {};
  20777. serializationObject.isEnabled = this.isEnabled;
  20778. serializationObject.leftColor = this.leftColor;
  20779. serializationObject.rightColor = this.rightColor;
  20780. serializationObject.bias = this.bias;
  20781. serializationObject.power = this.power;
  20782. return serializationObject;
  20783. };
  20784. FresnelParameters.Parse = function (parsedFresnelParameters) {
  20785. var fresnelParameters = new FresnelParameters();
  20786. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  20787. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  20788. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  20789. fresnelParameters.bias = parsedFresnelParameters.bias;
  20790. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  20791. return fresnelParameters;
  20792. };
  20793. return FresnelParameters;
  20794. })();
  20795. BABYLON.FresnelParameters = FresnelParameters;
  20796. })(BABYLON || (BABYLON = {}));
  20797. var BABYLON;
  20798. (function (BABYLON) {
  20799. var MaterialDefines = (function () {
  20800. function MaterialDefines() {
  20801. }
  20802. MaterialDefines.prototype.isEqual = function (other) {
  20803. for (var index = 0; index < this._keys.length; index++) {
  20804. var prop = this._keys[index];
  20805. if (this[prop] !== other[prop]) {
  20806. return false;
  20807. }
  20808. }
  20809. return true;
  20810. };
  20811. MaterialDefines.prototype.cloneTo = function (other) {
  20812. for (var index = 0; index < this._keys.length; index++) {
  20813. var prop = this._keys[index];
  20814. other[prop] = this[prop];
  20815. }
  20816. };
  20817. MaterialDefines.prototype.reset = function () {
  20818. for (var index = 0; index < this._keys.length; index++) {
  20819. var prop = this._keys[index];
  20820. if (typeof (this[prop]) === "number") {
  20821. this[prop] = 0;
  20822. }
  20823. else {
  20824. this[prop] = false;
  20825. }
  20826. }
  20827. };
  20828. MaterialDefines.prototype.toString = function () {
  20829. var result = "";
  20830. for (var index = 0; index < this._keys.length; index++) {
  20831. var prop = this._keys[index];
  20832. if (typeof (this[prop]) === "number") {
  20833. result += "#define " + prop + " " + this[prop] + "\n";
  20834. }
  20835. else if (this[prop]) {
  20836. result += "#define " + prop + "\n";
  20837. }
  20838. }
  20839. return result;
  20840. };
  20841. return MaterialDefines;
  20842. })();
  20843. BABYLON.MaterialDefines = MaterialDefines;
  20844. var Material = (function () {
  20845. function Material(name, scene, doNotAdd) {
  20846. this.name = name;
  20847. this.checkReadyOnEveryCall = false;
  20848. this.checkReadyOnlyOnce = false;
  20849. this.state = "";
  20850. this.alpha = 1.0;
  20851. this.backFaceCulling = true;
  20852. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  20853. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  20854. this.disableDepthWrite = false;
  20855. this.fogEnabled = true;
  20856. this.pointSize = 1.0;
  20857. this.zOffset = 0;
  20858. this._wasPreviouslyReady = false;
  20859. this._fillMode = Material.TriangleFillMode;
  20860. this.id = name;
  20861. this._scene = scene;
  20862. if (!doNotAdd) {
  20863. scene.materials.push(this);
  20864. }
  20865. }
  20866. Object.defineProperty(Material, "TriangleFillMode", {
  20867. get: function () {
  20868. return Material._TriangleFillMode;
  20869. },
  20870. enumerable: true,
  20871. configurable: true
  20872. });
  20873. Object.defineProperty(Material, "WireFrameFillMode", {
  20874. get: function () {
  20875. return Material._WireFrameFillMode;
  20876. },
  20877. enumerable: true,
  20878. configurable: true
  20879. });
  20880. Object.defineProperty(Material, "PointFillMode", {
  20881. get: function () {
  20882. return Material._PointFillMode;
  20883. },
  20884. enumerable: true,
  20885. configurable: true
  20886. });
  20887. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  20888. get: function () {
  20889. return Material._ClockWiseSideOrientation;
  20890. },
  20891. enumerable: true,
  20892. configurable: true
  20893. });
  20894. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  20895. get: function () {
  20896. return Material._CounterClockWiseSideOrientation;
  20897. },
  20898. enumerable: true,
  20899. configurable: true
  20900. });
  20901. Object.defineProperty(Material.prototype, "wireframe", {
  20902. get: function () {
  20903. return this._fillMode === Material.WireFrameFillMode;
  20904. },
  20905. set: function (value) {
  20906. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  20907. },
  20908. enumerable: true,
  20909. configurable: true
  20910. });
  20911. Object.defineProperty(Material.prototype, "pointsCloud", {
  20912. get: function () {
  20913. return this._fillMode === Material.PointFillMode;
  20914. },
  20915. set: function (value) {
  20916. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  20917. },
  20918. enumerable: true,
  20919. configurable: true
  20920. });
  20921. Object.defineProperty(Material.prototype, "fillMode", {
  20922. get: function () {
  20923. return this._fillMode;
  20924. },
  20925. set: function (value) {
  20926. this._fillMode = value;
  20927. },
  20928. enumerable: true,
  20929. configurable: true
  20930. });
  20931. /**
  20932. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20933. * subclasses should override adding information pertainent to themselves
  20934. */
  20935. Material.prototype.toString = function (fullDetails) {
  20936. var ret = "Name: " + this.name;
  20937. if (fullDetails) {
  20938. }
  20939. return ret;
  20940. };
  20941. Object.defineProperty(Material.prototype, "isFrozen", {
  20942. get: function () {
  20943. return this.checkReadyOnlyOnce;
  20944. },
  20945. enumerable: true,
  20946. configurable: true
  20947. });
  20948. Material.prototype.freeze = function () {
  20949. this.checkReadyOnlyOnce = true;
  20950. };
  20951. Material.prototype.unfreeze = function () {
  20952. this.checkReadyOnlyOnce = false;
  20953. };
  20954. Material.prototype.isReady = function (mesh, useInstances) {
  20955. return true;
  20956. };
  20957. Material.prototype.getEffect = function () {
  20958. return this._effect;
  20959. };
  20960. Material.prototype.getScene = function () {
  20961. return this._scene;
  20962. };
  20963. Material.prototype.needAlphaBlending = function () {
  20964. return (this.alpha < 1.0);
  20965. };
  20966. Material.prototype.needAlphaTesting = function () {
  20967. return false;
  20968. };
  20969. Material.prototype.getAlphaTestTexture = function () {
  20970. return null;
  20971. };
  20972. Material.prototype.trackCreation = function (onCompiled, onError) {
  20973. };
  20974. Material.prototype.markDirty = function () {
  20975. this._wasPreviouslyReady = false;
  20976. };
  20977. Material.prototype._preBind = function () {
  20978. var engine = this._scene.getEngine();
  20979. engine.enableEffect(this._effect);
  20980. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  20981. };
  20982. Material.prototype.bind = function (world, mesh) {
  20983. this._scene._cachedMaterial = this;
  20984. if (this.onBind) {
  20985. this.onBind(this, mesh);
  20986. }
  20987. if (this.disableDepthWrite) {
  20988. var engine = this._scene.getEngine();
  20989. this._cachedDepthWriteState = engine.getDepthWrite();
  20990. engine.setDepthWrite(false);
  20991. }
  20992. };
  20993. Material.prototype.bindOnlyWorldMatrix = function (world) {
  20994. };
  20995. Material.prototype.unbind = function () {
  20996. if (this.disableDepthWrite) {
  20997. var engine = this._scene.getEngine();
  20998. engine.setDepthWrite(this._cachedDepthWriteState);
  20999. }
  21000. };
  21001. Material.prototype.clone = function (name) {
  21002. return null;
  21003. };
  21004. Material.prototype.getBindedMeshes = function () {
  21005. var result = new Array();
  21006. for (var index = 0; index < this._scene.meshes.length; index++) {
  21007. var mesh = this._scene.meshes[index];
  21008. if (mesh.material === this) {
  21009. result.push(mesh);
  21010. }
  21011. }
  21012. return result;
  21013. };
  21014. Material.prototype.dispose = function (forceDisposeEffect) {
  21015. // Animations
  21016. this.getScene().stopAnimation(this);
  21017. // Remove from scene
  21018. var index = this._scene.materials.indexOf(this);
  21019. if (index >= 0) {
  21020. this._scene.materials.splice(index, 1);
  21021. }
  21022. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  21023. if (forceDisposeEffect && this._effect) {
  21024. this._scene.getEngine()._releaseEffect(this._effect);
  21025. this._effect = null;
  21026. }
  21027. // Remove from meshes
  21028. for (index = 0; index < this._scene.meshes.length; index++) {
  21029. var mesh = this._scene.meshes[index];
  21030. if (mesh.material === this) {
  21031. mesh.material = null;
  21032. }
  21033. }
  21034. // Callback
  21035. if (this.onDispose) {
  21036. this.onDispose();
  21037. }
  21038. };
  21039. Material.prototype.serialize = function () {
  21040. return BABYLON.SerializationHelper.Serialize(this);
  21041. };
  21042. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  21043. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  21044. multiMaterial.id = parsedMultiMaterial.id;
  21045. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  21046. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21047. var subMatId = parsedMultiMaterial.materials[matIndex];
  21048. if (subMatId) {
  21049. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  21050. }
  21051. else {
  21052. multiMaterial.subMaterials.push(null);
  21053. }
  21054. }
  21055. return multiMaterial;
  21056. };
  21057. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  21058. if (!parsedMaterial.customType) {
  21059. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  21060. }
  21061. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  21062. return materialType.Parse(parsedMaterial, scene, rootUrl);
  21063. ;
  21064. };
  21065. Material._TriangleFillMode = 0;
  21066. Material._WireFrameFillMode = 1;
  21067. Material._PointFillMode = 2;
  21068. Material._ClockWiseSideOrientation = 0;
  21069. Material._CounterClockWiseSideOrientation = 1;
  21070. __decorate([
  21071. BABYLON.serialize()
  21072. ], Material.prototype, "id", void 0);
  21073. __decorate([
  21074. BABYLON.serialize()
  21075. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  21076. __decorate([
  21077. BABYLON.serialize()
  21078. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  21079. __decorate([
  21080. BABYLON.serialize()
  21081. ], Material.prototype, "state", void 0);
  21082. __decorate([
  21083. BABYLON.serialize()
  21084. ], Material.prototype, "alpha", void 0);
  21085. __decorate([
  21086. BABYLON.serialize()
  21087. ], Material.prototype, "backFaceCulling", void 0);
  21088. __decorate([
  21089. BABYLON.serialize()
  21090. ], Material.prototype, "sideOrientation", void 0);
  21091. __decorate([
  21092. BABYLON.serialize()
  21093. ], Material.prototype, "alphaMode", void 0);
  21094. __decorate([
  21095. BABYLON.serialize()
  21096. ], Material.prototype, "disableDepthWrite", void 0);
  21097. __decorate([
  21098. BABYLON.serialize()
  21099. ], Material.prototype, "fogEnabled", void 0);
  21100. __decorate([
  21101. BABYLON.serialize()
  21102. ], Material.prototype, "pointSize", void 0);
  21103. __decorate([
  21104. BABYLON.serialize()
  21105. ], Material.prototype, "zOffset", void 0);
  21106. __decorate([
  21107. BABYLON.serialize()
  21108. ], Material.prototype, "wireframe", null);
  21109. __decorate([
  21110. BABYLON.serialize()
  21111. ], Material.prototype, "pointsCloud", null);
  21112. __decorate([
  21113. BABYLON.serialize()
  21114. ], Material.prototype, "fillMode", null);
  21115. return Material;
  21116. })();
  21117. BABYLON.Material = Material;
  21118. })(BABYLON || (BABYLON = {}));
  21119. var BABYLON;
  21120. (function (BABYLON) {
  21121. var StandardMaterialDefines = (function (_super) {
  21122. __extends(StandardMaterialDefines, _super);
  21123. function StandardMaterialDefines() {
  21124. _super.call(this);
  21125. this.DIFFUSE = false;
  21126. this.AMBIENT = false;
  21127. this.OPACITY = false;
  21128. this.OPACITYRGB = false;
  21129. this.REFLECTION = false;
  21130. this.EMISSIVE = false;
  21131. this.SPECULAR = false;
  21132. this.BUMP = false;
  21133. this.PARALLAX = false;
  21134. this.PARALLAXOCCLUSION = false;
  21135. this.SPECULAROVERALPHA = false;
  21136. this.CLIPPLANE = false;
  21137. this.ALPHATEST = false;
  21138. this.ALPHAFROMDIFFUSE = false;
  21139. this.POINTSIZE = false;
  21140. this.FOG = false;
  21141. this.LIGHT0 = false;
  21142. this.LIGHT1 = false;
  21143. this.LIGHT2 = false;
  21144. this.LIGHT3 = false;
  21145. this.SPOTLIGHT0 = false;
  21146. this.SPOTLIGHT1 = false;
  21147. this.SPOTLIGHT2 = false;
  21148. this.SPOTLIGHT3 = false;
  21149. this.HEMILIGHT0 = false;
  21150. this.HEMILIGHT1 = false;
  21151. this.HEMILIGHT2 = false;
  21152. this.HEMILIGHT3 = false;
  21153. this.POINTLIGHT0 = false;
  21154. this.POINTLIGHT1 = false;
  21155. this.POINTLIGHT2 = false;
  21156. this.POINTLIGHT3 = false;
  21157. this.DIRLIGHT0 = false;
  21158. this.DIRLIGHT1 = false;
  21159. this.DIRLIGHT2 = false;
  21160. this.DIRLIGHT3 = false;
  21161. this.SPECULARTERM = false;
  21162. this.SHADOW0 = false;
  21163. this.SHADOW1 = false;
  21164. this.SHADOW2 = false;
  21165. this.SHADOW3 = false;
  21166. this.SHADOWS = false;
  21167. this.SHADOWVSM0 = false;
  21168. this.SHADOWVSM1 = false;
  21169. this.SHADOWVSM2 = false;
  21170. this.SHADOWVSM3 = false;
  21171. this.SHADOWPCF0 = false;
  21172. this.SHADOWPCF1 = false;
  21173. this.SHADOWPCF2 = false;
  21174. this.SHADOWPCF3 = false;
  21175. this.DIFFUSEFRESNEL = false;
  21176. this.OPACITYFRESNEL = false;
  21177. this.REFLECTIONFRESNEL = false;
  21178. this.REFRACTIONFRESNEL = false;
  21179. this.EMISSIVEFRESNEL = false;
  21180. this.FRESNEL = false;
  21181. this.NORMAL = false;
  21182. this.UV1 = false;
  21183. this.UV2 = false;
  21184. this.VERTEXCOLOR = false;
  21185. this.VERTEXALPHA = false;
  21186. this.NUM_BONE_INFLUENCERS = 0;
  21187. this.BonesPerMesh = 0;
  21188. this.INSTANCES = false;
  21189. this.GLOSSINESS = false;
  21190. this.ROUGHNESS = false;
  21191. this.EMISSIVEASILLUMINATION = false;
  21192. this.LINKEMISSIVEWITHDIFFUSE = false;
  21193. this.REFLECTIONFRESNELFROMSPECULAR = false;
  21194. this.LIGHTMAP = false;
  21195. this.USELIGHTMAPASSHADOWMAP = false;
  21196. this.REFLECTIONMAP_3D = false;
  21197. this.REFLECTIONMAP_SPHERICAL = false;
  21198. this.REFLECTIONMAP_PLANAR = false;
  21199. this.REFLECTIONMAP_CUBIC = false;
  21200. this.REFLECTIONMAP_PROJECTION = false;
  21201. this.REFLECTIONMAP_SKYBOX = false;
  21202. this.REFLECTIONMAP_EXPLICIT = false;
  21203. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  21204. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  21205. this.INVERTCUBICMAP = false;
  21206. this.LOGARITHMICDEPTH = false;
  21207. this.REFRACTION = false;
  21208. this.REFRACTIONMAP_3D = false;
  21209. this.REFLECTIONOVERALPHA = false;
  21210. this._keys = Object.keys(this);
  21211. }
  21212. return StandardMaterialDefines;
  21213. })(BABYLON.MaterialDefines);
  21214. var StandardMaterial = (function (_super) {
  21215. __extends(StandardMaterial, _super);
  21216. function StandardMaterial(name, scene) {
  21217. var _this = this;
  21218. _super.call(this, name, scene);
  21219. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21220. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  21221. this.specularColor = new BABYLON.Color3(1, 1, 1);
  21222. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  21223. this.specularPower = 64;
  21224. this.useAlphaFromDiffuseTexture = false;
  21225. this.useEmissiveAsIllumination = false;
  21226. this.linkEmissiveWithDiffuse = false;
  21227. this.useReflectionFresnelFromSpecular = false;
  21228. this.useSpecularOverAlpha = false;
  21229. this.useReflectionOverAlpha = false;
  21230. this.disableLighting = false;
  21231. this.useParallax = false;
  21232. this.useParallaxOcclusion = false;
  21233. this.parallaxScaleBias = 0.05;
  21234. this.roughness = 0;
  21235. this.indexOfRefraction = 0.98;
  21236. this.invertRefractionY = true;
  21237. this.useLightmapAsShadowmap = false;
  21238. this.useGlossinessFromSpecularMapAlpha = false;
  21239. this._renderTargets = new BABYLON.SmartArray(16);
  21240. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  21241. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  21242. this._defines = new StandardMaterialDefines();
  21243. this._cachedDefines = new StandardMaterialDefines();
  21244. this._cachedDefines.BonesPerMesh = -1;
  21245. this.getRenderTargetTextures = function () {
  21246. _this._renderTargets.reset();
  21247. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  21248. _this._renderTargets.push(_this.reflectionTexture);
  21249. }
  21250. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  21251. _this._renderTargets.push(_this.refractionTexture);
  21252. }
  21253. return _this._renderTargets;
  21254. };
  21255. }
  21256. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  21257. get: function () {
  21258. return this._useLogarithmicDepth;
  21259. },
  21260. set: function (value) {
  21261. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  21262. },
  21263. enumerable: true,
  21264. configurable: true
  21265. });
  21266. StandardMaterial.prototype.needAlphaBlending = function () {
  21267. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  21268. };
  21269. StandardMaterial.prototype.needAlphaTesting = function () {
  21270. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  21271. };
  21272. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  21273. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  21274. };
  21275. StandardMaterial.prototype.getAlphaTestTexture = function () {
  21276. return this.diffuseTexture;
  21277. };
  21278. // Methods
  21279. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  21280. if (!mesh) {
  21281. return true;
  21282. }
  21283. if (this._defines.INSTANCES !== useInstances) {
  21284. return false;
  21285. }
  21286. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  21287. return true;
  21288. }
  21289. return false;
  21290. };
  21291. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  21292. if (this.isFrozen) {
  21293. if (this._wasPreviouslyReady) {
  21294. return true;
  21295. }
  21296. }
  21297. var scene = this.getScene();
  21298. if (!this.checkReadyOnEveryCall) {
  21299. if (this._renderId === scene.getRenderId()) {
  21300. if (this._checkCache(scene, mesh, useInstances)) {
  21301. return true;
  21302. }
  21303. }
  21304. }
  21305. var engine = scene.getEngine();
  21306. var needNormals = false;
  21307. var needUVs = false;
  21308. this._defines.reset();
  21309. // Textures
  21310. if (scene.texturesEnabled) {
  21311. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  21312. if (!this.diffuseTexture.isReady()) {
  21313. return false;
  21314. }
  21315. else {
  21316. needUVs = true;
  21317. this._defines.DIFFUSE = true;
  21318. }
  21319. }
  21320. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  21321. if (!this.ambientTexture.isReady()) {
  21322. return false;
  21323. }
  21324. else {
  21325. needUVs = true;
  21326. this._defines.AMBIENT = true;
  21327. }
  21328. }
  21329. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  21330. if (!this.opacityTexture.isReady()) {
  21331. return false;
  21332. }
  21333. else {
  21334. needUVs = true;
  21335. this._defines.OPACITY = true;
  21336. if (this.opacityTexture.getAlphaFromRGB) {
  21337. this._defines.OPACITYRGB = true;
  21338. }
  21339. }
  21340. }
  21341. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  21342. if (!this.reflectionTexture.isReady()) {
  21343. return false;
  21344. }
  21345. else {
  21346. needNormals = true;
  21347. this._defines.REFLECTION = true;
  21348. if (this.roughness > 0) {
  21349. this._defines.ROUGHNESS = true;
  21350. }
  21351. if (this.useReflectionOverAlpha) {
  21352. this._defines.REFLECTIONOVERALPHA = true;
  21353. }
  21354. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  21355. this._defines.INVERTCUBICMAP = true;
  21356. }
  21357. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  21358. switch (this.reflectionTexture.coordinatesMode) {
  21359. case BABYLON.Texture.CUBIC_MODE:
  21360. case BABYLON.Texture.INVCUBIC_MODE:
  21361. this._defines.REFLECTIONMAP_CUBIC = true;
  21362. break;
  21363. case BABYLON.Texture.EXPLICIT_MODE:
  21364. this._defines.REFLECTIONMAP_EXPLICIT = true;
  21365. break;
  21366. case BABYLON.Texture.PLANAR_MODE:
  21367. this._defines.REFLECTIONMAP_PLANAR = true;
  21368. break;
  21369. case BABYLON.Texture.PROJECTION_MODE:
  21370. this._defines.REFLECTIONMAP_PROJECTION = true;
  21371. break;
  21372. case BABYLON.Texture.SKYBOX_MODE:
  21373. this._defines.REFLECTIONMAP_SKYBOX = true;
  21374. break;
  21375. case BABYLON.Texture.SPHERICAL_MODE:
  21376. this._defines.REFLECTIONMAP_SPHERICAL = true;
  21377. break;
  21378. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  21379. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  21380. break;
  21381. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  21382. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  21383. break;
  21384. }
  21385. }
  21386. }
  21387. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  21388. if (!this.emissiveTexture.isReady()) {
  21389. return false;
  21390. }
  21391. else {
  21392. needUVs = true;
  21393. this._defines.EMISSIVE = true;
  21394. }
  21395. }
  21396. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  21397. if (!this.lightmapTexture.isReady()) {
  21398. return false;
  21399. }
  21400. else {
  21401. needUVs = true;
  21402. this._defines.LIGHTMAP = true;
  21403. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  21404. }
  21405. }
  21406. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  21407. if (!this.specularTexture.isReady()) {
  21408. return false;
  21409. }
  21410. else {
  21411. needUVs = true;
  21412. this._defines.SPECULAR = true;
  21413. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  21414. }
  21415. }
  21416. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  21417. if (!this.bumpTexture.isReady()) {
  21418. return false;
  21419. }
  21420. else {
  21421. needUVs = true;
  21422. this._defines.BUMP = true;
  21423. if (this.useParallax) {
  21424. this._defines.PARALLAX = true;
  21425. if (this.useParallaxOcclusion) {
  21426. this._defines.PARALLAXOCCLUSION = true;
  21427. }
  21428. }
  21429. }
  21430. }
  21431. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  21432. if (!this.refractionTexture.isReady()) {
  21433. return false;
  21434. }
  21435. else {
  21436. needUVs = true;
  21437. this._defines.REFRACTION = true;
  21438. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  21439. }
  21440. }
  21441. }
  21442. // Effect
  21443. if (scene.clipPlane) {
  21444. this._defines.CLIPPLANE = true;
  21445. }
  21446. if (engine.getAlphaTesting()) {
  21447. this._defines.ALPHATEST = true;
  21448. }
  21449. if (this._shouldUseAlphaFromDiffuseTexture()) {
  21450. this._defines.ALPHAFROMDIFFUSE = true;
  21451. }
  21452. if (this.useEmissiveAsIllumination) {
  21453. this._defines.EMISSIVEASILLUMINATION = true;
  21454. }
  21455. if (this.linkEmissiveWithDiffuse) {
  21456. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  21457. }
  21458. if (this.useLogarithmicDepth) {
  21459. this._defines.LOGARITHMICDEPTH = true;
  21460. }
  21461. // Point size
  21462. if (this.pointsCloud || scene.forcePointsCloud) {
  21463. this._defines.POINTSIZE = true;
  21464. }
  21465. // Fog
  21466. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21467. this._defines.FOG = true;
  21468. }
  21469. if (scene.lightsEnabled && !this.disableLighting) {
  21470. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  21471. }
  21472. if (StandardMaterial.FresnelEnabled) {
  21473. // Fresnel
  21474. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  21475. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  21476. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  21477. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  21478. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21479. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  21480. this._defines.DIFFUSEFRESNEL = true;
  21481. }
  21482. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  21483. this._defines.OPACITYFRESNEL = true;
  21484. }
  21485. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21486. this._defines.REFLECTIONFRESNEL = true;
  21487. if (this.useReflectionFresnelFromSpecular) {
  21488. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  21489. }
  21490. }
  21491. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  21492. this._defines.REFRACTIONFRESNEL = true;
  21493. }
  21494. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  21495. this._defines.EMISSIVEFRESNEL = true;
  21496. }
  21497. needNormals = true;
  21498. this._defines.FRESNEL = true;
  21499. }
  21500. }
  21501. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  21502. this._defines.SPECULAROVERALPHA = true;
  21503. }
  21504. // Attribs
  21505. if (mesh) {
  21506. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21507. this._defines.NORMAL = true;
  21508. }
  21509. if (needUVs) {
  21510. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21511. this._defines.UV1 = true;
  21512. }
  21513. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21514. this._defines.UV2 = true;
  21515. }
  21516. }
  21517. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21518. this._defines.VERTEXCOLOR = true;
  21519. if (mesh.hasVertexAlpha) {
  21520. this._defines.VERTEXALPHA = true;
  21521. }
  21522. }
  21523. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  21524. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  21525. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  21526. }
  21527. // Instances
  21528. if (useInstances) {
  21529. this._defines.INSTANCES = true;
  21530. }
  21531. }
  21532. // Get correct effect
  21533. if (!this._defines.isEqual(this._cachedDefines)) {
  21534. this._defines.cloneTo(this._cachedDefines);
  21535. scene.resetCachedMaterial();
  21536. // Fallbacks
  21537. var fallbacks = new BABYLON.EffectFallbacks();
  21538. if (this._defines.REFLECTION) {
  21539. fallbacks.addFallback(0, "REFLECTION");
  21540. }
  21541. if (this._defines.SPECULAR) {
  21542. fallbacks.addFallback(0, "SPECULAR");
  21543. }
  21544. if (this._defines.BUMP) {
  21545. fallbacks.addFallback(0, "BUMP");
  21546. }
  21547. if (this._defines.PARALLAX) {
  21548. fallbacks.addFallback(1, "PARALLAX");
  21549. }
  21550. if (this._defines.PARALLAXOCCLUSION) {
  21551. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  21552. }
  21553. if (this._defines.SPECULAROVERALPHA) {
  21554. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  21555. }
  21556. if (this._defines.FOG) {
  21557. fallbacks.addFallback(1, "FOG");
  21558. }
  21559. if (this._defines.POINTSIZE) {
  21560. fallbacks.addFallback(0, "POINTSIZE");
  21561. }
  21562. if (this._defines.LOGARITHMICDEPTH) {
  21563. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  21564. }
  21565. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  21566. if (this._defines.SPECULARTERM) {
  21567. fallbacks.addFallback(0, "SPECULARTERM");
  21568. }
  21569. if (this._defines.DIFFUSEFRESNEL) {
  21570. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  21571. }
  21572. if (this._defines.OPACITYFRESNEL) {
  21573. fallbacks.addFallback(2, "OPACITYFRESNEL");
  21574. }
  21575. if (this._defines.REFLECTIONFRESNEL) {
  21576. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  21577. }
  21578. if (this._defines.EMISSIVEFRESNEL) {
  21579. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  21580. }
  21581. if (this._defines.FRESNEL) {
  21582. fallbacks.addFallback(4, "FRESNEL");
  21583. }
  21584. //Attributes
  21585. var attribs = [BABYLON.VertexBuffer.PositionKind];
  21586. if (this._defines.NORMAL) {
  21587. attribs.push(BABYLON.VertexBuffer.NormalKind);
  21588. }
  21589. if (this._defines.UV1) {
  21590. attribs.push(BABYLON.VertexBuffer.UVKind);
  21591. }
  21592. if (this._defines.UV2) {
  21593. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  21594. }
  21595. if (this._defines.VERTEXCOLOR) {
  21596. attribs.push(BABYLON.VertexBuffer.ColorKind);
  21597. }
  21598. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  21599. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  21600. // Legacy browser patch
  21601. var shaderName = "default";
  21602. if (!scene.getEngine().getCaps().standardDerivatives) {
  21603. shaderName = "legacydefault";
  21604. }
  21605. var join = this._defines.toString();
  21606. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  21607. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  21608. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  21609. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  21610. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  21611. "vFogInfos", "vFogColor", "pointSize",
  21612. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  21613. "mBones",
  21614. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  21615. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  21616. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  21617. "logarithmicDepthConstant"
  21618. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  21619. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  21620. ], join, fallbacks, this.onCompiled, this.onError);
  21621. }
  21622. if (!this._effect.isReady()) {
  21623. return false;
  21624. }
  21625. this._renderId = scene.getRenderId();
  21626. this._wasPreviouslyReady = true;
  21627. if (mesh) {
  21628. if (!mesh._materialDefines) {
  21629. mesh._materialDefines = new StandardMaterialDefines();
  21630. }
  21631. this._defines.cloneTo(mesh._materialDefines);
  21632. }
  21633. return true;
  21634. };
  21635. StandardMaterial.prototype.unbind = function () {
  21636. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  21637. this._effect.setTexture("reflection2DSampler", null);
  21638. }
  21639. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  21640. this._effect.setTexture("refraction2DSampler", null);
  21641. }
  21642. _super.prototype.unbind.call(this);
  21643. };
  21644. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21645. this._effect.setMatrix("world", world);
  21646. };
  21647. StandardMaterial.prototype.bind = function (world, mesh) {
  21648. var scene = this.getScene();
  21649. // Matrices
  21650. this.bindOnlyWorldMatrix(world);
  21651. // Bones
  21652. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  21653. if (scene.getCachedMaterial() !== this) {
  21654. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  21655. if (StandardMaterial.FresnelEnabled) {
  21656. // Fresnel
  21657. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  21658. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  21659. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  21660. }
  21661. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  21662. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  21663. }
  21664. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21665. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  21666. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  21667. }
  21668. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  21669. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  21670. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  21671. }
  21672. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  21673. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  21674. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  21675. }
  21676. }
  21677. // Textures
  21678. if (scene.texturesEnabled) {
  21679. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  21680. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  21681. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  21682. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  21683. }
  21684. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  21685. this._effect.setTexture("ambientSampler", this.ambientTexture);
  21686. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  21687. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  21688. }
  21689. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  21690. this._effect.setTexture("opacitySampler", this.opacityTexture);
  21691. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  21692. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  21693. }
  21694. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  21695. if (this.reflectionTexture.isCube) {
  21696. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  21697. }
  21698. else {
  21699. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  21700. }
  21701. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  21702. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  21703. }
  21704. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  21705. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  21706. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  21707. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  21708. }
  21709. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  21710. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  21711. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  21712. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  21713. }
  21714. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  21715. this._effect.setTexture("specularSampler", this.specularTexture);
  21716. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  21717. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  21718. }
  21719. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  21720. this._effect.setTexture("bumpSampler", this.bumpTexture);
  21721. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  21722. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  21723. }
  21724. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  21725. var depth = 1.0;
  21726. if (this.refractionTexture.isCube) {
  21727. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  21728. }
  21729. else {
  21730. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  21731. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  21732. if (this.refractionTexture.depth) {
  21733. depth = this.refractionTexture.depth;
  21734. }
  21735. }
  21736. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  21737. }
  21738. }
  21739. // Clip plane
  21740. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  21741. // Point size
  21742. if (this.pointsCloud) {
  21743. this._effect.setFloat("pointSize", this.pointSize);
  21744. }
  21745. // Colors
  21746. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  21747. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  21748. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  21749. if (this._defines.SPECULARTERM) {
  21750. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  21751. }
  21752. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  21753. }
  21754. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  21755. // Diffuse
  21756. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  21757. // Lights
  21758. if (scene.lightsEnabled && !this.disableLighting) {
  21759. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  21760. }
  21761. // View
  21762. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  21763. this._effect.setMatrix("view", scene.getViewMatrix());
  21764. }
  21765. // Fog
  21766. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  21767. // Log. depth
  21768. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  21769. }
  21770. _super.prototype.bind.call(this, world, mesh);
  21771. };
  21772. StandardMaterial.prototype.getAnimatables = function () {
  21773. var results = [];
  21774. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  21775. results.push(this.diffuseTexture);
  21776. }
  21777. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  21778. results.push(this.ambientTexture);
  21779. }
  21780. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  21781. results.push(this.opacityTexture);
  21782. }
  21783. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  21784. results.push(this.reflectionTexture);
  21785. }
  21786. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  21787. results.push(this.emissiveTexture);
  21788. }
  21789. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  21790. results.push(this.specularTexture);
  21791. }
  21792. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  21793. results.push(this.bumpTexture);
  21794. }
  21795. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  21796. results.push(this.lightmapTexture);
  21797. }
  21798. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  21799. results.push(this.refractionTexture);
  21800. }
  21801. return results;
  21802. };
  21803. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  21804. if (this.diffuseTexture) {
  21805. this.diffuseTexture.dispose();
  21806. }
  21807. if (this.ambientTexture) {
  21808. this.ambientTexture.dispose();
  21809. }
  21810. if (this.opacityTexture) {
  21811. this.opacityTexture.dispose();
  21812. }
  21813. if (this.reflectionTexture) {
  21814. this.reflectionTexture.dispose();
  21815. }
  21816. if (this.emissiveTexture) {
  21817. this.emissiveTexture.dispose();
  21818. }
  21819. if (this.specularTexture) {
  21820. this.specularTexture.dispose();
  21821. }
  21822. if (this.bumpTexture) {
  21823. this.bumpTexture.dispose();
  21824. }
  21825. if (this.lightmapTexture) {
  21826. this.lightmapTexture.dispose();
  21827. }
  21828. if (this.refractionTexture) {
  21829. this.refractionTexture.dispose();
  21830. }
  21831. _super.prototype.dispose.call(this, forceDisposeEffect);
  21832. };
  21833. StandardMaterial.prototype.clone = function (name) {
  21834. var _this = this;
  21835. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  21836. };
  21837. StandardMaterial.prototype.serialize = function () {
  21838. return BABYLON.SerializationHelper.Serialize(this);
  21839. };
  21840. // Statics
  21841. StandardMaterial.Parse = function (source, scene, rootUrl) {
  21842. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  21843. };
  21844. // Flags used to enable or disable a type of texture for all Standard Materials
  21845. StandardMaterial.DiffuseTextureEnabled = true;
  21846. StandardMaterial.AmbientTextureEnabled = true;
  21847. StandardMaterial.OpacityTextureEnabled = true;
  21848. StandardMaterial.ReflectionTextureEnabled = true;
  21849. StandardMaterial.EmissiveTextureEnabled = true;
  21850. StandardMaterial.SpecularTextureEnabled = true;
  21851. StandardMaterial.BumpTextureEnabled = true;
  21852. StandardMaterial.FresnelEnabled = true;
  21853. StandardMaterial.LightmapTextureEnabled = true;
  21854. StandardMaterial.RefractionTextureEnabled = true;
  21855. __decorate([
  21856. BABYLON.serializeAsTexture()
  21857. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  21858. __decorate([
  21859. BABYLON.serializeAsTexture()
  21860. ], StandardMaterial.prototype, "ambientTexture", void 0);
  21861. __decorate([
  21862. BABYLON.serializeAsTexture()
  21863. ], StandardMaterial.prototype, "opacityTexture", void 0);
  21864. __decorate([
  21865. BABYLON.serializeAsTexture()
  21866. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  21867. __decorate([
  21868. BABYLON.serializeAsTexture()
  21869. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  21870. __decorate([
  21871. BABYLON.serializeAsTexture()
  21872. ], StandardMaterial.prototype, "specularTexture", void 0);
  21873. __decorate([
  21874. BABYLON.serializeAsTexture()
  21875. ], StandardMaterial.prototype, "bumpTexture", void 0);
  21876. __decorate([
  21877. BABYLON.serializeAsTexture()
  21878. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  21879. __decorate([
  21880. BABYLON.serializeAsTexture()
  21881. ], StandardMaterial.prototype, "refractionTexture", void 0);
  21882. __decorate([
  21883. BABYLON.serializeAsColor3("ambient")
  21884. ], StandardMaterial.prototype, "ambientColor", void 0);
  21885. __decorate([
  21886. BABYLON.serializeAsColor3("diffuse")
  21887. ], StandardMaterial.prototype, "diffuseColor", void 0);
  21888. __decorate([
  21889. BABYLON.serializeAsColor3("specular")
  21890. ], StandardMaterial.prototype, "specularColor", void 0);
  21891. __decorate([
  21892. BABYLON.serializeAsColor3("emissive")
  21893. ], StandardMaterial.prototype, "emissiveColor", void 0);
  21894. __decorate([
  21895. BABYLON.serialize()
  21896. ], StandardMaterial.prototype, "specularPower", void 0);
  21897. __decorate([
  21898. BABYLON.serialize()
  21899. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  21900. __decorate([
  21901. BABYLON.serialize()
  21902. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  21903. __decorate([
  21904. BABYLON.serialize()
  21905. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  21906. __decorate([
  21907. BABYLON.serialize()
  21908. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  21909. __decorate([
  21910. BABYLON.serialize()
  21911. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  21912. __decorate([
  21913. BABYLON.serialize()
  21914. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  21915. __decorate([
  21916. BABYLON.serialize()
  21917. ], StandardMaterial.prototype, "disableLighting", void 0);
  21918. __decorate([
  21919. BABYLON.serialize()
  21920. ], StandardMaterial.prototype, "useParallax", void 0);
  21921. __decorate([
  21922. BABYLON.serialize()
  21923. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  21924. __decorate([
  21925. BABYLON.serialize()
  21926. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  21927. __decorate([
  21928. BABYLON.serialize()
  21929. ], StandardMaterial.prototype, "roughness", void 0);
  21930. __decorate([
  21931. BABYLON.serialize()
  21932. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  21933. __decorate([
  21934. BABYLON.serialize()
  21935. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  21936. __decorate([
  21937. BABYLON.serialize()
  21938. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  21939. __decorate([
  21940. BABYLON.serializeAsFresnelParameters()
  21941. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  21942. __decorate([
  21943. BABYLON.serializeAsFresnelParameters()
  21944. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  21945. __decorate([
  21946. BABYLON.serializeAsFresnelParameters()
  21947. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  21948. __decorate([
  21949. BABYLON.serializeAsFresnelParameters()
  21950. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  21951. __decorate([
  21952. BABYLON.serializeAsFresnelParameters()
  21953. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  21954. __decorate([
  21955. BABYLON.serialize()
  21956. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  21957. __decorate([
  21958. BABYLON.serialize()
  21959. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  21960. return StandardMaterial;
  21961. })(BABYLON.Material);
  21962. BABYLON.StandardMaterial = StandardMaterial;
  21963. })(BABYLON || (BABYLON = {}));
  21964. var BABYLON;
  21965. (function (BABYLON) {
  21966. var MultiMaterial = (function (_super) {
  21967. __extends(MultiMaterial, _super);
  21968. function MultiMaterial(name, scene) {
  21969. _super.call(this, name, scene, true);
  21970. this.subMaterials = new Array();
  21971. scene.multiMaterials.push(this);
  21972. }
  21973. // Properties
  21974. MultiMaterial.prototype.getSubMaterial = function (index) {
  21975. if (index < 0 || index >= this.subMaterials.length) {
  21976. return this.getScene().defaultMaterial;
  21977. }
  21978. return this.subMaterials[index];
  21979. };
  21980. // Methods
  21981. MultiMaterial.prototype.isReady = function (mesh) {
  21982. for (var index = 0; index < this.subMaterials.length; index++) {
  21983. var subMaterial = this.subMaterials[index];
  21984. if (subMaterial) {
  21985. if (!this.subMaterials[index].isReady(mesh)) {
  21986. return false;
  21987. }
  21988. }
  21989. }
  21990. return true;
  21991. };
  21992. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  21993. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  21994. for (var index = 0; index < this.subMaterials.length; index++) {
  21995. var subMaterial = null;
  21996. if (cloneChildren) {
  21997. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  21998. }
  21999. else {
  22000. subMaterial = this.subMaterials[index];
  22001. }
  22002. newMultiMaterial.subMaterials.push(subMaterial);
  22003. }
  22004. return newMultiMaterial;
  22005. };
  22006. MultiMaterial.prototype.serialize = function () {
  22007. var serializationObject = {};
  22008. serializationObject.name = this.name;
  22009. serializationObject.id = this.id;
  22010. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22011. serializationObject.materials = [];
  22012. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  22013. var subMat = this.subMaterials[matIndex];
  22014. if (subMat) {
  22015. serializationObject.materials.push(subMat.id);
  22016. }
  22017. else {
  22018. serializationObject.materials.push(null);
  22019. }
  22020. }
  22021. return serializationObject;
  22022. };
  22023. return MultiMaterial;
  22024. })(BABYLON.Material);
  22025. BABYLON.MultiMaterial = MultiMaterial;
  22026. })(BABYLON || (BABYLON = {}));
  22027. var BABYLON;
  22028. (function (BABYLON) {
  22029. var SceneLoader = (function () {
  22030. function SceneLoader() {
  22031. }
  22032. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  22033. get: function () {
  22034. return 0;
  22035. },
  22036. enumerable: true,
  22037. configurable: true
  22038. });
  22039. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  22040. get: function () {
  22041. return 1;
  22042. },
  22043. enumerable: true,
  22044. configurable: true
  22045. });
  22046. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  22047. get: function () {
  22048. return 2;
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  22054. get: function () {
  22055. return 3;
  22056. },
  22057. enumerable: true,
  22058. configurable: true
  22059. });
  22060. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  22061. get: function () {
  22062. return SceneLoader._ForceFullSceneLoadingForIncremental;
  22063. },
  22064. set: function (value) {
  22065. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  22071. get: function () {
  22072. return SceneLoader._ShowLoadingScreen;
  22073. },
  22074. set: function (value) {
  22075. SceneLoader._ShowLoadingScreen = value;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. Object.defineProperty(SceneLoader, "loggingLevel", {
  22081. get: function () {
  22082. return SceneLoader._loggingLevel;
  22083. },
  22084. set: function (value) {
  22085. SceneLoader._loggingLevel = value;
  22086. },
  22087. enumerable: true,
  22088. configurable: true
  22089. });
  22090. SceneLoader._getPluginForFilename = function (sceneFilename) {
  22091. var dotPosition = sceneFilename.lastIndexOf(".");
  22092. var queryStringPosition = sceneFilename.indexOf("?");
  22093. if (queryStringPosition === -1) {
  22094. queryStringPosition = sceneFilename.length;
  22095. }
  22096. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  22097. for (var index = 0; index < this._registeredPlugins.length; index++) {
  22098. var plugin = this._registeredPlugins[index];
  22099. if (plugin.extensions.indexOf(extension) !== -1) {
  22100. return plugin;
  22101. }
  22102. }
  22103. return this._registeredPlugins[this._registeredPlugins.length - 1];
  22104. };
  22105. // Public functions
  22106. SceneLoader.GetPluginForExtension = function (extension) {
  22107. for (var index = 0; index < this._registeredPlugins.length; index++) {
  22108. var plugin = this._registeredPlugins[index];
  22109. if (plugin.extensions.indexOf(extension) !== -1) {
  22110. return plugin;
  22111. }
  22112. }
  22113. return null;
  22114. };
  22115. SceneLoader.RegisterPlugin = function (plugin) {
  22116. plugin.extensions = plugin.extensions.toLowerCase();
  22117. SceneLoader._registeredPlugins.push(plugin);
  22118. };
  22119. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  22120. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  22121. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  22122. return;
  22123. }
  22124. var loadingToken = {};
  22125. scene._addPendingData(loadingToken);
  22126. var manifestChecked = function (success) {
  22127. scene.database = database;
  22128. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  22129. var importMeshFromData = function (data) {
  22130. var meshes = [];
  22131. var particleSystems = [];
  22132. var skeletons = [];
  22133. try {
  22134. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  22135. if (onerror) {
  22136. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  22137. }
  22138. scene._removePendingData(loadingToken);
  22139. return;
  22140. }
  22141. }
  22142. catch (e) {
  22143. if (onerror) {
  22144. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  22145. }
  22146. scene._removePendingData(loadingToken);
  22147. return;
  22148. }
  22149. if (onsuccess) {
  22150. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  22151. onsuccess(meshes, particleSystems, skeletons);
  22152. scene._removePendingData(loadingToken);
  22153. }
  22154. };
  22155. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  22156. // Direct load
  22157. importMeshFromData(sceneFilename.substr(5));
  22158. return;
  22159. }
  22160. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  22161. importMeshFromData(data);
  22162. }, progressCallBack, database);
  22163. };
  22164. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  22165. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  22166. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  22167. }
  22168. else {
  22169. // If the scene is a data stream or offline support is not enabled, it's a direct load
  22170. manifestChecked(true);
  22171. }
  22172. };
  22173. /**
  22174. * Load a scene
  22175. * @param rootUrl a string that defines the root url for scene and resources
  22176. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  22177. * @param engine is the instance of BABYLON.Engine to use to create the scene
  22178. */
  22179. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  22180. if (!SceneLoader._warned) {
  22181. BABYLON.Tools.Warn("SceneLoader.Load deprecated since 2.4. Use SceneLoader.Append.");
  22182. SceneLoader._warned = true;
  22183. }
  22184. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  22185. };
  22186. /**
  22187. * Append a scene
  22188. * @param rootUrl a string that defines the root url for scene and resources
  22189. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  22190. * @param scene is the instance of BABYLON.Scene to append to
  22191. */
  22192. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  22193. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  22194. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  22195. return;
  22196. }
  22197. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  22198. var database;
  22199. var loadingToken = {};
  22200. scene._addPendingData(loadingToken);
  22201. if (SceneLoader.ShowLoadingScreen) {
  22202. scene.getEngine().displayLoadingUI();
  22203. }
  22204. var loadSceneFromData = function (data) {
  22205. scene.database = database;
  22206. if (!plugin.load(scene, data, rootUrl)) {
  22207. if (onerror) {
  22208. onerror(scene);
  22209. }
  22210. scene._removePendingData(loadingToken);
  22211. scene.getEngine().hideLoadingUI();
  22212. return;
  22213. }
  22214. if (onsuccess) {
  22215. onsuccess(scene);
  22216. }
  22217. scene._removePendingData(loadingToken);
  22218. if (SceneLoader.ShowLoadingScreen) {
  22219. scene.executeWhenReady(function () {
  22220. scene.getEngine().hideLoadingUI();
  22221. });
  22222. }
  22223. };
  22224. var manifestChecked = function (success) {
  22225. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  22226. };
  22227. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  22228. // Direct load
  22229. loadSceneFromData(sceneFilename.substr(5));
  22230. return;
  22231. }
  22232. if (rootUrl.indexOf("file:") === -1) {
  22233. if (scene.getEngine().enableOfflineSupport) {
  22234. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  22235. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  22236. }
  22237. else {
  22238. manifestChecked(true);
  22239. }
  22240. }
  22241. else {
  22242. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  22243. }
  22244. };
  22245. // Flags
  22246. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  22247. SceneLoader._ShowLoadingScreen = true;
  22248. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  22249. // Members
  22250. SceneLoader._registeredPlugins = new Array();
  22251. return SceneLoader;
  22252. })();
  22253. BABYLON.SceneLoader = SceneLoader;
  22254. ;
  22255. })(BABYLON || (BABYLON = {}));
  22256. var BABYLON;
  22257. (function (BABYLON) {
  22258. var Internals;
  22259. (function (Internals) {
  22260. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  22261. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  22262. var parsedMaterial = parsedData.materials[index];
  22263. if (parsedMaterial.id === id) {
  22264. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  22265. }
  22266. }
  22267. return null;
  22268. };
  22269. var isDescendantOf = function (mesh, names, hierarchyIds) {
  22270. names = (names instanceof Array) ? names : [names];
  22271. for (var i in names) {
  22272. if (mesh.name === names[i]) {
  22273. hierarchyIds.push(mesh.id);
  22274. return true;
  22275. }
  22276. }
  22277. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  22278. hierarchyIds.push(mesh.id);
  22279. return true;
  22280. }
  22281. return false;
  22282. };
  22283. var logOperation = function (operation, producer) {
  22284. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  22285. };
  22286. BABYLON.SceneLoader.RegisterPlugin({
  22287. extensions: ".babylon",
  22288. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  22289. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  22290. // when SceneLoader.debugLogging = true (default), or exception encountered.
  22291. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  22292. // and avoid problems with multiple concurrent .babylon loads.
  22293. var log = "importMesh has failed JSON parse";
  22294. try {
  22295. var parsedData = JSON.parse(data);
  22296. log = "";
  22297. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  22298. var loadedSkeletonsIds = [];
  22299. var loadedMaterialsIds = [];
  22300. var hierarchyIds = [];
  22301. var index;
  22302. var cache;
  22303. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  22304. var parsedMesh = parsedData.meshes[index];
  22305. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  22306. if (meshesNames instanceof Array) {
  22307. // Remove found mesh name from list.
  22308. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  22309. }
  22310. //Geometry?
  22311. if (parsedMesh.geometryId) {
  22312. //does the file contain geometries?
  22313. if (parsedData.geometries) {
  22314. //find the correct geometry and add it to the scene
  22315. var found = false;
  22316. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  22317. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  22318. return;
  22319. }
  22320. else {
  22321. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  22322. if (parsedGeometryData.id === parsedMesh.geometryId) {
  22323. switch (geometryType) {
  22324. case "boxes":
  22325. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  22326. break;
  22327. case "spheres":
  22328. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  22329. break;
  22330. case "cylinders":
  22331. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  22332. break;
  22333. case "toruses":
  22334. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  22335. break;
  22336. case "grounds":
  22337. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  22338. break;
  22339. case "planes":
  22340. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  22341. break;
  22342. case "torusKnots":
  22343. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  22344. break;
  22345. case "vertexData":
  22346. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  22347. break;
  22348. }
  22349. found = true;
  22350. }
  22351. });
  22352. }
  22353. });
  22354. if (!found) {
  22355. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  22356. }
  22357. }
  22358. }
  22359. // Material ?
  22360. if (parsedMesh.materialId) {
  22361. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  22362. if (!materialFound && parsedData.multiMaterials) {
  22363. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  22364. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  22365. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  22366. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  22367. var subMatId = parsedMultiMaterial.materials[matIndex];
  22368. loadedMaterialsIds.push(subMatId);
  22369. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  22370. log += "\n\tMaterial " + mat.toString(fullDetails);
  22371. }
  22372. loadedMaterialsIds.push(parsedMultiMaterial.id);
  22373. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  22374. materialFound = true;
  22375. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  22376. break;
  22377. }
  22378. }
  22379. }
  22380. if (!materialFound) {
  22381. loadedMaterialsIds.push(parsedMesh.materialId);
  22382. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  22383. if (!mat) {
  22384. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  22385. }
  22386. else {
  22387. log += "\n\tMaterial " + mat.toString(fullDetails);
  22388. }
  22389. }
  22390. }
  22391. // Skeleton ?
  22392. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  22393. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  22394. if (!skeletonAlreadyLoaded) {
  22395. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  22396. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  22397. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  22398. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  22399. skeletons.push(skeleton);
  22400. loadedSkeletonsIds.push(parsedSkeleton.id);
  22401. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  22402. }
  22403. }
  22404. }
  22405. }
  22406. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  22407. meshes.push(mesh);
  22408. log += "\n\tMesh " + mesh.toString(fullDetails);
  22409. }
  22410. }
  22411. // Connecting parents
  22412. var currentMesh;
  22413. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22414. currentMesh = scene.meshes[index];
  22415. if (currentMesh._waitingParentId) {
  22416. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  22417. currentMesh._waitingParentId = undefined;
  22418. }
  22419. }
  22420. // freeze and compute world matrix application
  22421. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22422. currentMesh = scene.meshes[index];
  22423. if (currentMesh._waitingFreezeWorldMatrix) {
  22424. currentMesh.freezeWorldMatrix();
  22425. currentMesh._waitingFreezeWorldMatrix = undefined;
  22426. }
  22427. else {
  22428. currentMesh.computeWorldMatrix(true);
  22429. }
  22430. }
  22431. // Particles
  22432. if (parsedData.particleSystems) {
  22433. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  22434. var parsedParticleSystem = parsedData.particleSystems[index];
  22435. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  22436. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  22437. }
  22438. }
  22439. }
  22440. return true;
  22441. }
  22442. catch (err) {
  22443. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  22444. log = null;
  22445. throw err;
  22446. }
  22447. finally {
  22448. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  22449. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  22450. }
  22451. }
  22452. },
  22453. load: function (scene, data, rootUrl) {
  22454. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  22455. // when SceneLoader.debugLogging = true (default), or exception encountered.
  22456. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  22457. // and avoid problems with multiple concurrent .babylon loads.
  22458. var log = "importScene has failed JSON parse";
  22459. try {
  22460. var parsedData = JSON.parse(data);
  22461. log = "";
  22462. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  22463. // Scene
  22464. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  22465. scene.autoClear = parsedData.autoClear;
  22466. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  22467. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  22468. if (parsedData.gravity) {
  22469. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  22470. }
  22471. // Fog
  22472. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  22473. scene.fogMode = parsedData.fogMode;
  22474. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  22475. scene.fogStart = parsedData.fogStart;
  22476. scene.fogEnd = parsedData.fogEnd;
  22477. scene.fogDensity = parsedData.fogDensity;
  22478. log += "\tFog mode for scene: ";
  22479. switch (scene.fogMode) {
  22480. // getters not compiling, so using hardcoded
  22481. case 1:
  22482. log += "exp\n";
  22483. break;
  22484. case 2:
  22485. log += "exp2\n";
  22486. break;
  22487. case 3:
  22488. log += "linear\n";
  22489. break;
  22490. }
  22491. }
  22492. //Physics
  22493. if (parsedData.physicsEnabled) {
  22494. var physicsPlugin;
  22495. if (parsedData.physicsEngine === "cannon") {
  22496. physicsPlugin = new BABYLON.CannonJSPlugin();
  22497. }
  22498. else if (parsedData.physicsEngine === "oimo") {
  22499. physicsPlugin = new BABYLON.OimoJSPlugin();
  22500. }
  22501. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  22502. //else - default engine, which is currently oimo
  22503. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  22504. scene.enablePhysics(physicsGravity, physicsPlugin);
  22505. }
  22506. //collisions, if defined. otherwise, default is true
  22507. if (parsedData.collisionsEnabled != undefined) {
  22508. scene.collisionsEnabled = parsedData.collisionsEnabled;
  22509. }
  22510. scene.workerCollisions = !!parsedData.workerCollisions;
  22511. var index;
  22512. var cache;
  22513. // Lights
  22514. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  22515. var parsedLight = parsedData.lights[index];
  22516. var light = BABYLON.Light.Parse(parsedLight, scene);
  22517. log += (index === 0 ? "\n\tLights:" : "");
  22518. log += "\n\t\t" + light.toString(fullDetails);
  22519. }
  22520. // Animations
  22521. if (parsedData.animations) {
  22522. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  22523. var parsedAnimation = parsedData.animations[index];
  22524. var animation = BABYLON.Animation.Parse(parsedAnimation);
  22525. scene.animations.push(animation);
  22526. log += (index === 0 ? "\n\tAnimations:" : "");
  22527. log += "\n\t\t" + animation.toString(fullDetails);
  22528. }
  22529. }
  22530. // Materials
  22531. if (parsedData.materials) {
  22532. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  22533. var parsedMaterial = parsedData.materials[index];
  22534. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  22535. log += (index === 0 ? "\n\tMaterials:" : "");
  22536. log += "\n\t\t" + mat.toString(fullDetails);
  22537. }
  22538. }
  22539. if (parsedData.multiMaterials) {
  22540. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  22541. var parsedMultiMaterial = parsedData.multiMaterials[index];
  22542. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  22543. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  22544. log += "\n\t\t" + mmat.toString(fullDetails);
  22545. }
  22546. }
  22547. // Skeletons
  22548. if (parsedData.skeletons) {
  22549. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  22550. var parsedSkeleton = parsedData.skeletons[index];
  22551. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  22552. log += (index === 0 ? "\n\tSkeletons:" : "");
  22553. log += "\n\t\t" + skeleton.toString(fullDetails);
  22554. }
  22555. }
  22556. // Geometries
  22557. var geometries = parsedData.geometries;
  22558. if (geometries) {
  22559. // Boxes
  22560. var boxes = geometries.boxes;
  22561. if (boxes) {
  22562. for (index = 0, cache = boxes.length; index < cache; index++) {
  22563. var parsedBox = boxes[index];
  22564. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  22565. }
  22566. }
  22567. // Spheres
  22568. var spheres = geometries.spheres;
  22569. if (spheres) {
  22570. for (index = 0, cache = spheres.length; index < cache; index++) {
  22571. var parsedSphere = spheres[index];
  22572. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  22573. }
  22574. }
  22575. // Cylinders
  22576. var cylinders = geometries.cylinders;
  22577. if (cylinders) {
  22578. for (index = 0, cache = cylinders.length; index < cache; index++) {
  22579. var parsedCylinder = cylinders[index];
  22580. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  22581. }
  22582. }
  22583. // Toruses
  22584. var toruses = geometries.toruses;
  22585. if (toruses) {
  22586. for (index = 0, cache = toruses.length; index < cache; index++) {
  22587. var parsedTorus = toruses[index];
  22588. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  22589. }
  22590. }
  22591. // Grounds
  22592. var grounds = geometries.grounds;
  22593. if (grounds) {
  22594. for (index = 0, cache = grounds.length; index < cache; index++) {
  22595. var parsedGround = grounds[index];
  22596. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  22597. }
  22598. }
  22599. // Planes
  22600. var planes = geometries.planes;
  22601. if (planes) {
  22602. for (index = 0, cache = planes.length; index < cache; index++) {
  22603. var parsedPlane = planes[index];
  22604. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  22605. }
  22606. }
  22607. // TorusKnots
  22608. var torusKnots = geometries.torusKnots;
  22609. if (torusKnots) {
  22610. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  22611. var parsedTorusKnot = torusKnots[index];
  22612. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  22613. }
  22614. }
  22615. // VertexData
  22616. var vertexData = geometries.vertexData;
  22617. if (vertexData) {
  22618. for (index = 0, cache = vertexData.length; index < cache; index++) {
  22619. var parsedVertexData = vertexData[index];
  22620. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  22621. }
  22622. }
  22623. }
  22624. // Meshes
  22625. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  22626. var parsedMesh = parsedData.meshes[index];
  22627. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  22628. log += (index === 0 ? "\n\tMeshes:" : "");
  22629. log += "\n\t\t" + mesh.toString(fullDetails);
  22630. }
  22631. // Cameras
  22632. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  22633. var parsedCamera = parsedData.cameras[index];
  22634. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  22635. log += (index === 0 ? "\n\tCameras:" : "");
  22636. log += "\n\t\t" + camera.toString(fullDetails);
  22637. }
  22638. if (parsedData.activeCameraID) {
  22639. scene.setActiveCameraByID(parsedData.activeCameraID);
  22640. }
  22641. // Browsing all the graph to connect the dots
  22642. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  22643. var camera = scene.cameras[index];
  22644. if (camera._waitingParentId) {
  22645. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  22646. camera._waitingParentId = undefined;
  22647. }
  22648. }
  22649. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  22650. var light = scene.lights[index];
  22651. if (light._waitingParentId) {
  22652. light.parent = scene.getLastEntryByID(light._waitingParentId);
  22653. light._waitingParentId = undefined;
  22654. }
  22655. }
  22656. // Sounds
  22657. var loadedSounds = [];
  22658. var loadedSound;
  22659. if (BABYLON.AudioEngine && parsedData.sounds) {
  22660. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  22661. var parsedSound = parsedData.sounds[index];
  22662. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  22663. if (!parsedSound.url)
  22664. parsedSound.url = parsedSound.name;
  22665. if (!loadedSounds[parsedSound.url]) {
  22666. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  22667. loadedSounds[parsedSound.url] = loadedSound;
  22668. }
  22669. else {
  22670. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  22671. }
  22672. }
  22673. else {
  22674. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  22675. }
  22676. }
  22677. log += (index === 0 ? "\n\tSounds:" : "");
  22678. log += "\n\t\t" + mat.toString(fullDetails);
  22679. }
  22680. loadedSounds = [];
  22681. // Connect parents & children and parse actions
  22682. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22683. var mesh = scene.meshes[index];
  22684. if (mesh._waitingParentId) {
  22685. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  22686. mesh._waitingParentId = undefined;
  22687. }
  22688. if (mesh._waitingActions) {
  22689. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  22690. mesh._waitingActions = undefined;
  22691. }
  22692. }
  22693. // freeze world matrix application
  22694. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22695. var currentMesh = scene.meshes[index];
  22696. if (currentMesh._waitingFreezeWorldMatrix) {
  22697. currentMesh.freezeWorldMatrix();
  22698. currentMesh._waitingFreezeWorldMatrix = undefined;
  22699. }
  22700. else {
  22701. currentMesh.computeWorldMatrix(true);
  22702. }
  22703. }
  22704. // Particles Systems
  22705. if (parsedData.particleSystems) {
  22706. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  22707. var parsedParticleSystem = parsedData.particleSystems[index];
  22708. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  22709. }
  22710. }
  22711. // Lens flares
  22712. if (parsedData.lensFlareSystems) {
  22713. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  22714. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  22715. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  22716. }
  22717. }
  22718. // Shadows
  22719. if (parsedData.shadowGenerators) {
  22720. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  22721. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  22722. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  22723. }
  22724. }
  22725. // Actions (scene)
  22726. if (parsedData.actions) {
  22727. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  22728. }
  22729. // Finish
  22730. return true;
  22731. }
  22732. catch (err) {
  22733. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  22734. log = null;
  22735. throw err;
  22736. }
  22737. finally {
  22738. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  22739. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  22740. }
  22741. }
  22742. }
  22743. });
  22744. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22745. })(BABYLON || (BABYLON = {}));
  22746. var BABYLON;
  22747. (function (BABYLON) {
  22748. var SpriteManager = (function () {
  22749. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  22750. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22751. this.name = name;
  22752. this.cellSize = cellSize;
  22753. this.sprites = new Array();
  22754. this.renderingGroupId = 0;
  22755. this.layerMask = 0x0FFFFFFF;
  22756. this.fogEnabled = true;
  22757. this.isPickable = false;
  22758. this._vertexDeclaration = [4, 4, 4, 4];
  22759. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  22760. this._capacity = capacity;
  22761. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  22762. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22763. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22764. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  22765. this._scene = scene;
  22766. this._scene.spriteManagers.push(this);
  22767. // VBO
  22768. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  22769. var indices = [];
  22770. var index = 0;
  22771. for (var count = 0; count < capacity; count++) {
  22772. indices.push(index);
  22773. indices.push(index + 1);
  22774. indices.push(index + 2);
  22775. indices.push(index);
  22776. indices.push(index + 2);
  22777. indices.push(index + 3);
  22778. index += 4;
  22779. }
  22780. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22781. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  22782. // Effects
  22783. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  22784. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  22785. }
  22786. Object.defineProperty(SpriteManager.prototype, "texture", {
  22787. get: function () {
  22788. return this._spriteTexture;
  22789. },
  22790. set: function (value) {
  22791. this._spriteTexture = value;
  22792. },
  22793. enumerable: true,
  22794. configurable: true
  22795. });
  22796. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  22797. var arrayOffset = index * 16;
  22798. if (offsetX === 0)
  22799. offsetX = this._epsilon;
  22800. else if (offsetX === 1)
  22801. offsetX = 1 - this._epsilon;
  22802. if (offsetY === 0)
  22803. offsetY = this._epsilon;
  22804. else if (offsetY === 1)
  22805. offsetY = 1 - this._epsilon;
  22806. this._vertices[arrayOffset] = sprite.position.x;
  22807. this._vertices[arrayOffset + 1] = sprite.position.y;
  22808. this._vertices[arrayOffset + 2] = sprite.position.z;
  22809. this._vertices[arrayOffset + 3] = sprite.angle;
  22810. this._vertices[arrayOffset + 4] = sprite.width;
  22811. this._vertices[arrayOffset + 5] = sprite.height;
  22812. this._vertices[arrayOffset + 6] = offsetX;
  22813. this._vertices[arrayOffset + 7] = offsetY;
  22814. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  22815. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  22816. var offset = (sprite.cellIndex / rowSize) >> 0;
  22817. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  22818. this._vertices[arrayOffset + 11] = offset;
  22819. // Color
  22820. this._vertices[arrayOffset + 12] = sprite.color.r;
  22821. this._vertices[arrayOffset + 13] = sprite.color.g;
  22822. this._vertices[arrayOffset + 14] = sprite.color.b;
  22823. this._vertices[arrayOffset + 15] = sprite.color.a;
  22824. };
  22825. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  22826. var count = Math.min(this._capacity, this.sprites.length);
  22827. var min = BABYLON.Vector3.Zero();
  22828. var max = BABYLON.Vector3.Zero();
  22829. var distance = Number.MAX_VALUE;
  22830. var currentSprite;
  22831. var cameraSpacePosition = BABYLON.Vector3.Zero();
  22832. var cameraView = camera.getViewMatrix();
  22833. for (var index = 0; index < count; index++) {
  22834. var sprite = this.sprites[index];
  22835. if (!sprite) {
  22836. continue;
  22837. }
  22838. if (predicate) {
  22839. if (!predicate(sprite)) {
  22840. continue;
  22841. }
  22842. }
  22843. else if (!sprite.isPickable) {
  22844. continue;
  22845. }
  22846. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  22847. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  22848. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  22849. if (ray.intersectsBoxMinMax(min, max)) {
  22850. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  22851. if (distance > currentDistance) {
  22852. distance = currentDistance;
  22853. currentSprite = sprite;
  22854. if (fastCheck) {
  22855. break;
  22856. }
  22857. }
  22858. }
  22859. }
  22860. if (currentSprite) {
  22861. var result = new BABYLON.PickingInfo();
  22862. result.hit = true;
  22863. result.pickedSprite = currentSprite;
  22864. result.distance = distance;
  22865. return result;
  22866. }
  22867. return null;
  22868. };
  22869. SpriteManager.prototype.render = function () {
  22870. // Check
  22871. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  22872. return;
  22873. var engine = this._scene.getEngine();
  22874. var baseSize = this._spriteTexture.getBaseSize();
  22875. // Sprites
  22876. var deltaTime = engine.getDeltaTime();
  22877. var max = Math.min(this._capacity, this.sprites.length);
  22878. var rowSize = baseSize.width / this.cellSize;
  22879. var offset = 0;
  22880. for (var index = 0; index < max; index++) {
  22881. var sprite = this.sprites[index];
  22882. if (!sprite) {
  22883. continue;
  22884. }
  22885. sprite._animate(deltaTime);
  22886. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  22887. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  22888. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  22889. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  22890. }
  22891. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22892. // Render
  22893. var effect = this._effectBase;
  22894. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22895. effect = this._effectFog;
  22896. }
  22897. engine.enableEffect(effect);
  22898. var viewMatrix = this._scene.getViewMatrix();
  22899. effect.setTexture("diffuseSampler", this._spriteTexture);
  22900. effect.setMatrix("view", viewMatrix);
  22901. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22902. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  22903. // Fog
  22904. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22905. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  22906. effect.setColor3("vFogColor", this._scene.fogColor);
  22907. }
  22908. // VBOs
  22909. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22910. // Draw order
  22911. engine.setDepthFunctionToLessOrEqual();
  22912. effect.setBool("alphaTest", true);
  22913. engine.setColorWrite(false);
  22914. engine.draw(true, 0, max * 6);
  22915. engine.setColorWrite(true);
  22916. effect.setBool("alphaTest", false);
  22917. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22918. engine.draw(true, 0, max * 6);
  22919. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22920. };
  22921. SpriteManager.prototype.dispose = function () {
  22922. if (this._vertexBuffer) {
  22923. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22924. this._vertexBuffer = null;
  22925. }
  22926. if (this._indexBuffer) {
  22927. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22928. this._indexBuffer = null;
  22929. }
  22930. if (this._spriteTexture) {
  22931. this._spriteTexture.dispose();
  22932. this._spriteTexture = null;
  22933. }
  22934. // Remove from scene
  22935. var index = this._scene.spriteManagers.indexOf(this);
  22936. this._scene.spriteManagers.splice(index, 1);
  22937. // Callback
  22938. if (this.onDispose) {
  22939. this.onDispose();
  22940. }
  22941. };
  22942. return SpriteManager;
  22943. })();
  22944. BABYLON.SpriteManager = SpriteManager;
  22945. })(BABYLON || (BABYLON = {}));
  22946. var BABYLON;
  22947. (function (BABYLON) {
  22948. var Sprite = (function () {
  22949. function Sprite(name, manager) {
  22950. this.name = name;
  22951. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  22952. this.width = 1.0;
  22953. this.height = 1.0;
  22954. this.angle = 0;
  22955. this.cellIndex = 0;
  22956. this.invertU = 0;
  22957. this.invertV = 0;
  22958. this.animations = new Array();
  22959. this.isPickable = false;
  22960. this._animationStarted = false;
  22961. this._loopAnimation = false;
  22962. this._fromIndex = 0;
  22963. this._toIndex = 0;
  22964. this._delay = 0;
  22965. this._direction = 1;
  22966. this._frameCount = 0;
  22967. this._time = 0;
  22968. this._manager = manager;
  22969. this._manager.sprites.push(this);
  22970. this.position = BABYLON.Vector3.Zero();
  22971. }
  22972. Object.defineProperty(Sprite.prototype, "size", {
  22973. get: function () {
  22974. return this.width;
  22975. },
  22976. set: function (value) {
  22977. this.width = value;
  22978. this.height = value;
  22979. },
  22980. enumerable: true,
  22981. configurable: true
  22982. });
  22983. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  22984. this._fromIndex = from;
  22985. this._toIndex = to;
  22986. this._loopAnimation = loop;
  22987. this._delay = delay;
  22988. this._animationStarted = true;
  22989. this._direction = from < to ? 1 : -1;
  22990. this.cellIndex = from;
  22991. this._time = 0;
  22992. };
  22993. Sprite.prototype.stopAnimation = function () {
  22994. this._animationStarted = false;
  22995. };
  22996. Sprite.prototype._animate = function (deltaTime) {
  22997. if (!this._animationStarted)
  22998. return;
  22999. this._time += deltaTime;
  23000. if (this._time > this._delay) {
  23001. this._time = this._time % this._delay;
  23002. this.cellIndex += this._direction;
  23003. if (this.cellIndex == this._toIndex) {
  23004. if (this._loopAnimation) {
  23005. this.cellIndex = this._fromIndex;
  23006. }
  23007. else {
  23008. this._animationStarted = false;
  23009. if (this.disposeWhenFinishedAnimating) {
  23010. this.dispose();
  23011. }
  23012. }
  23013. }
  23014. }
  23015. };
  23016. Sprite.prototype.dispose = function () {
  23017. for (var i = 0; i < this._manager.sprites.length; i++) {
  23018. if (this._manager.sprites[i] == this) {
  23019. this._manager.sprites.splice(i, 1);
  23020. }
  23021. }
  23022. };
  23023. return Sprite;
  23024. })();
  23025. BABYLON.Sprite = Sprite;
  23026. })(BABYLON || (BABYLON = {}));
  23027. var BABYLON;
  23028. (function (BABYLON) {
  23029. var Layer = (function () {
  23030. function Layer(name, imgUrl, scene, isBackground, color) {
  23031. this.name = name;
  23032. this.scale = new BABYLON.Vector2(1, 1);
  23033. this.offset = new BABYLON.Vector2(0, 0);
  23034. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  23035. this._vertexDeclaration = [2];
  23036. this._vertexStrideSize = 2 * 4;
  23037. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  23038. this.isBackground = isBackground === undefined ? true : isBackground;
  23039. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  23040. this._scene = scene;
  23041. this._scene.layers.push(this);
  23042. // VBO
  23043. var vertices = [];
  23044. vertices.push(1, 1);
  23045. vertices.push(-1, 1);
  23046. vertices.push(-1, -1);
  23047. vertices.push(1, -1);
  23048. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23049. // Indices
  23050. var indices = [];
  23051. indices.push(0);
  23052. indices.push(1);
  23053. indices.push(2);
  23054. indices.push(0);
  23055. indices.push(2);
  23056. indices.push(3);
  23057. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23058. // Effects
  23059. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  23060. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  23061. }
  23062. Layer.prototype.render = function () {
  23063. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  23064. // Check
  23065. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  23066. return;
  23067. var engine = this._scene.getEngine();
  23068. if (this.onBeforeRender) {
  23069. this.onBeforeRender();
  23070. }
  23071. // Render
  23072. engine.enableEffect(currentEffect);
  23073. engine.setState(false);
  23074. // Texture
  23075. currentEffect.setTexture("textureSampler", this.texture);
  23076. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  23077. // Color
  23078. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  23079. // Scale / offset
  23080. currentEffect.setVector2("offset", this.offset);
  23081. currentEffect.setVector2("scale", this.scale);
  23082. // VBOs
  23083. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  23084. // Draw order
  23085. if (!this._alphaTestEffect) {
  23086. engine.setAlphaMode(this.alphaBlendingMode);
  23087. engine.draw(true, 0, 6);
  23088. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23089. }
  23090. else {
  23091. engine.draw(true, 0, 6);
  23092. }
  23093. if (this.onAfterRender) {
  23094. this.onAfterRender();
  23095. }
  23096. };
  23097. Layer.prototype.dispose = function () {
  23098. if (this._vertexBuffer) {
  23099. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23100. this._vertexBuffer = null;
  23101. }
  23102. if (this._indexBuffer) {
  23103. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23104. this._indexBuffer = null;
  23105. }
  23106. if (this.texture) {
  23107. this.texture.dispose();
  23108. this.texture = null;
  23109. }
  23110. // Remove from scene
  23111. var index = this._scene.layers.indexOf(this);
  23112. this._scene.layers.splice(index, 1);
  23113. // Callback
  23114. if (this.onDispose) {
  23115. this.onDispose();
  23116. }
  23117. };
  23118. return Layer;
  23119. })();
  23120. BABYLON.Layer = Layer;
  23121. })(BABYLON || (BABYLON = {}));
  23122. var BABYLON;
  23123. (function (BABYLON) {
  23124. var Particle = (function () {
  23125. function Particle() {
  23126. this.position = BABYLON.Vector3.Zero();
  23127. this.direction = BABYLON.Vector3.Zero();
  23128. this.color = new BABYLON.Color4(0, 0, 0, 0);
  23129. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  23130. this.lifeTime = 1.0;
  23131. this.age = 0;
  23132. this.size = 0;
  23133. this.angle = 0;
  23134. this.angularSpeed = 0;
  23135. }
  23136. Particle.prototype.copyTo = function (other) {
  23137. other.position.copyFrom(this.position);
  23138. other.direction.copyFrom(this.direction);
  23139. other.color.copyFrom(this.color);
  23140. other.colorStep.copyFrom(this.colorStep);
  23141. other.lifeTime = this.lifeTime;
  23142. other.age = this.age;
  23143. other.size = this.size;
  23144. other.angle = this.angle;
  23145. other.angularSpeed = this.angularSpeed;
  23146. };
  23147. return Particle;
  23148. })();
  23149. BABYLON.Particle = Particle;
  23150. })(BABYLON || (BABYLON = {}));
  23151. var BABYLON;
  23152. (function (BABYLON) {
  23153. var randomNumber = function (min, max) {
  23154. if (min === max) {
  23155. return (min);
  23156. }
  23157. var random = Math.random();
  23158. return ((random * (max - min)) + min);
  23159. };
  23160. var ParticleSystem = (function () {
  23161. function ParticleSystem(name, capacity, scene, customEffect) {
  23162. var _this = this;
  23163. this.name = name;
  23164. // Members
  23165. this.animations = [];
  23166. this.renderingGroupId = 0;
  23167. this.emitter = null;
  23168. this.emitRate = 10;
  23169. this.manualEmitCount = -1;
  23170. this.updateSpeed = 0.01;
  23171. this.targetStopDuration = 0;
  23172. this.disposeOnStop = false;
  23173. this.minEmitPower = 1;
  23174. this.maxEmitPower = 1;
  23175. this.minLifeTime = 1;
  23176. this.maxLifeTime = 1;
  23177. this.minSize = 1;
  23178. this.maxSize = 1;
  23179. this.minAngularSpeed = 0;
  23180. this.maxAngularSpeed = 0;
  23181. this.layerMask = 0x0FFFFFFF;
  23182. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  23183. this.forceDepthWrite = false;
  23184. this.gravity = BABYLON.Vector3.Zero();
  23185. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  23186. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  23187. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  23188. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  23189. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23190. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23191. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  23192. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23193. this.particles = new Array();
  23194. this._vertexDeclaration = [3, 4, 4];
  23195. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  23196. this._stockParticles = new Array();
  23197. this._newPartsExcess = 0;
  23198. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  23199. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  23200. this._scaledDirection = BABYLON.Vector3.Zero();
  23201. this._scaledGravity = BABYLON.Vector3.Zero();
  23202. this._currentRenderId = -1;
  23203. this._started = false;
  23204. this._stopped = false;
  23205. this._actualFrame = 0;
  23206. this.id = name;
  23207. this._capacity = capacity;
  23208. this._scene = scene;
  23209. this._customEffect = customEffect;
  23210. scene.particleSystems.push(this);
  23211. // VBO
  23212. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  23213. var indices = [];
  23214. var index = 0;
  23215. for (var count = 0; count < capacity; count++) {
  23216. indices.push(index);
  23217. indices.push(index + 1);
  23218. indices.push(index + 2);
  23219. indices.push(index);
  23220. indices.push(index + 2);
  23221. indices.push(index + 3);
  23222. index += 4;
  23223. }
  23224. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23225. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  23226. // Default behaviors
  23227. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  23228. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  23229. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  23230. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  23231. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  23232. };
  23233. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  23234. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  23235. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  23236. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  23237. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  23238. };
  23239. this.updateFunction = function (particles) {
  23240. for (var index = 0; index < particles.length; index++) {
  23241. var particle = particles[index];
  23242. particle.age += _this._scaledUpdateSpeed;
  23243. if (particle.age >= particle.lifeTime) {
  23244. _this.recycleParticle(particle);
  23245. index--;
  23246. continue;
  23247. }
  23248. else {
  23249. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  23250. particle.color.addInPlace(_this._scaledColorStep);
  23251. if (particle.color.a < 0)
  23252. particle.color.a = 0;
  23253. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  23254. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  23255. particle.position.addInPlace(_this._scaledDirection);
  23256. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  23257. particle.direction.addInPlace(_this._scaledGravity);
  23258. }
  23259. }
  23260. };
  23261. }
  23262. ParticleSystem.prototype.recycleParticle = function (particle) {
  23263. var lastParticle = this.particles.pop();
  23264. if (lastParticle !== particle) {
  23265. lastParticle.copyTo(particle);
  23266. this._stockParticles.push(lastParticle);
  23267. }
  23268. };
  23269. ParticleSystem.prototype.getCapacity = function () {
  23270. return this._capacity;
  23271. };
  23272. ParticleSystem.prototype.isAlive = function () {
  23273. return this._alive;
  23274. };
  23275. ParticleSystem.prototype.isStarted = function () {
  23276. return this._started;
  23277. };
  23278. ParticleSystem.prototype.start = function () {
  23279. this._started = true;
  23280. this._stopped = false;
  23281. this._actualFrame = 0;
  23282. };
  23283. ParticleSystem.prototype.stop = function () {
  23284. this._stopped = true;
  23285. };
  23286. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  23287. var offset = index * 11;
  23288. this._vertices[offset] = particle.position.x;
  23289. this._vertices[offset + 1] = particle.position.y;
  23290. this._vertices[offset + 2] = particle.position.z;
  23291. this._vertices[offset + 3] = particle.color.r;
  23292. this._vertices[offset + 4] = particle.color.g;
  23293. this._vertices[offset + 5] = particle.color.b;
  23294. this._vertices[offset + 6] = particle.color.a;
  23295. this._vertices[offset + 7] = particle.angle;
  23296. this._vertices[offset + 8] = particle.size;
  23297. this._vertices[offset + 9] = offsetX;
  23298. this._vertices[offset + 10] = offsetY;
  23299. };
  23300. ParticleSystem.prototype._update = function (newParticles) {
  23301. // Update current
  23302. this._alive = this.particles.length > 0;
  23303. this.updateFunction(this.particles);
  23304. // Add new ones
  23305. var worldMatrix;
  23306. if (this.emitter.position) {
  23307. worldMatrix = this.emitter.getWorldMatrix();
  23308. }
  23309. else {
  23310. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  23311. }
  23312. var particle;
  23313. for (var index = 0; index < newParticles; index++) {
  23314. if (this.particles.length === this._capacity) {
  23315. break;
  23316. }
  23317. if (this._stockParticles.length !== 0) {
  23318. particle = this._stockParticles.pop();
  23319. particle.age = 0;
  23320. }
  23321. else {
  23322. particle = new BABYLON.Particle();
  23323. }
  23324. this.particles.push(particle);
  23325. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  23326. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  23327. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  23328. particle.size = randomNumber(this.minSize, this.maxSize);
  23329. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  23330. this.startPositionFunction(worldMatrix, particle.position, particle);
  23331. var step = randomNumber(0, 1.0);
  23332. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  23333. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  23334. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  23335. }
  23336. };
  23337. ParticleSystem.prototype._getEffect = function () {
  23338. if (this._customEffect) {
  23339. return this._customEffect;
  23340. }
  23341. ;
  23342. var defines = [];
  23343. if (this._scene.clipPlane) {
  23344. defines.push("#define CLIPPLANE");
  23345. }
  23346. // Effect
  23347. var join = defines.join("\n");
  23348. if (this._cachedDefines !== join) {
  23349. this._cachedDefines = join;
  23350. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  23351. }
  23352. return this._effect;
  23353. };
  23354. ParticleSystem.prototype.animate = function () {
  23355. if (!this._started)
  23356. return;
  23357. var effect = this._getEffect();
  23358. // Check
  23359. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  23360. return;
  23361. if (this._currentRenderId === this._scene.getRenderId()) {
  23362. return;
  23363. }
  23364. this._currentRenderId = this._scene.getRenderId();
  23365. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  23366. // determine the number of particles we need to create
  23367. var newParticles;
  23368. if (this.manualEmitCount > -1) {
  23369. newParticles = this.manualEmitCount;
  23370. this._newPartsExcess = 0;
  23371. this.manualEmitCount = 0;
  23372. }
  23373. else {
  23374. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  23375. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  23376. }
  23377. if (this._newPartsExcess > 1.0) {
  23378. newParticles += this._newPartsExcess >> 0;
  23379. this._newPartsExcess -= this._newPartsExcess >> 0;
  23380. }
  23381. this._alive = false;
  23382. if (!this._stopped) {
  23383. this._actualFrame += this._scaledUpdateSpeed;
  23384. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  23385. this.stop();
  23386. }
  23387. else {
  23388. newParticles = 0;
  23389. }
  23390. this._update(newParticles);
  23391. // Stopped?
  23392. if (this._stopped) {
  23393. if (!this._alive) {
  23394. this._started = false;
  23395. if (this.disposeOnStop) {
  23396. this._scene._toBeDisposed.push(this);
  23397. }
  23398. }
  23399. }
  23400. // Update VBO
  23401. var offset = 0;
  23402. for (var index = 0; index < this.particles.length; index++) {
  23403. var particle = this.particles[index];
  23404. this._appendParticleVertex(offset++, particle, 0, 0);
  23405. this._appendParticleVertex(offset++, particle, 1, 0);
  23406. this._appendParticleVertex(offset++, particle, 1, 1);
  23407. this._appendParticleVertex(offset++, particle, 0, 1);
  23408. }
  23409. var engine = this._scene.getEngine();
  23410. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  23411. };
  23412. ParticleSystem.prototype.render = function () {
  23413. var effect = this._getEffect();
  23414. // Check
  23415. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  23416. return 0;
  23417. var engine = this._scene.getEngine();
  23418. // Render
  23419. engine.enableEffect(effect);
  23420. engine.setState(false);
  23421. var viewMatrix = this._scene.getViewMatrix();
  23422. effect.setTexture("diffuseSampler", this.particleTexture);
  23423. effect.setMatrix("view", viewMatrix);
  23424. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  23425. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  23426. if (this._scene.clipPlane) {
  23427. var clipPlane = this._scene.clipPlane;
  23428. var invView = viewMatrix.clone();
  23429. invView.invert();
  23430. effect.setMatrix("invView", invView);
  23431. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23432. }
  23433. // VBOs
  23434. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23435. // Draw order
  23436. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  23437. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23438. }
  23439. else {
  23440. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23441. }
  23442. if (this.forceDepthWrite) {
  23443. engine.setDepthWrite(true);
  23444. }
  23445. engine.draw(true, 0, this.particles.length * 6);
  23446. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23447. return this.particles.length;
  23448. };
  23449. ParticleSystem.prototype.dispose = function () {
  23450. if (this._vertexBuffer) {
  23451. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23452. this._vertexBuffer = null;
  23453. }
  23454. if (this._indexBuffer) {
  23455. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23456. this._indexBuffer = null;
  23457. }
  23458. if (this.particleTexture) {
  23459. this.particleTexture.dispose();
  23460. this.particleTexture = null;
  23461. }
  23462. // Remove from scene
  23463. var index = this._scene.particleSystems.indexOf(this);
  23464. this._scene.particleSystems.splice(index, 1);
  23465. // Callback
  23466. if (this.onDispose) {
  23467. this.onDispose();
  23468. }
  23469. };
  23470. // Clone
  23471. ParticleSystem.prototype.clone = function (name, newEmitter) {
  23472. var result = new ParticleSystem(name, this._capacity, this._scene);
  23473. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  23474. if (newEmitter === undefined) {
  23475. newEmitter = this.emitter;
  23476. }
  23477. result.emitter = newEmitter;
  23478. if (this.particleTexture) {
  23479. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  23480. }
  23481. result.start();
  23482. return result;
  23483. };
  23484. ParticleSystem.prototype.serialize = function () {
  23485. var serializationObject = {};
  23486. serializationObject.name = this.name;
  23487. serializationObject.id = this.id;
  23488. // Emitter
  23489. if (this.emitter.position) {
  23490. serializationObject.emitterId = this.emitter.id;
  23491. }
  23492. else {
  23493. serializationObject.emitter = this.emitter.asArray();
  23494. }
  23495. serializationObject.capacity = this.getCapacity();
  23496. if (this.particleTexture) {
  23497. serializationObject.textureName = this.particleTexture.name;
  23498. }
  23499. // Animations
  23500. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23501. // Particle system
  23502. serializationObject.minAngularSpeed = this.minAngularSpeed;
  23503. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  23504. serializationObject.minSize = this.minSize;
  23505. serializationObject.maxSize = this.maxSize;
  23506. serializationObject.minEmitPower = this.minEmitPower;
  23507. serializationObject.maxEmitPower = this.maxEmitPower;
  23508. serializationObject.minLifeTime = this.minLifeTime;
  23509. serializationObject.maxLifeTime = this.maxLifeTime;
  23510. serializationObject.emitRate = this.emitRate;
  23511. serializationObject.minEmitBox = this.minEmitBox.asArray();
  23512. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  23513. serializationObject.gravity = this.gravity.asArray();
  23514. serializationObject.direction1 = this.direction1.asArray();
  23515. serializationObject.direction2 = this.direction2.asArray();
  23516. serializationObject.color1 = this.color1.asArray();
  23517. serializationObject.color2 = this.color2.asArray();
  23518. serializationObject.colorDead = this.colorDead.asArray();
  23519. serializationObject.updateSpeed = this.updateSpeed;
  23520. serializationObject.targetStopDuration = this.targetStopDuration;
  23521. serializationObject.textureMask = this.textureMask.asArray();
  23522. serializationObject.blendMode = this.blendMode;
  23523. return serializationObject;
  23524. };
  23525. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  23526. var name = parsedParticleSystem.name;
  23527. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  23528. if (parsedParticleSystem.id) {
  23529. particleSystem.id = parsedParticleSystem.id;
  23530. }
  23531. // Texture
  23532. if (parsedParticleSystem.textureName) {
  23533. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  23534. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  23535. }
  23536. // Emitter
  23537. if (parsedParticleSystem.emitterId) {
  23538. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  23539. }
  23540. else {
  23541. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  23542. }
  23543. // Animations
  23544. if (parsedParticleSystem.animations) {
  23545. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  23546. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  23547. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23548. }
  23549. }
  23550. if (parsedParticleSystem.autoAnimate) {
  23551. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  23552. }
  23553. // Particle system
  23554. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  23555. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  23556. particleSystem.minSize = parsedParticleSystem.minSize;
  23557. particleSystem.maxSize = parsedParticleSystem.maxSize;
  23558. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  23559. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  23560. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  23561. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  23562. particleSystem.emitRate = parsedParticleSystem.emitRate;
  23563. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  23564. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  23565. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  23566. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  23567. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  23568. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  23569. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  23570. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  23571. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  23572. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  23573. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  23574. particleSystem.blendMode = parsedParticleSystem.blendMode;
  23575. particleSystem.start();
  23576. return particleSystem;
  23577. };
  23578. // Statics
  23579. ParticleSystem.BLENDMODE_ONEONE = 0;
  23580. ParticleSystem.BLENDMODE_STANDARD = 1;
  23581. return ParticleSystem;
  23582. })();
  23583. BABYLON.ParticleSystem = ParticleSystem;
  23584. })(BABYLON || (BABYLON = {}));
  23585. var BABYLON;
  23586. (function (BABYLON) {
  23587. var AnimationRange = (function () {
  23588. function AnimationRange(name, from, to) {
  23589. this.name = name;
  23590. this.from = from;
  23591. this.to = to;
  23592. }
  23593. AnimationRange.prototype.clone = function () {
  23594. return new AnimationRange(this.name, this.from, this.to);
  23595. };
  23596. return AnimationRange;
  23597. })();
  23598. BABYLON.AnimationRange = AnimationRange;
  23599. /**
  23600. * Composed of a frame, and an action function
  23601. */
  23602. var AnimationEvent = (function () {
  23603. function AnimationEvent(frame, action, onlyOnce) {
  23604. this.frame = frame;
  23605. this.action = action;
  23606. this.onlyOnce = onlyOnce;
  23607. this.isDone = false;
  23608. }
  23609. return AnimationEvent;
  23610. })();
  23611. BABYLON.AnimationEvent = AnimationEvent;
  23612. var PathCursor = (function () {
  23613. function PathCursor(path) {
  23614. this.path = path;
  23615. this._onchange = new Array();
  23616. this.value = 0;
  23617. this.animations = new Array();
  23618. }
  23619. PathCursor.prototype.getPoint = function () {
  23620. var point = this.path.getPointAtLengthPosition(this.value);
  23621. return new BABYLON.Vector3(point.x, 0, point.y);
  23622. };
  23623. PathCursor.prototype.moveAhead = function (step) {
  23624. if (step === void 0) { step = 0.002; }
  23625. this.move(step);
  23626. return this;
  23627. };
  23628. PathCursor.prototype.moveBack = function (step) {
  23629. if (step === void 0) { step = 0.002; }
  23630. this.move(-step);
  23631. return this;
  23632. };
  23633. PathCursor.prototype.move = function (step) {
  23634. if (Math.abs(step) > 1) {
  23635. throw "step size should be less than 1.";
  23636. }
  23637. this.value += step;
  23638. this.ensureLimits();
  23639. this.raiseOnChange();
  23640. return this;
  23641. };
  23642. PathCursor.prototype.ensureLimits = function () {
  23643. while (this.value > 1) {
  23644. this.value -= 1;
  23645. }
  23646. while (this.value < 0) {
  23647. this.value += 1;
  23648. }
  23649. return this;
  23650. };
  23651. // used by animation engine
  23652. PathCursor.prototype.markAsDirty = function (propertyName) {
  23653. this.ensureLimits();
  23654. this.raiseOnChange();
  23655. return this;
  23656. };
  23657. PathCursor.prototype.raiseOnChange = function () {
  23658. var _this = this;
  23659. this._onchange.forEach(function (f) { return f(_this); });
  23660. return this;
  23661. };
  23662. PathCursor.prototype.onchange = function (f) {
  23663. this._onchange.push(f);
  23664. return this;
  23665. };
  23666. return PathCursor;
  23667. })();
  23668. BABYLON.PathCursor = PathCursor;
  23669. var Animation = (function () {
  23670. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  23671. this.name = name;
  23672. this.targetProperty = targetProperty;
  23673. this.framePerSecond = framePerSecond;
  23674. this.dataType = dataType;
  23675. this.loopMode = loopMode;
  23676. this.enableBlending = enableBlending;
  23677. this._offsetsCache = {};
  23678. this._highLimitsCache = {};
  23679. this._stopped = false;
  23680. this._blendingFactor = 0;
  23681. // The set of event that will be linked to this animation
  23682. this._events = new Array();
  23683. this.allowMatricesInterpolation = false;
  23684. this.blendingSpeed = 0.01;
  23685. this._ranges = {};
  23686. this.targetPropertyPath = targetProperty.split(".");
  23687. this.dataType = dataType;
  23688. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  23689. }
  23690. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  23691. var dataType = undefined;
  23692. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  23693. dataType = Animation.ANIMATIONTYPE_FLOAT;
  23694. }
  23695. else if (from instanceof BABYLON.Quaternion) {
  23696. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  23697. }
  23698. else if (from instanceof BABYLON.Vector3) {
  23699. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  23700. }
  23701. else if (from instanceof BABYLON.Vector2) {
  23702. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  23703. }
  23704. else if (from instanceof BABYLON.Color3) {
  23705. dataType = Animation.ANIMATIONTYPE_COLOR3;
  23706. }
  23707. if (dataType == undefined) {
  23708. return null;
  23709. }
  23710. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  23711. var keys = [];
  23712. keys.push({ frame: 0, value: from });
  23713. keys.push({ frame: totalFrame, value: to });
  23714. animation.setKeys(keys);
  23715. if (easingFunction !== undefined) {
  23716. animation.setEasingFunction(easingFunction);
  23717. }
  23718. return animation;
  23719. };
  23720. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  23721. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  23722. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  23723. };
  23724. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  23725. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  23726. node.animations.push(animation);
  23727. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  23728. };
  23729. // Methods
  23730. /**
  23731. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23732. */
  23733. Animation.prototype.toString = function (fullDetails) {
  23734. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  23735. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  23736. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  23737. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  23738. if (fullDetails) {
  23739. ret += ", Ranges: {";
  23740. var first = true;
  23741. for (var name in this._ranges) {
  23742. if (!first) {
  23743. ret + ", ";
  23744. first = false;
  23745. }
  23746. ret += name;
  23747. }
  23748. ret += "}";
  23749. }
  23750. return ret;
  23751. };
  23752. /**
  23753. * Add an event to this animation.
  23754. */
  23755. Animation.prototype.addEvent = function (event) {
  23756. this._events.push(event);
  23757. };
  23758. /**
  23759. * Remove all events found at the given frame
  23760. * @param frame
  23761. */
  23762. Animation.prototype.removeEvents = function (frame) {
  23763. for (var index = 0; index < this._events.length; index++) {
  23764. if (this._events[index].frame === frame) {
  23765. this._events.splice(index, 1);
  23766. index--;
  23767. }
  23768. }
  23769. };
  23770. Animation.prototype.createRange = function (name, from, to) {
  23771. // check name not already in use; could happen for bones after serialized
  23772. if (!this._ranges[name]) {
  23773. this._ranges[name] = new AnimationRange(name, from, to);
  23774. }
  23775. };
  23776. Animation.prototype.deleteRange = function (name, deleteFrames) {
  23777. if (deleteFrames === void 0) { deleteFrames = true; }
  23778. if (this._ranges[name]) {
  23779. if (deleteFrames) {
  23780. var from = this._ranges[name].from;
  23781. var to = this._ranges[name].to;
  23782. // this loop MUST go high to low for multiple splices to work
  23783. for (var key = this._keys.length - 1; key >= 0; key--) {
  23784. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  23785. this._keys.splice(key, 1);
  23786. }
  23787. }
  23788. }
  23789. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23790. }
  23791. };
  23792. Animation.prototype.getRange = function (name) {
  23793. return this._ranges[name];
  23794. };
  23795. Animation.prototype.reset = function () {
  23796. this._offsetsCache = {};
  23797. this._highLimitsCache = {};
  23798. this.currentFrame = 0;
  23799. this._blendingFactor = 0;
  23800. this._originalBlendValue = null;
  23801. };
  23802. Animation.prototype.isStopped = function () {
  23803. return this._stopped;
  23804. };
  23805. Animation.prototype.getKeys = function () {
  23806. return this._keys;
  23807. };
  23808. Animation.prototype.getHighestFrame = function () {
  23809. var ret = 0;
  23810. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  23811. if (ret < this._keys[key].frame) {
  23812. ret = this._keys[key].frame;
  23813. }
  23814. }
  23815. return ret;
  23816. };
  23817. Animation.prototype.getEasingFunction = function () {
  23818. return this._easingFunction;
  23819. };
  23820. Animation.prototype.setEasingFunction = function (easingFunction) {
  23821. this._easingFunction = easingFunction;
  23822. };
  23823. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  23824. return startValue + (endValue - startValue) * gradient;
  23825. };
  23826. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  23827. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  23828. };
  23829. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  23830. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  23831. };
  23832. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  23833. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  23834. };
  23835. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  23836. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  23837. };
  23838. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  23839. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  23840. };
  23841. Animation.prototype.clone = function () {
  23842. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  23843. if (this._keys) {
  23844. clone.setKeys(this._keys);
  23845. }
  23846. if (this._ranges) {
  23847. clone._ranges = {};
  23848. for (var name in this._ranges) {
  23849. clone._ranges[name] = this._ranges[name].clone();
  23850. }
  23851. }
  23852. return clone;
  23853. };
  23854. Animation.prototype.setKeys = function (values) {
  23855. this._keys = values.slice(0);
  23856. this._offsetsCache = {};
  23857. this._highLimitsCache = {};
  23858. };
  23859. Animation.prototype._getKeyValue = function (value) {
  23860. if (typeof value === "function") {
  23861. return value();
  23862. }
  23863. return value;
  23864. };
  23865. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  23866. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  23867. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  23868. }
  23869. this.currentFrame = currentFrame;
  23870. // Try to get a hash to find the right key
  23871. 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));
  23872. if (this._keys[startKey].frame >= currentFrame) {
  23873. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  23874. startKey--;
  23875. }
  23876. }
  23877. for (var key = startKey; key < this._keys.length; key++) {
  23878. if (this._keys[key + 1].frame >= currentFrame) {
  23879. var startValue = this._getKeyValue(this._keys[key].value);
  23880. var endValue = this._getKeyValue(this._keys[key + 1].value);
  23881. // gradient : percent of currentFrame between the frame inf and the frame sup
  23882. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  23883. // check for easingFunction and correction of gradient
  23884. if (this._easingFunction != null) {
  23885. gradient = this._easingFunction.ease(gradient);
  23886. }
  23887. switch (this.dataType) {
  23888. // Float
  23889. case Animation.ANIMATIONTYPE_FLOAT:
  23890. switch (loopMode) {
  23891. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23892. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23893. return this.floatInterpolateFunction(startValue, endValue, gradient);
  23894. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23895. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  23896. }
  23897. break;
  23898. // Quaternion
  23899. case Animation.ANIMATIONTYPE_QUATERNION:
  23900. var quaternion = null;
  23901. switch (loopMode) {
  23902. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23903. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23904. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  23905. break;
  23906. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23907. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23908. break;
  23909. }
  23910. return quaternion;
  23911. // Vector3
  23912. case Animation.ANIMATIONTYPE_VECTOR3:
  23913. switch (loopMode) {
  23914. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23915. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23916. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  23917. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23918. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23919. }
  23920. // Vector2
  23921. case Animation.ANIMATIONTYPE_VECTOR2:
  23922. switch (loopMode) {
  23923. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23924. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23925. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  23926. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23927. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23928. }
  23929. // Color3
  23930. case Animation.ANIMATIONTYPE_COLOR3:
  23931. switch (loopMode) {
  23932. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23933. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23934. return this.color3InterpolateFunction(startValue, endValue, gradient);
  23935. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23936. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23937. }
  23938. // Matrix
  23939. case Animation.ANIMATIONTYPE_MATRIX:
  23940. switch (loopMode) {
  23941. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23942. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23943. if (this.allowMatricesInterpolation) {
  23944. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  23945. }
  23946. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23947. return startValue;
  23948. }
  23949. default:
  23950. break;
  23951. }
  23952. break;
  23953. }
  23954. }
  23955. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  23956. };
  23957. Animation.prototype.setValue = function (currentValue, blend) {
  23958. if (blend === void 0) { blend = false; }
  23959. // Set value
  23960. var path;
  23961. var destination;
  23962. if (this.targetPropertyPath.length > 1) {
  23963. var property = this._target[this.targetPropertyPath[0]];
  23964. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  23965. property = property[this.targetPropertyPath[index]];
  23966. }
  23967. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  23968. destination = property;
  23969. }
  23970. else {
  23971. path = this.targetPropertyPath[0];
  23972. destination = this._target;
  23973. }
  23974. // Blending
  23975. if (this.enableBlending && this._blendingFactor <= 1.0) {
  23976. if (!this._originalBlendValue) {
  23977. this._originalBlendValue = destination[path];
  23978. }
  23979. if (this._originalBlendValue.prototype) {
  23980. if (this._originalBlendValue.prototype.Lerp) {
  23981. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  23982. }
  23983. else {
  23984. destination[path] = currentValue;
  23985. }
  23986. }
  23987. else {
  23988. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  23989. }
  23990. this._blendingFactor += this.blendingSpeed;
  23991. }
  23992. else {
  23993. destination[path] = currentValue;
  23994. }
  23995. if (this._target.markAsDirty) {
  23996. this._target.markAsDirty(this.targetProperty);
  23997. }
  23998. };
  23999. Animation.prototype.goToFrame = function (frame) {
  24000. if (frame < this._keys[0].frame) {
  24001. frame = this._keys[0].frame;
  24002. }
  24003. else if (frame > this._keys[this._keys.length - 1].frame) {
  24004. frame = this._keys[this._keys.length - 1].frame;
  24005. }
  24006. var currentValue = this._interpolate(frame, 0, this.loopMode);
  24007. this.setValue(currentValue);
  24008. };
  24009. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  24010. if (blend === void 0) { blend = false; }
  24011. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  24012. this._stopped = true;
  24013. return false;
  24014. }
  24015. var returnValue = true;
  24016. // Adding a start key at frame 0 if missing
  24017. if (this._keys[0].frame !== 0) {
  24018. var newKey = { frame: 0, value: this._keys[0].value };
  24019. this._keys.splice(0, 0, newKey);
  24020. }
  24021. // Check limits
  24022. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  24023. from = this._keys[0].frame;
  24024. }
  24025. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  24026. to = this._keys[this._keys.length - 1].frame;
  24027. }
  24028. // Compute ratio
  24029. var range = to - from;
  24030. var offsetValue;
  24031. // ratio represents the frame delta between from and to
  24032. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  24033. var highLimitValue = 0;
  24034. if (ratio > range && !loop) {
  24035. returnValue = false;
  24036. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  24037. }
  24038. else {
  24039. // Get max value if required
  24040. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  24041. var keyOffset = to.toString() + from.toString();
  24042. if (!this._offsetsCache[keyOffset]) {
  24043. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24044. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24045. switch (this.dataType) {
  24046. // Float
  24047. case Animation.ANIMATIONTYPE_FLOAT:
  24048. this._offsetsCache[keyOffset] = toValue - fromValue;
  24049. break;
  24050. // Quaternion
  24051. case Animation.ANIMATIONTYPE_QUATERNION:
  24052. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24053. break;
  24054. // Vector3
  24055. case Animation.ANIMATIONTYPE_VECTOR3:
  24056. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24057. // Vector2
  24058. case Animation.ANIMATIONTYPE_VECTOR2:
  24059. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24060. // Color3
  24061. case Animation.ANIMATIONTYPE_COLOR3:
  24062. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24063. default:
  24064. break;
  24065. }
  24066. this._highLimitsCache[keyOffset] = toValue;
  24067. }
  24068. highLimitValue = this._highLimitsCache[keyOffset];
  24069. offsetValue = this._offsetsCache[keyOffset];
  24070. }
  24071. }
  24072. if (offsetValue === undefined) {
  24073. switch (this.dataType) {
  24074. // Float
  24075. case Animation.ANIMATIONTYPE_FLOAT:
  24076. offsetValue = 0;
  24077. break;
  24078. // Quaternion
  24079. case Animation.ANIMATIONTYPE_QUATERNION:
  24080. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  24081. break;
  24082. // Vector3
  24083. case Animation.ANIMATIONTYPE_VECTOR3:
  24084. offsetValue = BABYLON.Vector3.Zero();
  24085. break;
  24086. // Vector2
  24087. case Animation.ANIMATIONTYPE_VECTOR2:
  24088. offsetValue = BABYLON.Vector2.Zero();
  24089. break;
  24090. // Color3
  24091. case Animation.ANIMATIONTYPE_COLOR3:
  24092. offsetValue = BABYLON.Color3.Black();
  24093. }
  24094. }
  24095. // Compute value
  24096. var repeatCount = (ratio / range) >> 0;
  24097. var currentFrame = returnValue ? from + ratio % range : to;
  24098. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  24099. // Set value
  24100. this.setValue(currentValue);
  24101. // Check events
  24102. for (var index = 0; index < this._events.length; index++) {
  24103. if (currentFrame >= this._events[index].frame) {
  24104. var event = this._events[index];
  24105. if (!event.isDone) {
  24106. // If event should be done only once, remove it.
  24107. if (event.onlyOnce) {
  24108. this._events.splice(index, 1);
  24109. index--;
  24110. }
  24111. event.isDone = true;
  24112. event.action();
  24113. } // Don't do anything if the event has already be done.
  24114. }
  24115. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  24116. // reset event, the animation is looping
  24117. this._events[index].isDone = false;
  24118. }
  24119. }
  24120. if (!returnValue) {
  24121. this._stopped = true;
  24122. }
  24123. return returnValue;
  24124. };
  24125. Animation.prototype.serialize = function () {
  24126. var serializationObject = {};
  24127. serializationObject.name = this.name;
  24128. serializationObject.property = this.targetProperty;
  24129. serializationObject.framePerSecond = this.framePerSecond;
  24130. serializationObject.dataType = this.dataType;
  24131. serializationObject.loopBehavior = this.loopMode;
  24132. var dataType = this.dataType;
  24133. serializationObject.keys = [];
  24134. var keys = this.getKeys();
  24135. for (var index = 0; index < keys.length; index++) {
  24136. var animationKey = keys[index];
  24137. var key = {};
  24138. key.frame = animationKey.frame;
  24139. switch (dataType) {
  24140. case Animation.ANIMATIONTYPE_FLOAT:
  24141. key.values = [animationKey.value];
  24142. break;
  24143. case Animation.ANIMATIONTYPE_QUATERNION:
  24144. case Animation.ANIMATIONTYPE_MATRIX:
  24145. case Animation.ANIMATIONTYPE_VECTOR3:
  24146. case Animation.ANIMATIONTYPE_COLOR3:
  24147. key.values = animationKey.value.asArray();
  24148. break;
  24149. }
  24150. serializationObject.keys.push(key);
  24151. }
  24152. serializationObject.ranges = [];
  24153. for (var name in this._ranges) {
  24154. var range = {};
  24155. range.name = name;
  24156. range.from = this._ranges[name].from;
  24157. range.to = this._ranges[name].to;
  24158. serializationObject.ranges.push(range);
  24159. }
  24160. return serializationObject;
  24161. };
  24162. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  24163. get: function () {
  24164. return Animation._ANIMATIONTYPE_FLOAT;
  24165. },
  24166. enumerable: true,
  24167. configurable: true
  24168. });
  24169. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  24170. get: function () {
  24171. return Animation._ANIMATIONTYPE_VECTOR3;
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  24177. get: function () {
  24178. return Animation._ANIMATIONTYPE_VECTOR2;
  24179. },
  24180. enumerable: true,
  24181. configurable: true
  24182. });
  24183. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  24184. get: function () {
  24185. return Animation._ANIMATIONTYPE_QUATERNION;
  24186. },
  24187. enumerable: true,
  24188. configurable: true
  24189. });
  24190. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  24191. get: function () {
  24192. return Animation._ANIMATIONTYPE_MATRIX;
  24193. },
  24194. enumerable: true,
  24195. configurable: true
  24196. });
  24197. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  24198. get: function () {
  24199. return Animation._ANIMATIONTYPE_COLOR3;
  24200. },
  24201. enumerable: true,
  24202. configurable: true
  24203. });
  24204. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  24205. get: function () {
  24206. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  24207. },
  24208. enumerable: true,
  24209. configurable: true
  24210. });
  24211. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  24212. get: function () {
  24213. return Animation._ANIMATIONLOOPMODE_CYCLE;
  24214. },
  24215. enumerable: true,
  24216. configurable: true
  24217. });
  24218. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  24219. get: function () {
  24220. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Animation.Parse = function (parsedAnimation) {
  24226. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  24227. var dataType = parsedAnimation.dataType;
  24228. var keys = [];
  24229. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  24230. var key = parsedAnimation.keys[index];
  24231. var data;
  24232. switch (dataType) {
  24233. case Animation.ANIMATIONTYPE_FLOAT:
  24234. data = key.values[0];
  24235. break;
  24236. case Animation.ANIMATIONTYPE_QUATERNION:
  24237. data = BABYLON.Quaternion.FromArray(key.values);
  24238. break;
  24239. case Animation.ANIMATIONTYPE_MATRIX:
  24240. data = BABYLON.Matrix.FromArray(key.values);
  24241. break;
  24242. case Animation.ANIMATIONTYPE_COLOR3:
  24243. data = BABYLON.Color3.FromArray(key.values);
  24244. break;
  24245. case Animation.ANIMATIONTYPE_VECTOR3:
  24246. default:
  24247. data = BABYLON.Vector3.FromArray(key.values);
  24248. break;
  24249. }
  24250. keys.push({
  24251. frame: key.frame,
  24252. value: data
  24253. });
  24254. }
  24255. animation.setKeys(keys);
  24256. if (parsedAnimation.ranges) {
  24257. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  24258. data = parsedAnimation.ranges[index];
  24259. animation.createRange(data.name, data.from, data.to);
  24260. }
  24261. }
  24262. return animation;
  24263. };
  24264. Animation.AppendSerializedAnimations = function (source, destination) {
  24265. if (source.animations) {
  24266. destination.animations = [];
  24267. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24268. var animation = source.animations[animationIndex];
  24269. destination.animations.push(animation.serialize());
  24270. }
  24271. }
  24272. };
  24273. // Statics
  24274. Animation._ANIMATIONTYPE_FLOAT = 0;
  24275. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  24276. Animation._ANIMATIONTYPE_QUATERNION = 2;
  24277. Animation._ANIMATIONTYPE_MATRIX = 3;
  24278. Animation._ANIMATIONTYPE_COLOR3 = 4;
  24279. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  24280. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  24281. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  24282. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  24283. return Animation;
  24284. })();
  24285. BABYLON.Animation = Animation;
  24286. })(BABYLON || (BABYLON = {}));
  24287. var BABYLON;
  24288. (function (BABYLON) {
  24289. var Animatable = (function () {
  24290. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  24291. if (fromFrame === void 0) { fromFrame = 0; }
  24292. if (toFrame === void 0) { toFrame = 100; }
  24293. if (loopAnimation === void 0) { loopAnimation = false; }
  24294. if (speedRatio === void 0) { speedRatio = 1.0; }
  24295. this.target = target;
  24296. this.fromFrame = fromFrame;
  24297. this.toFrame = toFrame;
  24298. this.loopAnimation = loopAnimation;
  24299. this.speedRatio = speedRatio;
  24300. this.onAnimationEnd = onAnimationEnd;
  24301. this._animations = new Array();
  24302. this._paused = false;
  24303. this.animationStarted = false;
  24304. if (animations) {
  24305. this.appendAnimations(target, animations);
  24306. }
  24307. this._scene = scene;
  24308. scene._activeAnimatables.push(this);
  24309. }
  24310. // Methods
  24311. Animatable.prototype.getAnimations = function () {
  24312. return this._animations;
  24313. };
  24314. Animatable.prototype.appendAnimations = function (target, animations) {
  24315. for (var index = 0; index < animations.length; index++) {
  24316. var animation = animations[index];
  24317. animation._target = target;
  24318. this._animations.push(animation);
  24319. }
  24320. };
  24321. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  24322. var animations = this._animations;
  24323. for (var index = 0; index < animations.length; index++) {
  24324. if (animations[index].targetProperty === property) {
  24325. return animations[index];
  24326. }
  24327. }
  24328. return null;
  24329. };
  24330. Animatable.prototype.reset = function () {
  24331. var animations = this._animations;
  24332. for (var index = 0; index < animations.length; index++) {
  24333. animations[index].reset();
  24334. }
  24335. this._localDelayOffset = null;
  24336. this._pausedDelay = null;
  24337. };
  24338. Animatable.prototype.enableBlending = function (blendingSpeed) {
  24339. var animations = this._animations;
  24340. for (var index = 0; index < animations.length; index++) {
  24341. animations[index].enableBlending = true;
  24342. animations[index].blendingSpeed = blendingSpeed;
  24343. }
  24344. };
  24345. Animatable.prototype.disableBlending = function () {
  24346. var animations = this._animations;
  24347. for (var index = 0; index < animations.length; index++) {
  24348. animations[index].enableBlending = false;
  24349. }
  24350. };
  24351. Animatable.prototype.goToFrame = function (frame) {
  24352. var animations = this._animations;
  24353. for (var index = 0; index < animations.length; index++) {
  24354. animations[index].goToFrame(frame);
  24355. }
  24356. };
  24357. Animatable.prototype.pause = function () {
  24358. if (this._paused) {
  24359. return;
  24360. }
  24361. this._paused = true;
  24362. };
  24363. Animatable.prototype.restart = function () {
  24364. this._paused = false;
  24365. };
  24366. Animatable.prototype.stop = function () {
  24367. var index = this._scene._activeAnimatables.indexOf(this);
  24368. if (index > -1) {
  24369. this._scene._activeAnimatables.splice(index, 1);
  24370. var animations = this._animations;
  24371. for (var index = 0; index < animations.length; index++) {
  24372. animations[index].reset();
  24373. }
  24374. if (this.onAnimationEnd) {
  24375. this.onAnimationEnd();
  24376. }
  24377. }
  24378. };
  24379. Animatable.prototype._animate = function (delay) {
  24380. if (this._paused) {
  24381. this.animationStarted = false;
  24382. if (!this._pausedDelay) {
  24383. this._pausedDelay = delay;
  24384. }
  24385. return true;
  24386. }
  24387. if (!this._localDelayOffset) {
  24388. this._localDelayOffset = delay;
  24389. }
  24390. else if (this._pausedDelay) {
  24391. this._localDelayOffset += delay - this._pausedDelay;
  24392. this._pausedDelay = null;
  24393. }
  24394. // Animating
  24395. var running = false;
  24396. var animations = this._animations;
  24397. var index;
  24398. for (index = 0; index < animations.length; index++) {
  24399. var animation = animations[index];
  24400. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  24401. running = running || isRunning;
  24402. }
  24403. this.animationStarted = running;
  24404. if (!running) {
  24405. // Remove from active animatables
  24406. index = this._scene._activeAnimatables.indexOf(this);
  24407. this._scene._activeAnimatables.splice(index, 1);
  24408. }
  24409. if (!running && this.onAnimationEnd) {
  24410. this.onAnimationEnd();
  24411. this.onAnimationEnd = null;
  24412. }
  24413. return running;
  24414. };
  24415. return Animatable;
  24416. })();
  24417. BABYLON.Animatable = Animatable;
  24418. })(BABYLON || (BABYLON = {}));
  24419. var BABYLON;
  24420. (function (BABYLON) {
  24421. var EasingFunction = (function () {
  24422. function EasingFunction() {
  24423. // Properties
  24424. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  24425. }
  24426. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  24427. get: function () {
  24428. return EasingFunction._EASINGMODE_EASEIN;
  24429. },
  24430. enumerable: true,
  24431. configurable: true
  24432. });
  24433. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  24434. get: function () {
  24435. return EasingFunction._EASINGMODE_EASEOUT;
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  24441. get: function () {
  24442. return EasingFunction._EASINGMODE_EASEINOUT;
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. EasingFunction.prototype.setEasingMode = function (easingMode) {
  24448. var n = Math.min(Math.max(easingMode, 0), 2);
  24449. this._easingMode = n;
  24450. };
  24451. EasingFunction.prototype.getEasingMode = function () {
  24452. return this._easingMode;
  24453. };
  24454. EasingFunction.prototype.easeInCore = function (gradient) {
  24455. throw new Error('You must implement this method');
  24456. };
  24457. EasingFunction.prototype.ease = function (gradient) {
  24458. switch (this._easingMode) {
  24459. case EasingFunction.EASINGMODE_EASEIN:
  24460. return this.easeInCore(gradient);
  24461. case EasingFunction.EASINGMODE_EASEOUT:
  24462. return (1 - this.easeInCore(1 - gradient));
  24463. }
  24464. if (gradient >= 0.5) {
  24465. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  24466. }
  24467. return (this.easeInCore(gradient * 2) * 0.5);
  24468. };
  24469. //Statics
  24470. EasingFunction._EASINGMODE_EASEIN = 0;
  24471. EasingFunction._EASINGMODE_EASEOUT = 1;
  24472. EasingFunction._EASINGMODE_EASEINOUT = 2;
  24473. return EasingFunction;
  24474. })();
  24475. BABYLON.EasingFunction = EasingFunction;
  24476. var CircleEase = (function (_super) {
  24477. __extends(CircleEase, _super);
  24478. function CircleEase() {
  24479. _super.apply(this, arguments);
  24480. }
  24481. CircleEase.prototype.easeInCore = function (gradient) {
  24482. gradient = Math.max(0, Math.min(1, gradient));
  24483. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  24484. };
  24485. return CircleEase;
  24486. })(EasingFunction);
  24487. BABYLON.CircleEase = CircleEase;
  24488. var BackEase = (function (_super) {
  24489. __extends(BackEase, _super);
  24490. function BackEase(amplitude) {
  24491. if (amplitude === void 0) { amplitude = 1; }
  24492. _super.call(this);
  24493. this.amplitude = amplitude;
  24494. }
  24495. BackEase.prototype.easeInCore = function (gradient) {
  24496. var num = Math.max(0, this.amplitude);
  24497. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  24498. };
  24499. return BackEase;
  24500. })(EasingFunction);
  24501. BABYLON.BackEase = BackEase;
  24502. var BounceEase = (function (_super) {
  24503. __extends(BounceEase, _super);
  24504. function BounceEase(bounces, bounciness) {
  24505. if (bounces === void 0) { bounces = 3; }
  24506. if (bounciness === void 0) { bounciness = 2; }
  24507. _super.call(this);
  24508. this.bounces = bounces;
  24509. this.bounciness = bounciness;
  24510. }
  24511. BounceEase.prototype.easeInCore = function (gradient) {
  24512. var y = Math.max(0.0, this.bounces);
  24513. var bounciness = this.bounciness;
  24514. if (bounciness <= 1.0) {
  24515. bounciness = 1.001;
  24516. }
  24517. var num9 = Math.pow(bounciness, y);
  24518. var num5 = 1.0 - bounciness;
  24519. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  24520. var num15 = gradient * num4;
  24521. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  24522. var num3 = Math.floor(num65);
  24523. var num13 = num3 + 1.0;
  24524. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  24525. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  24526. var num7 = (num8 + num12) * 0.5;
  24527. var num6 = gradient - num7;
  24528. var num2 = num7 - num8;
  24529. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  24530. };
  24531. return BounceEase;
  24532. })(EasingFunction);
  24533. BABYLON.BounceEase = BounceEase;
  24534. var CubicEase = (function (_super) {
  24535. __extends(CubicEase, _super);
  24536. function CubicEase() {
  24537. _super.apply(this, arguments);
  24538. }
  24539. CubicEase.prototype.easeInCore = function (gradient) {
  24540. return (gradient * gradient * gradient);
  24541. };
  24542. return CubicEase;
  24543. })(EasingFunction);
  24544. BABYLON.CubicEase = CubicEase;
  24545. var ElasticEase = (function (_super) {
  24546. __extends(ElasticEase, _super);
  24547. function ElasticEase(oscillations, springiness) {
  24548. if (oscillations === void 0) { oscillations = 3; }
  24549. if (springiness === void 0) { springiness = 3; }
  24550. _super.call(this);
  24551. this.oscillations = oscillations;
  24552. this.springiness = springiness;
  24553. }
  24554. ElasticEase.prototype.easeInCore = function (gradient) {
  24555. var num2;
  24556. var num3 = Math.max(0.0, this.oscillations);
  24557. var num = Math.max(0.0, this.springiness);
  24558. if (num == 0) {
  24559. num2 = gradient;
  24560. }
  24561. else {
  24562. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  24563. }
  24564. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  24565. };
  24566. return ElasticEase;
  24567. })(EasingFunction);
  24568. BABYLON.ElasticEase = ElasticEase;
  24569. var ExponentialEase = (function (_super) {
  24570. __extends(ExponentialEase, _super);
  24571. function ExponentialEase(exponent) {
  24572. if (exponent === void 0) { exponent = 2; }
  24573. _super.call(this);
  24574. this.exponent = exponent;
  24575. }
  24576. ExponentialEase.prototype.easeInCore = function (gradient) {
  24577. if (this.exponent <= 0) {
  24578. return gradient;
  24579. }
  24580. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  24581. };
  24582. return ExponentialEase;
  24583. })(EasingFunction);
  24584. BABYLON.ExponentialEase = ExponentialEase;
  24585. var PowerEase = (function (_super) {
  24586. __extends(PowerEase, _super);
  24587. function PowerEase(power) {
  24588. if (power === void 0) { power = 2; }
  24589. _super.call(this);
  24590. this.power = power;
  24591. }
  24592. PowerEase.prototype.easeInCore = function (gradient) {
  24593. var y = Math.max(0.0, this.power);
  24594. return Math.pow(gradient, y);
  24595. };
  24596. return PowerEase;
  24597. })(EasingFunction);
  24598. BABYLON.PowerEase = PowerEase;
  24599. var QuadraticEase = (function (_super) {
  24600. __extends(QuadraticEase, _super);
  24601. function QuadraticEase() {
  24602. _super.apply(this, arguments);
  24603. }
  24604. QuadraticEase.prototype.easeInCore = function (gradient) {
  24605. return (gradient * gradient);
  24606. };
  24607. return QuadraticEase;
  24608. })(EasingFunction);
  24609. BABYLON.QuadraticEase = QuadraticEase;
  24610. var QuarticEase = (function (_super) {
  24611. __extends(QuarticEase, _super);
  24612. function QuarticEase() {
  24613. _super.apply(this, arguments);
  24614. }
  24615. QuarticEase.prototype.easeInCore = function (gradient) {
  24616. return (gradient * gradient * gradient * gradient);
  24617. };
  24618. return QuarticEase;
  24619. })(EasingFunction);
  24620. BABYLON.QuarticEase = QuarticEase;
  24621. var QuinticEase = (function (_super) {
  24622. __extends(QuinticEase, _super);
  24623. function QuinticEase() {
  24624. _super.apply(this, arguments);
  24625. }
  24626. QuinticEase.prototype.easeInCore = function (gradient) {
  24627. return (gradient * gradient * gradient * gradient * gradient);
  24628. };
  24629. return QuinticEase;
  24630. })(EasingFunction);
  24631. BABYLON.QuinticEase = QuinticEase;
  24632. var SineEase = (function (_super) {
  24633. __extends(SineEase, _super);
  24634. function SineEase() {
  24635. _super.apply(this, arguments);
  24636. }
  24637. SineEase.prototype.easeInCore = function (gradient) {
  24638. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  24639. };
  24640. return SineEase;
  24641. })(EasingFunction);
  24642. BABYLON.SineEase = SineEase;
  24643. var BezierCurveEase = (function (_super) {
  24644. __extends(BezierCurveEase, _super);
  24645. function BezierCurveEase(x1, y1, x2, y2) {
  24646. if (x1 === void 0) { x1 = 0; }
  24647. if (y1 === void 0) { y1 = 0; }
  24648. if (x2 === void 0) { x2 = 1; }
  24649. if (y2 === void 0) { y2 = 1; }
  24650. _super.call(this);
  24651. this.x1 = x1;
  24652. this.y1 = y1;
  24653. this.x2 = x2;
  24654. this.y2 = y2;
  24655. }
  24656. BezierCurveEase.prototype.easeInCore = function (gradient) {
  24657. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  24658. };
  24659. return BezierCurveEase;
  24660. })(EasingFunction);
  24661. BABYLON.BezierCurveEase = BezierCurveEase;
  24662. })(BABYLON || (BABYLON = {}));
  24663. var BABYLON;
  24664. (function (BABYLON) {
  24665. var Bone = (function (_super) {
  24666. __extends(Bone, _super);
  24667. function Bone(name, skeleton, parentBone, matrix, restPose) {
  24668. _super.call(this, name, skeleton.getScene());
  24669. this.name = name;
  24670. this.children = new Array();
  24671. this.animations = new Array();
  24672. this._worldTransform = new BABYLON.Matrix();
  24673. this._absoluteTransform = new BABYLON.Matrix();
  24674. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  24675. this._skeleton = skeleton;
  24676. this._matrix = matrix;
  24677. this._baseMatrix = matrix;
  24678. this._restPose = restPose ? restPose : matrix.clone();
  24679. skeleton.bones.push(this);
  24680. if (parentBone) {
  24681. this._parent = parentBone;
  24682. parentBone.children.push(this);
  24683. }
  24684. else {
  24685. this._parent = null;
  24686. }
  24687. this._updateDifferenceMatrix();
  24688. }
  24689. // Members
  24690. Bone.prototype.getParent = function () {
  24691. return this._parent;
  24692. };
  24693. Bone.prototype.getLocalMatrix = function () {
  24694. return this._matrix;
  24695. };
  24696. Bone.prototype.getBaseMatrix = function () {
  24697. return this._baseMatrix;
  24698. };
  24699. Bone.prototype.getRestPose = function () {
  24700. return this._restPose;
  24701. };
  24702. Bone.prototype.returnToRest = function () {
  24703. this.updateMatrix(this._restPose.clone());
  24704. };
  24705. Bone.prototype.getWorldMatrix = function () {
  24706. return this._worldTransform;
  24707. };
  24708. Bone.prototype.getInvertedAbsoluteTransform = function () {
  24709. return this._invertedAbsoluteTransform;
  24710. };
  24711. Bone.prototype.getAbsoluteTransform = function () {
  24712. return this._absoluteTransform;
  24713. };
  24714. // Methods
  24715. Bone.prototype.updateMatrix = function (matrix) {
  24716. this._baseMatrix = matrix.clone();
  24717. this._matrix = matrix.clone();
  24718. this._skeleton._markAsDirty();
  24719. this._updateDifferenceMatrix();
  24720. };
  24721. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  24722. if (!rootMatrix) {
  24723. rootMatrix = this._baseMatrix;
  24724. }
  24725. if (this._parent) {
  24726. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  24727. }
  24728. else {
  24729. this._absoluteTransform.copyFrom(rootMatrix);
  24730. }
  24731. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  24732. for (var index = 0; index < this.children.length; index++) {
  24733. this.children[index]._updateDifferenceMatrix();
  24734. }
  24735. };
  24736. Bone.prototype.markAsDirty = function () {
  24737. this._currentRenderId++;
  24738. this._skeleton._markAsDirty();
  24739. };
  24740. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  24741. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  24742. // all animation may be coming from a library skeleton, so may need to create animation
  24743. if (this.animations.length === 0) {
  24744. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  24745. this.animations[0].setKeys([]);
  24746. }
  24747. // get animation info / verify there is such a range from the source bone
  24748. var sourceRange = source.animations[0].getRange(rangeName);
  24749. if (!sourceRange) {
  24750. return false;
  24751. }
  24752. var from = sourceRange.from;
  24753. var to = sourceRange.to;
  24754. var sourceKeys = source.animations[0].getKeys();
  24755. // rescaling prep
  24756. var sourceBoneLength = source.length;
  24757. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  24758. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  24759. var destKeys = this.animations[0].getKeys();
  24760. // loop vars declaration / initialization
  24761. var orig;
  24762. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  24763. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  24764. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  24765. var mat;
  24766. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  24767. orig = sourceKeys[key];
  24768. if (orig.frame >= from && orig.frame <= to) {
  24769. if (scalingReqd) {
  24770. orig.value.decompose(origScale, origRotation, origTranslation);
  24771. origTranslation.scaleInPlace(ratio);
  24772. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  24773. }
  24774. else {
  24775. mat = orig.value;
  24776. }
  24777. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  24778. }
  24779. }
  24780. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  24781. return true;
  24782. };
  24783. return Bone;
  24784. })(BABYLON.Node);
  24785. BABYLON.Bone = Bone;
  24786. })(BABYLON || (BABYLON = {}));
  24787. var BABYLON;
  24788. (function (BABYLON) {
  24789. var Skeleton = (function () {
  24790. function Skeleton(name, id, scene) {
  24791. this.name = name;
  24792. this.id = id;
  24793. this.bones = new Array();
  24794. this.needInitialSkinMatrix = false;
  24795. this._isDirty = true;
  24796. this._meshesWithPoseMatrix = new Array();
  24797. this._identity = BABYLON.Matrix.Identity();
  24798. this._ranges = {};
  24799. this.bones = [];
  24800. this._scene = scene;
  24801. scene.skeletons.push(this);
  24802. //make sure it will recalculate the matrix next time prepare is called.
  24803. this._isDirty = true;
  24804. }
  24805. // Members
  24806. Skeleton.prototype.getTransformMatrices = function (mesh) {
  24807. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  24808. return mesh._bonesTransformMatrices;
  24809. }
  24810. return this._transformMatrices;
  24811. };
  24812. Skeleton.prototype.getScene = function () {
  24813. return this._scene;
  24814. };
  24815. // Methods
  24816. /**
  24817. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24818. */
  24819. Skeleton.prototype.toString = function (fullDetails) {
  24820. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  24821. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  24822. if (fullDetails) {
  24823. ret += ", Ranges: {";
  24824. var first = true;
  24825. for (var name in this._ranges) {
  24826. if (!first) {
  24827. ret + ", ";
  24828. first = false;
  24829. }
  24830. ret += name;
  24831. }
  24832. ret += "}";
  24833. }
  24834. return ret;
  24835. };
  24836. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  24837. // check name not already in use
  24838. if (!this._ranges[name]) {
  24839. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  24840. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24841. if (this.bones[i].animations[0]) {
  24842. this.bones[i].animations[0].createRange(name, from, to);
  24843. }
  24844. }
  24845. }
  24846. };
  24847. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  24848. if (deleteFrames === void 0) { deleteFrames = true; }
  24849. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24850. if (this.bones[i].animations[0]) {
  24851. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  24852. }
  24853. }
  24854. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  24855. };
  24856. Skeleton.prototype.getAnimationRange = function (name) {
  24857. return this._ranges[name];
  24858. };
  24859. /**
  24860. * Returns as an Array, all AnimationRanges defined on this skeleton
  24861. */
  24862. Skeleton.prototype.getAnimationRanges = function () {
  24863. var animationRanges = [];
  24864. var name;
  24865. var i = 0;
  24866. for (name in this._ranges) {
  24867. animationRanges[i] = this._ranges[name];
  24868. i++;
  24869. }
  24870. return animationRanges;
  24871. };
  24872. /**
  24873. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  24874. */
  24875. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  24876. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  24877. if (this._ranges[name] || !source.getAnimationRange(name)) {
  24878. return false;
  24879. }
  24880. var ret = true;
  24881. var frameOffset = this._getHighestAnimationFrame() + 1;
  24882. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  24883. var boneDict = {};
  24884. var sourceBones = source.bones;
  24885. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  24886. boneDict[sourceBones[i].name] = sourceBones[i];
  24887. }
  24888. if (this.bones.length !== sourceBones.length) {
  24889. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  24890. ret = false;
  24891. }
  24892. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24893. var boneName = this.bones[i].name;
  24894. var sourceBone = boneDict[boneName];
  24895. if (sourceBone) {
  24896. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  24897. }
  24898. else {
  24899. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  24900. ret = false;
  24901. }
  24902. }
  24903. // do not call createAnimationRange(), since it also is done to bones, which was already done
  24904. var range = source.getAnimationRange(name);
  24905. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  24906. return ret;
  24907. };
  24908. Skeleton.prototype.returnToRest = function () {
  24909. for (var index = 0; index < this.bones.length; index++) {
  24910. this.bones[index].returnToRest();
  24911. }
  24912. };
  24913. Skeleton.prototype._getHighestAnimationFrame = function () {
  24914. var ret = 0;
  24915. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24916. if (this.bones[i].animations[0]) {
  24917. var highest = this.bones[i].animations[0].getHighestFrame();
  24918. if (ret < highest) {
  24919. ret = highest;
  24920. }
  24921. }
  24922. }
  24923. return ret;
  24924. };
  24925. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  24926. var range = this.getAnimationRange(name);
  24927. if (!range) {
  24928. return null;
  24929. }
  24930. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  24931. };
  24932. Skeleton.prototype._markAsDirty = function () {
  24933. this._isDirty = true;
  24934. };
  24935. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  24936. this._meshesWithPoseMatrix.push(mesh);
  24937. };
  24938. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  24939. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  24940. if (index > -1) {
  24941. this._meshesWithPoseMatrix.splice(index, 1);
  24942. }
  24943. };
  24944. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  24945. for (var index = 0; index < this.bones.length; index++) {
  24946. var bone = this.bones[index];
  24947. var parentBone = bone.getParent();
  24948. if (parentBone) {
  24949. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  24950. }
  24951. else {
  24952. if (initialSkinMatrix) {
  24953. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  24954. }
  24955. else {
  24956. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  24957. }
  24958. }
  24959. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  24960. }
  24961. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  24962. };
  24963. Skeleton.prototype.prepare = function () {
  24964. if (!this._isDirty) {
  24965. return;
  24966. }
  24967. if (this.needInitialSkinMatrix) {
  24968. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  24969. var mesh = this._meshesWithPoseMatrix[index];
  24970. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  24971. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  24972. }
  24973. var poseMatrix = mesh.getPoseMatrix();
  24974. // Prepare bones
  24975. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  24976. var bone = this.bones[boneIndex];
  24977. if (!bone.getParent()) {
  24978. var matrix = bone.getBaseMatrix();
  24979. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  24980. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  24981. }
  24982. }
  24983. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  24984. }
  24985. }
  24986. else {
  24987. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  24988. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  24989. }
  24990. this._computeTransformMatrices(this._transformMatrices, null);
  24991. }
  24992. this._isDirty = false;
  24993. this._scene._activeBones += this.bones.length;
  24994. };
  24995. Skeleton.prototype.getAnimatables = function () {
  24996. if (!this._animatables || this._animatables.length !== this.bones.length) {
  24997. this._animatables = [];
  24998. for (var index = 0; index < this.bones.length; index++) {
  24999. this._animatables.push(this.bones[index]);
  25000. }
  25001. }
  25002. return this._animatables;
  25003. };
  25004. Skeleton.prototype.clone = function (name, id) {
  25005. var result = new Skeleton(name, id || name, this._scene);
  25006. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25007. for (var index = 0; index < this.bones.length; index++) {
  25008. var source = this.bones[index];
  25009. var parentBone = null;
  25010. if (source.getParent()) {
  25011. var parentIndex = this.bones.indexOf(source.getParent());
  25012. parentBone = result.bones[parentIndex];
  25013. }
  25014. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  25015. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  25016. }
  25017. if (this._ranges) {
  25018. result._ranges = {};
  25019. for (var rangeName in this._ranges) {
  25020. result._ranges[rangeName] = this._ranges[rangeName].clone();
  25021. }
  25022. }
  25023. this._isDirty = true;
  25024. return result;
  25025. };
  25026. Skeleton.prototype.dispose = function () {
  25027. this._meshesWithPoseMatrix = [];
  25028. // Animations
  25029. this.getScene().stopAnimation(this);
  25030. // Remove from scene
  25031. this.getScene().removeSkeleton(this);
  25032. };
  25033. Skeleton.prototype.serialize = function () {
  25034. var serializationObject = {};
  25035. serializationObject.name = this.name;
  25036. serializationObject.id = this.id;
  25037. serializationObject.bones = [];
  25038. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25039. for (var index = 0; index < this.bones.length; index++) {
  25040. var bone = this.bones[index];
  25041. var serializedBone = {
  25042. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  25043. name: bone.name,
  25044. matrix: bone.getLocalMatrix().toArray(),
  25045. rest: bone.getRestPose().toArray()
  25046. };
  25047. serializationObject.bones.push(serializedBone);
  25048. if (bone.length) {
  25049. serializedBone.length = bone.length;
  25050. }
  25051. if (bone.animations && bone.animations.length > 0) {
  25052. serializedBone.animation = bone.animations[0].serialize();
  25053. }
  25054. serializationObject.ranges = [];
  25055. for (var name in this._ranges) {
  25056. var range = {};
  25057. range.name = name;
  25058. range.from = this._ranges[name].from;
  25059. range.to = this._ranges[name].to;
  25060. serializationObject.ranges.push(range);
  25061. }
  25062. }
  25063. return serializationObject;
  25064. };
  25065. Skeleton.Parse = function (parsedSkeleton, scene) {
  25066. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  25067. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  25068. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  25069. var parsedBone = parsedSkeleton.bones[index];
  25070. var parentBone = null;
  25071. if (parsedBone.parentBoneIndex > -1) {
  25072. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  25073. }
  25074. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  25075. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  25076. if (parsedBone.length) {
  25077. bone.length = parsedBone.length;
  25078. }
  25079. if (parsedBone.animation) {
  25080. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  25081. }
  25082. }
  25083. // placed after bones, so createAnimationRange can cascade down
  25084. if (parsedSkeleton.ranges) {
  25085. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  25086. var data = parsedSkeleton.ranges[index];
  25087. skeleton.createAnimationRange(data.name, data.from, data.to);
  25088. }
  25089. }
  25090. return skeleton;
  25091. };
  25092. return Skeleton;
  25093. })();
  25094. BABYLON.Skeleton = Skeleton;
  25095. })(BABYLON || (BABYLON = {}));
  25096. var BABYLON;
  25097. (function (BABYLON) {
  25098. var PostProcess = (function () {
  25099. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  25100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  25101. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25102. this.name = name;
  25103. this.width = -1;
  25104. this.height = -1;
  25105. this._reusable = false;
  25106. this._textures = new BABYLON.SmartArray(2);
  25107. this._currentRenderTextureInd = 0;
  25108. if (camera != null) {
  25109. this._camera = camera;
  25110. this._scene = camera.getScene();
  25111. camera.attachPostProcess(this);
  25112. this._engine = this._scene.getEngine();
  25113. }
  25114. else {
  25115. this._engine = engine;
  25116. }
  25117. this._renderRatio = ratio;
  25118. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  25119. this._reusable = reusable || false;
  25120. this._textureType = textureType;
  25121. this._samplers = samplers || [];
  25122. this._samplers.push("textureSampler");
  25123. this._fragmentUrl = fragmentUrl;
  25124. this._parameters = parameters || [];
  25125. this.updateEffect(defines);
  25126. }
  25127. PostProcess.prototype.updateEffect = function (defines) {
  25128. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  25129. };
  25130. PostProcess.prototype.isReusable = function () {
  25131. return this._reusable;
  25132. };
  25133. PostProcess.prototype.activate = function (camera, sourceTexture) {
  25134. camera = camera || this._camera;
  25135. var scene = camera.getScene();
  25136. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  25137. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  25138. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  25139. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  25140. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  25141. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  25142. if (this._textures.length > 0) {
  25143. for (var i = 0; i < this._textures.length; i++) {
  25144. this._engine._releaseTexture(this._textures.data[i]);
  25145. }
  25146. this._textures.reset();
  25147. }
  25148. this.width = desiredWidth;
  25149. this.height = desiredHeight;
  25150. 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 }));
  25151. if (this._reusable) {
  25152. 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 }));
  25153. }
  25154. if (this.onSizeChanged) {
  25155. this.onSizeChanged();
  25156. }
  25157. }
  25158. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  25159. if (this.onActivate) {
  25160. this.onActivate(camera);
  25161. }
  25162. // Clear
  25163. if (this.clearColor) {
  25164. this._engine.clear(this.clearColor, true, true);
  25165. }
  25166. else {
  25167. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  25168. }
  25169. if (this._reusable) {
  25170. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  25171. }
  25172. };
  25173. Object.defineProperty(PostProcess.prototype, "isSupported", {
  25174. get: function () {
  25175. return this._effect.isSupported;
  25176. },
  25177. enumerable: true,
  25178. configurable: true
  25179. });
  25180. PostProcess.prototype.apply = function () {
  25181. // Check
  25182. if (!this._effect.isReady())
  25183. return null;
  25184. // States
  25185. this._engine.enableEffect(this._effect);
  25186. this._engine.setState(false);
  25187. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25188. this._engine.setDepthBuffer(false);
  25189. this._engine.setDepthWrite(false);
  25190. // Texture
  25191. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  25192. // Parameters
  25193. if (this.onApply) {
  25194. this.onApply(this._effect);
  25195. }
  25196. return this._effect;
  25197. };
  25198. PostProcess.prototype.dispose = function (camera) {
  25199. camera = camera || this._camera;
  25200. if (this._textures.length > 0) {
  25201. for (var i = 0; i < this._textures.length; i++) {
  25202. this._engine._releaseTexture(this._textures.data[i]);
  25203. }
  25204. this._textures.reset();
  25205. }
  25206. if (!camera) {
  25207. return;
  25208. }
  25209. camera.detachPostProcess(this);
  25210. var index = camera._postProcesses.indexOf(this);
  25211. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  25212. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  25213. }
  25214. };
  25215. return PostProcess;
  25216. })();
  25217. BABYLON.PostProcess = PostProcess;
  25218. })(BABYLON || (BABYLON = {}));
  25219. var BABYLON;
  25220. (function (BABYLON) {
  25221. var PostProcessManager = (function () {
  25222. function PostProcessManager(scene) {
  25223. this._vertexDeclaration = [2];
  25224. this._vertexStrideSize = 2 * 4;
  25225. this._scene = scene;
  25226. }
  25227. PostProcessManager.prototype._prepareBuffers = function () {
  25228. if (this._vertexBuffer) {
  25229. return;
  25230. }
  25231. // VBO
  25232. var vertices = [];
  25233. vertices.push(1, 1);
  25234. vertices.push(-1, 1);
  25235. vertices.push(-1, -1);
  25236. vertices.push(1, -1);
  25237. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  25238. // Indices
  25239. var indices = [];
  25240. indices.push(0);
  25241. indices.push(1);
  25242. indices.push(2);
  25243. indices.push(0);
  25244. indices.push(2);
  25245. indices.push(3);
  25246. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  25247. };
  25248. // Methods
  25249. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  25250. var postProcesses = this._scene.activeCamera._postProcesses;
  25251. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  25252. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  25253. return false;
  25254. }
  25255. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  25256. return true;
  25257. };
  25258. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  25259. var engine = this._scene.getEngine();
  25260. for (var index = 0; index < postProcesses.length; index++) {
  25261. if (index < postProcesses.length - 1) {
  25262. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  25263. }
  25264. else {
  25265. if (targetTexture) {
  25266. engine.bindFramebuffer(targetTexture);
  25267. }
  25268. else {
  25269. engine.restoreDefaultFramebuffer();
  25270. }
  25271. }
  25272. var pp = postProcesses[index];
  25273. var effect = pp.apply();
  25274. if (effect) {
  25275. if (pp.onBeforeRender) {
  25276. pp.onBeforeRender(effect);
  25277. }
  25278. // VBOs
  25279. this._prepareBuffers();
  25280. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25281. // Draw order
  25282. engine.draw(true, 0, 6);
  25283. if (pp.onAfterRender) {
  25284. pp.onAfterRender(effect);
  25285. }
  25286. }
  25287. }
  25288. // Restore depth buffer
  25289. engine.setDepthBuffer(true);
  25290. engine.setDepthWrite(true);
  25291. };
  25292. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  25293. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  25294. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  25295. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  25296. return;
  25297. }
  25298. var engine = this._scene.getEngine();
  25299. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  25300. if (index < postProcessesTakenIndices.length - 1) {
  25301. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  25302. }
  25303. else {
  25304. if (targetTexture) {
  25305. engine.bindFramebuffer(targetTexture, faceIndex);
  25306. }
  25307. else {
  25308. engine.restoreDefaultFramebuffer();
  25309. }
  25310. }
  25311. if (doNotPresent) {
  25312. break;
  25313. }
  25314. var pp = postProcesses[postProcessesTakenIndices[index]];
  25315. var effect = pp.apply();
  25316. if (effect) {
  25317. if (pp.onBeforeRender) {
  25318. pp.onBeforeRender(effect);
  25319. }
  25320. // VBOs
  25321. this._prepareBuffers();
  25322. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25323. // Draw order
  25324. engine.draw(true, 0, 6);
  25325. if (pp.onAfterRender) {
  25326. pp.onAfterRender(effect);
  25327. }
  25328. }
  25329. }
  25330. // Restore depth buffer
  25331. engine.setDepthBuffer(true);
  25332. engine.setDepthWrite(true);
  25333. };
  25334. PostProcessManager.prototype.dispose = function () {
  25335. if (this._vertexBuffer) {
  25336. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25337. this._vertexBuffer = null;
  25338. }
  25339. if (this._indexBuffer) {
  25340. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25341. this._indexBuffer = null;
  25342. }
  25343. };
  25344. return PostProcessManager;
  25345. })();
  25346. BABYLON.PostProcessManager = PostProcessManager;
  25347. })(BABYLON || (BABYLON = {}));
  25348. var BABYLON;
  25349. (function (BABYLON) {
  25350. var PassPostProcess = (function (_super) {
  25351. __extends(PassPostProcess, _super);
  25352. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25353. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  25354. }
  25355. return PassPostProcess;
  25356. })(BABYLON.PostProcess);
  25357. BABYLON.PassPostProcess = PassPostProcess;
  25358. })(BABYLON || (BABYLON = {}));
  25359. var BABYLON;
  25360. (function (BABYLON) {
  25361. var PhysicsJoint = (function () {
  25362. function PhysicsJoint(type, jointData) {
  25363. this.type = type;
  25364. this.jointData = jointData;
  25365. jointData.nativeParams = jointData.nativeParams || {};
  25366. }
  25367. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  25368. get: function () {
  25369. return this._physicsJoint;
  25370. },
  25371. set: function (newJoint) {
  25372. if (this._physicsJoint) {
  25373. }
  25374. this._physicsJoint = newJoint;
  25375. },
  25376. enumerable: true,
  25377. configurable: true
  25378. });
  25379. //TODO check if the native joints are the same
  25380. //Joint Types
  25381. PhysicsJoint.DistanceJoint = 0;
  25382. PhysicsJoint.HingeJoint = 1;
  25383. PhysicsJoint.BallAndSocketJoint = 2;
  25384. PhysicsJoint.WheelJoint = 3;
  25385. PhysicsJoint.SliderJoint = 4;
  25386. //OIMO
  25387. PhysicsJoint.PrismaticJoint = 5;
  25388. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  25389. PhysicsJoint.UniversalJoint = 6;
  25390. PhysicsJoint.Hinge2Joint = 7;
  25391. //Cannon
  25392. //Similar to a Ball-Joint. Different in params
  25393. //TODO check!!
  25394. PhysicsJoint.PointToPointJoint = 8;
  25395. //Cannon only at the moment
  25396. PhysicsJoint.SpringJoint = 9;
  25397. return PhysicsJoint;
  25398. })();
  25399. BABYLON.PhysicsJoint = PhysicsJoint;
  25400. })(BABYLON || (BABYLON = {}));
  25401. var BABYLON;
  25402. (function (BABYLON) {
  25403. var PhysicsImpostor = (function () {
  25404. function PhysicsImpostor(_mesh, type, _options) {
  25405. var _this = this;
  25406. if (_options === void 0) { _options = { mass: 0 }; }
  25407. this._mesh = _mesh;
  25408. this.type = type;
  25409. this._options = _options;
  25410. this._bodyUpdateRequired = false;
  25411. this._onBeforePhysicsStepCallbacks = new Array();
  25412. this._onAfterPhysicsStepCallbacks = new Array();
  25413. this._onPhysicsCollideCallbacks = [];
  25414. this._deltaPosition = BABYLON.Vector3.Zero();
  25415. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  25416. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  25417. /**
  25418. * this function is executed by the physics engine.
  25419. */
  25420. this.beforeStep = function () {
  25421. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  25422. //conjugate deltaRotation
  25423. if (_this._deltaRotationConjugated) {
  25424. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  25425. }
  25426. else {
  25427. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  25428. }
  25429. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  25430. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  25431. func(_this);
  25432. });
  25433. };
  25434. /**
  25435. * this function is executed by the physics engine.
  25436. */
  25437. this.afterStep = function () {
  25438. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  25439. func(_this);
  25440. });
  25441. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  25442. _this.mesh.position.addInPlace(_this._deltaPosition);
  25443. if (_this._deltaRotation) {
  25444. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  25445. }
  25446. };
  25447. //event and body object due to cannon's event-based architecture.
  25448. this.onCollide = function (e) {
  25449. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  25450. if (otherImpostor) {
  25451. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  25452. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  25453. }).forEach(function (obj) {
  25454. obj.callback(_this, otherImpostor);
  25455. });
  25456. }
  25457. };
  25458. //default options params
  25459. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  25460. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  25461. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  25462. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  25463. this._joints = [];
  25464. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  25465. if (!this._mesh.parent) {
  25466. this._init();
  25467. }
  25468. }
  25469. /**
  25470. * This function will completly initialize this impostor.
  25471. * It will create a new body - but only if this mesh has no parent.
  25472. * If it has, this impostor will not be used other than to define the impostor
  25473. * of the child mesh.
  25474. */
  25475. PhysicsImpostor.prototype._init = function () {
  25476. this._physicsEngine.removeImpostor(this);
  25477. this.physicsBody = null;
  25478. this._parent = this._parent || this._getPhysicsParent();
  25479. if (!this.parent) {
  25480. this._physicsEngine.addImpostor(this);
  25481. }
  25482. };
  25483. PhysicsImpostor.prototype._getPhysicsParent = function () {
  25484. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  25485. var parentMesh = this.mesh.parent;
  25486. return parentMesh.getPhysicsImpostor();
  25487. }
  25488. return;
  25489. };
  25490. /**
  25491. * Should a new body be generated.
  25492. */
  25493. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  25494. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  25495. };
  25496. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  25497. this.forceUpdate();
  25498. };
  25499. /**
  25500. * Force a regeneration of this or the parent's impostor's body.
  25501. * Use under cautious - This will remove all joints already implemented.
  25502. */
  25503. PhysicsImpostor.prototype.forceUpdate = function () {
  25504. this._init();
  25505. if (this.parent) {
  25506. this.parent.forceUpdate();
  25507. }
  25508. };
  25509. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  25510. get: function () {
  25511. return this._mesh;
  25512. },
  25513. enumerable: true,
  25514. configurable: true
  25515. });
  25516. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  25517. /**
  25518. * Gets the body that holds this impostor. Either its own, or its parent.
  25519. */
  25520. get: function () {
  25521. return this._parent ? this._parent.physicsBody : this._physicsBody;
  25522. },
  25523. /**
  25524. * Set the physics body. Used mainly by the physics engine/plugin
  25525. */
  25526. set: function (physicsBody) {
  25527. if (this._physicsBody) {
  25528. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  25529. }
  25530. this._physicsBody = physicsBody;
  25531. this.resetUpdateFlags();
  25532. },
  25533. enumerable: true,
  25534. configurable: true
  25535. });
  25536. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  25537. get: function () {
  25538. return this._parent;
  25539. },
  25540. enumerable: true,
  25541. configurable: true
  25542. });
  25543. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  25544. this._bodyUpdateRequired = false;
  25545. };
  25546. /**
  25547. * Get a specific parametes from the options parameter.
  25548. */
  25549. PhysicsImpostor.prototype.getParam = function (paramName) {
  25550. return this._options[paramName];
  25551. };
  25552. /**
  25553. * Sets a specific parameter in the options given to the physics plugin
  25554. */
  25555. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  25556. this._options[paramName] = value;
  25557. this._bodyUpdateRequired = true;
  25558. };
  25559. /**
  25560. * Specifically change the body's mass option. Won't recreate the physics body object
  25561. */
  25562. PhysicsImpostor.prototype.setMass = function (mass) {
  25563. if (this.getParam("mass") !== mass) {
  25564. this.setParam("mass", mass);
  25565. }
  25566. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  25567. };
  25568. /**
  25569. * Set the body's linear velocity.
  25570. */
  25571. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  25572. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  25573. };
  25574. /**
  25575. * Set the body's linear velocity.
  25576. */
  25577. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  25578. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  25579. };
  25580. /**
  25581. * Execute a function with the physics plugin native code.
  25582. * Provide a function the will have two variables - the world object and the physics body object.
  25583. */
  25584. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  25585. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  25586. };
  25587. /**
  25588. * Register a function that will be executed before the physics world is stepping forward.
  25589. */
  25590. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  25591. this._onBeforePhysicsStepCallbacks.push(func);
  25592. };
  25593. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  25594. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  25595. if (index > -1) {
  25596. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  25597. }
  25598. else {
  25599. BABYLON.Tools.Warn("Function to remove was not found");
  25600. }
  25601. };
  25602. /**
  25603. * Register a function that will be executed after the physics step
  25604. */
  25605. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  25606. this._onAfterPhysicsStepCallbacks.push(func);
  25607. };
  25608. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  25609. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  25610. if (index > -1) {
  25611. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  25612. }
  25613. else {
  25614. BABYLON.Tools.Warn("Function to remove was not found");
  25615. }
  25616. };
  25617. /**
  25618. * register a function that will be executed when this impostor collides against a different body.
  25619. */
  25620. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  25621. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  25622. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  25623. };
  25624. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  25625. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  25626. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  25627. if (index > -1) {
  25628. this._onPhysicsCollideCallbacks.splice(index, 1);
  25629. }
  25630. else {
  25631. BABYLON.Tools.Warn("Function to remove was not found");
  25632. }
  25633. };
  25634. /**
  25635. * Apply a force
  25636. */
  25637. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  25638. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  25639. };
  25640. /**
  25641. * Apply an impulse
  25642. */
  25643. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  25644. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  25645. };
  25646. /**
  25647. * A help function to create a joint.
  25648. */
  25649. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  25650. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  25651. this.addJoint(otherImpostor, joint);
  25652. };
  25653. /**
  25654. * Add a joint to this impostor with a different impostor.
  25655. */
  25656. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  25657. this._joints.push({
  25658. otherImpostor: otherImpostor,
  25659. joint: joint
  25660. });
  25661. this._physicsEngine.addJoint(this, otherImpostor, joint);
  25662. };
  25663. /**
  25664. * Will keep this body still, in a sleep mode.
  25665. */
  25666. PhysicsImpostor.prototype.sleep = function () {
  25667. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  25668. };
  25669. /**
  25670. * Wake the body up.
  25671. */
  25672. PhysicsImpostor.prototype.wakeUp = function () {
  25673. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  25674. };
  25675. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  25676. if (disposeChildren === void 0) { disposeChildren = true; }
  25677. this.physicsBody = null;
  25678. if (this.parent) {
  25679. this.parent.forceUpdate();
  25680. }
  25681. else {
  25682. this.mesh.getChildMeshes().forEach(function (mesh) {
  25683. if (mesh.physicsImpostor) {
  25684. if (disposeChildren) {
  25685. mesh.physicsImpostor.dispose();
  25686. mesh.physicsImpostor = null;
  25687. }
  25688. }
  25689. });
  25690. }
  25691. };
  25692. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  25693. this._deltaPosition.copyFrom(position);
  25694. };
  25695. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  25696. if (!this._deltaRotation) {
  25697. this._deltaRotation = new BABYLON.Quaternion();
  25698. }
  25699. this._deltaRotation.copyFrom(rotation);
  25700. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  25701. };
  25702. //Impostor types
  25703. PhysicsImpostor.NoImpostor = 0;
  25704. PhysicsImpostor.SphereImpostor = 1;
  25705. PhysicsImpostor.BoxImpostor = 2;
  25706. PhysicsImpostor.PlaneImpostor = 3;
  25707. PhysicsImpostor.MeshImpostor = 4;
  25708. PhysicsImpostor.CapsuleImpostor = 5;
  25709. PhysicsImpostor.ConeImpostor = 6;
  25710. PhysicsImpostor.CylinderImpostor = 7;
  25711. PhysicsImpostor.ConvexHullImpostor = 8;
  25712. PhysicsImpostor.HeightmapImpostor = 9;
  25713. return PhysicsImpostor;
  25714. })();
  25715. BABYLON.PhysicsImpostor = PhysicsImpostor;
  25716. })(BABYLON || (BABYLON = {}));
  25717. var BABYLON;
  25718. (function (BABYLON) {
  25719. var PhysicsEngine = (function () {
  25720. function PhysicsEngine(gravity, _physicsPlugin) {
  25721. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  25722. this._physicsPlugin = _physicsPlugin;
  25723. //new methods and parameters
  25724. this._impostors = [];
  25725. this._joints = [];
  25726. if (!this._physicsPlugin.isSupported()) {
  25727. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  25728. + "Please make sure it is included.");
  25729. }
  25730. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  25731. this.setGravity(gravity);
  25732. this.setTimeStep();
  25733. }
  25734. PhysicsEngine.prototype.setGravity = function (gravity) {
  25735. this.gravity = gravity;
  25736. this._physicsPlugin.setGravity(this.gravity);
  25737. };
  25738. /**
  25739. * Set the time step of the physics engine.
  25740. * default is 1/60.
  25741. * To slow it down, enter 1/600 for example.
  25742. * To speed it up, 1/30
  25743. */
  25744. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  25745. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  25746. this._physicsPlugin.setTimeStep(newTimeStep);
  25747. };
  25748. PhysicsEngine.prototype.dispose = function () {
  25749. this._impostors.forEach(function (impostor) {
  25750. impostor.dispose();
  25751. });
  25752. this._physicsPlugin.dispose();
  25753. };
  25754. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  25755. return this._physicsPlugin.name;
  25756. };
  25757. PhysicsEngine.prototype.addImpostor = function (impostor) {
  25758. this._impostors.push(impostor);
  25759. //if no parent, generate the body
  25760. if (!impostor.parent) {
  25761. this._physicsPlugin.generatePhysicsBody(impostor);
  25762. }
  25763. };
  25764. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  25765. var index = this._impostors.indexOf(impostor);
  25766. if (index > -1) {
  25767. var removed = this._impostors.splice(index, 1);
  25768. //Is it needed?
  25769. if (removed.length) {
  25770. //this will also remove it from the world.
  25771. removed[0].physicsBody = null;
  25772. }
  25773. }
  25774. };
  25775. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  25776. var impostorJoint = {
  25777. mainImpostor: mainImpostor,
  25778. connectedImpostor: connectedImpostor,
  25779. joint: joint
  25780. };
  25781. this._joints.push(impostorJoint);
  25782. this._physicsPlugin.generateJoint(impostorJoint);
  25783. };
  25784. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  25785. var matchingJoints = this._joints.filter(function (impostorJoint) {
  25786. return (impostorJoint.connectedImpostor === connectedImpostor
  25787. && impostorJoint.joint === joint
  25788. && impostorJoint.mainImpostor === mainImpostor);
  25789. });
  25790. if (matchingJoints.length) {
  25791. this._physicsPlugin.removeJoint(matchingJoints[0]);
  25792. }
  25793. };
  25794. /**
  25795. * Called by the scene. no need to call it.
  25796. */
  25797. PhysicsEngine.prototype._step = function (delta) {
  25798. var _this = this;
  25799. //check if any mesh has no body / requires an update
  25800. this._impostors.forEach(function (impostor) {
  25801. if (impostor.isBodyInitRequired()) {
  25802. _this._physicsPlugin.generatePhysicsBody(impostor);
  25803. }
  25804. });
  25805. if (delta > 0.1) {
  25806. delta = 0.1;
  25807. }
  25808. else if (delta <= 0) {
  25809. delta = 1.0 / 60.0;
  25810. }
  25811. this._physicsPlugin.executeStep(delta, this._impostors);
  25812. };
  25813. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  25814. return this._physicsPlugin;
  25815. };
  25816. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  25817. for (var i = 0; i < this._impostors.length; ++i) {
  25818. if (this._impostors[i].physicsBody === body) {
  25819. return this._impostors[i];
  25820. }
  25821. }
  25822. };
  25823. // Statics, Legacy support.
  25824. /**
  25825. * @Deprecated
  25826. *
  25827. */
  25828. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  25829. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  25830. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  25831. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  25832. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  25833. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  25834. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  25835. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  25836. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  25837. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  25838. PhysicsEngine.Epsilon = 0.001;
  25839. return PhysicsEngine;
  25840. })();
  25841. BABYLON.PhysicsEngine = PhysicsEngine;
  25842. })(BABYLON || (BABYLON = {}));
  25843. var BABYLON;
  25844. (function (BABYLON) {
  25845. var VertexData = (function () {
  25846. function VertexData() {
  25847. }
  25848. VertexData.prototype.set = function (data, kind) {
  25849. switch (kind) {
  25850. case BABYLON.VertexBuffer.PositionKind:
  25851. this.positions = data;
  25852. break;
  25853. case BABYLON.VertexBuffer.NormalKind:
  25854. this.normals = data;
  25855. break;
  25856. case BABYLON.VertexBuffer.UVKind:
  25857. this.uvs = data;
  25858. break;
  25859. case BABYLON.VertexBuffer.UV2Kind:
  25860. this.uvs2 = data;
  25861. break;
  25862. case BABYLON.VertexBuffer.UV3Kind:
  25863. this.uvs3 = data;
  25864. break;
  25865. case BABYLON.VertexBuffer.UV4Kind:
  25866. this.uvs4 = data;
  25867. break;
  25868. case BABYLON.VertexBuffer.UV5Kind:
  25869. this.uvs5 = data;
  25870. break;
  25871. case BABYLON.VertexBuffer.UV6Kind:
  25872. this.uvs6 = data;
  25873. break;
  25874. case BABYLON.VertexBuffer.ColorKind:
  25875. this.colors = data;
  25876. break;
  25877. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25878. this.matricesIndices = data;
  25879. break;
  25880. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25881. this.matricesWeights = data;
  25882. break;
  25883. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25884. this.matricesIndicesExtra = data;
  25885. break;
  25886. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25887. this.matricesWeightsExtra = data;
  25888. break;
  25889. }
  25890. };
  25891. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25892. this._applyTo(mesh, updatable);
  25893. };
  25894. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25895. this._applyTo(geometry, updatable);
  25896. };
  25897. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25898. this._update(mesh);
  25899. };
  25900. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25901. this._update(geometry);
  25902. };
  25903. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25904. if (this.positions) {
  25905. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25906. }
  25907. if (this.normals) {
  25908. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25909. }
  25910. if (this.uvs) {
  25911. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25912. }
  25913. if (this.uvs2) {
  25914. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25915. }
  25916. if (this.uvs3) {
  25917. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25918. }
  25919. if (this.uvs4) {
  25920. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25921. }
  25922. if (this.uvs5) {
  25923. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25924. }
  25925. if (this.uvs6) {
  25926. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25927. }
  25928. if (this.colors) {
  25929. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25930. }
  25931. if (this.matricesIndices) {
  25932. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25933. }
  25934. if (this.matricesWeights) {
  25935. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25936. }
  25937. if (this.matricesIndicesExtra) {
  25938. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25939. }
  25940. if (this.matricesWeightsExtra) {
  25941. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25942. }
  25943. if (this.indices) {
  25944. meshOrGeometry.setIndices(this.indices);
  25945. }
  25946. };
  25947. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25948. if (this.positions) {
  25949. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25950. }
  25951. if (this.normals) {
  25952. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25953. }
  25954. if (this.uvs) {
  25955. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25956. }
  25957. if (this.uvs2) {
  25958. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25959. }
  25960. if (this.uvs3) {
  25961. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25962. }
  25963. if (this.uvs4) {
  25964. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25965. }
  25966. if (this.uvs5) {
  25967. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25968. }
  25969. if (this.uvs6) {
  25970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25971. }
  25972. if (this.colors) {
  25973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25974. }
  25975. if (this.matricesIndices) {
  25976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25977. }
  25978. if (this.matricesWeights) {
  25979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25980. }
  25981. if (this.matricesIndicesExtra) {
  25982. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25983. }
  25984. if (this.matricesWeightsExtra) {
  25985. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25986. }
  25987. if (this.indices) {
  25988. meshOrGeometry.setIndices(this.indices);
  25989. }
  25990. };
  25991. VertexData.prototype.transform = function (matrix) {
  25992. var transformed = BABYLON.Vector3.Zero();
  25993. var index;
  25994. if (this.positions) {
  25995. var position = BABYLON.Vector3.Zero();
  25996. for (index = 0; index < this.positions.length; index += 3) {
  25997. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25998. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25999. this.positions[index] = transformed.x;
  26000. this.positions[index + 1] = transformed.y;
  26001. this.positions[index + 2] = transformed.z;
  26002. }
  26003. }
  26004. if (this.normals) {
  26005. var normal = BABYLON.Vector3.Zero();
  26006. for (index = 0; index < this.normals.length; index += 3) {
  26007. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26008. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26009. this.normals[index] = transformed.x;
  26010. this.normals[index + 1] = transformed.y;
  26011. this.normals[index + 2] = transformed.z;
  26012. }
  26013. }
  26014. };
  26015. VertexData.prototype.merge = function (other) {
  26016. if (other.indices) {
  26017. if (!this.indices) {
  26018. this.indices = [];
  26019. }
  26020. var offset = this.positions ? this.positions.length / 3 : 0;
  26021. for (var index = 0; index < other.indices.length; index++) {
  26022. //TODO check type - if Int32Array!
  26023. this.indices.push(other.indices[index] + offset);
  26024. }
  26025. }
  26026. this.positions = this._mergeElement(this.positions, other.positions);
  26027. this.normals = this._mergeElement(this.normals, other.normals);
  26028. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26029. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26030. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26031. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26032. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26033. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26034. this.colors = this._mergeElement(this.colors, other.colors);
  26035. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26036. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26037. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26038. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26039. };
  26040. VertexData.prototype._mergeElement = function (source, other) {
  26041. if (!other)
  26042. return source;
  26043. if (!source)
  26044. return other;
  26045. var len = other.length + source.length;
  26046. var isSrcTypedArray = source instanceof Float32Array;
  26047. var isOthTypedArray = other instanceof Float32Array;
  26048. // use non-loop method when the source is Float32Array
  26049. if (isSrcTypedArray) {
  26050. var ret32 = new Float32Array(len);
  26051. ret32.set(source);
  26052. ret32.set(other, source.length);
  26053. return ret32;
  26054. }
  26055. else if (!isOthTypedArray) {
  26056. return source.concat(other);
  26057. }
  26058. else {
  26059. var ret = source.slice(0); // copy source to a separate array
  26060. for (var i = 0, len = other.length; i < len; i++) {
  26061. ret.push(other[i]);
  26062. }
  26063. return ret;
  26064. }
  26065. };
  26066. VertexData.prototype.serialize = function () {
  26067. var serializationObject = this.serialize();
  26068. if (this.positions) {
  26069. serializationObject.positions = this.positions;
  26070. }
  26071. if (this.normals) {
  26072. serializationObject.normals = this.normals;
  26073. }
  26074. if (this.uvs) {
  26075. serializationObject.uvs = this.uvs;
  26076. }
  26077. if (this.uvs2) {
  26078. serializationObject.uvs2 = this.uvs2;
  26079. }
  26080. if (this.uvs3) {
  26081. serializationObject.uvs3 = this.uvs3;
  26082. }
  26083. if (this.uvs4) {
  26084. serializationObject.uvs4 = this.uvs4;
  26085. }
  26086. if (this.uvs5) {
  26087. serializationObject.uvs5 = this.uvs5;
  26088. }
  26089. if (this.uvs6) {
  26090. serializationObject.uvs6 = this.uvs6;
  26091. }
  26092. if (this.colors) {
  26093. serializationObject.colors = this.colors;
  26094. }
  26095. if (this.matricesIndices) {
  26096. serializationObject.matricesIndices = this.matricesIndices;
  26097. serializationObject.matricesIndices._isExpanded = true;
  26098. }
  26099. if (this.matricesWeights) {
  26100. serializationObject.matricesWeights = this.matricesWeights;
  26101. }
  26102. if (this.matricesIndicesExtra) {
  26103. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26104. serializationObject.matricesIndicesExtra._isExpanded = true;
  26105. }
  26106. if (this.matricesWeightsExtra) {
  26107. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26108. }
  26109. serializationObject.indices = this.indices;
  26110. return serializationObject;
  26111. };
  26112. // Statics
  26113. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26114. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26115. };
  26116. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26117. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26118. };
  26119. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26120. var result = new VertexData();
  26121. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26122. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26123. }
  26124. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26125. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26126. }
  26127. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26128. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26129. }
  26130. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26131. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26132. }
  26133. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26134. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26135. }
  26136. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26137. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26138. }
  26139. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26140. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26141. }
  26142. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26143. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26144. }
  26145. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26146. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26147. }
  26148. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26149. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26150. }
  26151. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26152. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26153. }
  26154. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26155. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  26156. }
  26157. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26158. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  26159. }
  26160. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26161. return result;
  26162. };
  26163. VertexData.CreateRibbon = function (options) {
  26164. var pathArray = options.pathArray;
  26165. var closeArray = options.closeArray || false;
  26166. var closePath = options.closePath || false;
  26167. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26168. var offset = options.offset || defaultOffset;
  26169. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26170. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26171. var positions = [];
  26172. var indices = [];
  26173. var normals = [];
  26174. var uvs = [];
  26175. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26176. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26177. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26178. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26179. var minlg; // minimal length among all paths from pathArray
  26180. var lg = []; // array of path lengths : nb of vertex per path
  26181. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26182. var p; // path iterator
  26183. var i; // point iterator
  26184. var j; // point iterator
  26185. // if single path in pathArray
  26186. if (pathArray.length < 2) {
  26187. var ar1 = [];
  26188. var ar2 = [];
  26189. for (i = 0; i < pathArray[0].length - offset; i++) {
  26190. ar1.push(pathArray[0][i]);
  26191. ar2.push(pathArray[0][i + offset]);
  26192. }
  26193. pathArray = [ar1, ar2];
  26194. }
  26195. // positions and horizontal distances (u)
  26196. var idc = 0;
  26197. var closePathCorr = (closePath) ? 1 : 0;
  26198. var path;
  26199. var l;
  26200. minlg = pathArray[0].length;
  26201. var vectlg;
  26202. var dist;
  26203. for (p = 0; p < pathArray.length; p++) {
  26204. uTotalDistance[p] = 0;
  26205. us[p] = [0];
  26206. path = pathArray[p];
  26207. l = path.length;
  26208. minlg = (minlg < l) ? minlg : l;
  26209. j = 0;
  26210. while (j < l) {
  26211. positions.push(path[j].x, path[j].y, path[j].z);
  26212. if (j > 0) {
  26213. vectlg = path[j].subtract(path[j - 1]).length();
  26214. dist = vectlg + uTotalDistance[p];
  26215. us[p].push(dist);
  26216. uTotalDistance[p] = dist;
  26217. }
  26218. j++;
  26219. }
  26220. if (closePath) {
  26221. j--;
  26222. positions.push(path[0].x, path[0].y, path[0].z);
  26223. vectlg = path[j].subtract(path[0]).length();
  26224. dist = vectlg + uTotalDistance[p];
  26225. us[p].push(dist);
  26226. uTotalDistance[p] = dist;
  26227. }
  26228. lg[p] = l + closePathCorr;
  26229. idx[p] = idc;
  26230. idc += (l + closePathCorr);
  26231. }
  26232. // vertical distances (v)
  26233. var path1;
  26234. var path2;
  26235. var vertex1;
  26236. var vertex2;
  26237. for (i = 0; i < minlg + closePathCorr; i++) {
  26238. vTotalDistance[i] = 0;
  26239. vs[i] = [0];
  26240. for (p = 0; p < pathArray.length - 1; p++) {
  26241. path1 = pathArray[p];
  26242. path2 = pathArray[p + 1];
  26243. if (i === minlg) {
  26244. vertex1 = path1[0];
  26245. vertex2 = path2[0];
  26246. }
  26247. else {
  26248. vertex1 = path1[i];
  26249. vertex2 = path2[i];
  26250. }
  26251. vectlg = vertex2.subtract(vertex1).length();
  26252. dist = vectlg + vTotalDistance[i];
  26253. vs[i].push(dist);
  26254. vTotalDistance[i] = dist;
  26255. }
  26256. if (closeArray) {
  26257. path1 = pathArray[p];
  26258. path2 = pathArray[0];
  26259. if (i === minlg) {
  26260. vertex2 = path2[0];
  26261. }
  26262. vectlg = vertex2.subtract(vertex1).length();
  26263. dist = vectlg + vTotalDistance[i];
  26264. vTotalDistance[i] = dist;
  26265. }
  26266. }
  26267. // uvs
  26268. var u;
  26269. var v;
  26270. for (p = 0; p < pathArray.length; p++) {
  26271. for (i = 0; i < minlg + closePathCorr; i++) {
  26272. u = us[p][i] / uTotalDistance[p];
  26273. v = vs[i][p] / vTotalDistance[i];
  26274. uvs.push(u, v);
  26275. }
  26276. }
  26277. // indices
  26278. p = 0; // path index
  26279. var pi = 0; // positions array index
  26280. var l1 = lg[p] - 1; // path1 length
  26281. var l2 = lg[p + 1] - 1; // path2 length
  26282. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26283. var shft = idx[1] - idx[0]; // shift
  26284. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26285. while (pi <= min && p < path1nb) {
  26286. // 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
  26287. indices.push(pi, pi + shft, pi + 1);
  26288. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26289. pi += 1;
  26290. if (pi === min) {
  26291. p++;
  26292. if (p === lg.length - 1) {
  26293. shft = idx[0] - idx[p];
  26294. l1 = lg[p] - 1;
  26295. l2 = lg[0] - 1;
  26296. }
  26297. else {
  26298. shft = idx[p + 1] - idx[p];
  26299. l1 = lg[p] - 1;
  26300. l2 = lg[p + 1] - 1;
  26301. }
  26302. pi = idx[p];
  26303. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26304. }
  26305. }
  26306. // normals
  26307. VertexData.ComputeNormals(positions, indices, normals);
  26308. if (closePath) {
  26309. var indexFirst = 0;
  26310. var indexLast = 0;
  26311. for (p = 0; p < pathArray.length; p++) {
  26312. indexFirst = idx[p] * 3;
  26313. if (p + 1 < pathArray.length) {
  26314. indexLast = (idx[p + 1] - 1) * 3;
  26315. }
  26316. else {
  26317. indexLast = normals.length - 3;
  26318. }
  26319. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26320. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26321. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26322. normals[indexLast] = normals[indexFirst];
  26323. normals[indexLast + 1] = normals[indexFirst + 1];
  26324. normals[indexLast + 2] = normals[indexFirst + 2];
  26325. }
  26326. }
  26327. // sides
  26328. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26329. // Result
  26330. var vertexData = new VertexData();
  26331. vertexData.indices = indices;
  26332. vertexData.positions = positions;
  26333. vertexData.normals = normals;
  26334. vertexData.uvs = uvs;
  26335. if (closePath) {
  26336. vertexData._idx = idx;
  26337. }
  26338. return vertexData;
  26339. };
  26340. VertexData.CreateBox = function (options) {
  26341. var normalsSource = [
  26342. new BABYLON.Vector3(0, 0, 1),
  26343. new BABYLON.Vector3(0, 0, -1),
  26344. new BABYLON.Vector3(1, 0, 0),
  26345. new BABYLON.Vector3(-1, 0, 0),
  26346. new BABYLON.Vector3(0, 1, 0),
  26347. new BABYLON.Vector3(0, -1, 0)
  26348. ];
  26349. var indices = [];
  26350. var positions = [];
  26351. var normals = [];
  26352. var uvs = [];
  26353. var width = options.width || options.size || 1;
  26354. var height = options.height || options.size || 1;
  26355. var depth = options.depth || options.size || 1;
  26356. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26357. var faceUV = options.faceUV || new Array(6);
  26358. var faceColors = options.faceColors;
  26359. var colors = [];
  26360. // default face colors and UV if undefined
  26361. for (var f = 0; f < 6; f++) {
  26362. if (faceUV[f] === undefined) {
  26363. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26364. }
  26365. if (faceColors && faceColors[f] === undefined) {
  26366. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26367. }
  26368. }
  26369. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26370. // Create each face in turn.
  26371. for (var index = 0; index < normalsSource.length; index++) {
  26372. var normal = normalsSource[index];
  26373. // Get two vectors perpendicular to the face normal and to each other.
  26374. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26375. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26376. // Six indices (two triangles) per face.
  26377. var verticesLength = positions.length / 3;
  26378. indices.push(verticesLength);
  26379. indices.push(verticesLength + 1);
  26380. indices.push(verticesLength + 2);
  26381. indices.push(verticesLength);
  26382. indices.push(verticesLength + 2);
  26383. indices.push(verticesLength + 3);
  26384. // Four vertices per face.
  26385. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26386. positions.push(vertex.x, vertex.y, vertex.z);
  26387. normals.push(normal.x, normal.y, normal.z);
  26388. uvs.push(faceUV[index].z, faceUV[index].w);
  26389. if (faceColors) {
  26390. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26391. }
  26392. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26393. positions.push(vertex.x, vertex.y, vertex.z);
  26394. normals.push(normal.x, normal.y, normal.z);
  26395. uvs.push(faceUV[index].x, faceUV[index].w);
  26396. if (faceColors) {
  26397. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26398. }
  26399. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26400. positions.push(vertex.x, vertex.y, vertex.z);
  26401. normals.push(normal.x, normal.y, normal.z);
  26402. uvs.push(faceUV[index].x, faceUV[index].y);
  26403. if (faceColors) {
  26404. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26405. }
  26406. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26407. positions.push(vertex.x, vertex.y, vertex.z);
  26408. normals.push(normal.x, normal.y, normal.z);
  26409. uvs.push(faceUV[index].z, faceUV[index].y);
  26410. if (faceColors) {
  26411. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26412. }
  26413. }
  26414. // sides
  26415. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26416. // Result
  26417. var vertexData = new VertexData();
  26418. vertexData.indices = indices;
  26419. vertexData.positions = positions;
  26420. vertexData.normals = normals;
  26421. vertexData.uvs = uvs;
  26422. if (faceColors) {
  26423. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26424. vertexData.colors = totalColors;
  26425. }
  26426. return vertexData;
  26427. };
  26428. VertexData.CreateSphere = function (options) {
  26429. var segments = options.segments || 32;
  26430. var diameterX = options.diameterX || options.diameter || 1;
  26431. var diameterY = options.diameterY || options.diameter || 1;
  26432. var diameterZ = options.diameterZ || options.diameter || 1;
  26433. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26434. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26435. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26436. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26437. var totalZRotationSteps = 2 + segments;
  26438. var totalYRotationSteps = 2 * totalZRotationSteps;
  26439. var indices = [];
  26440. var positions = [];
  26441. var normals = [];
  26442. var uvs = [];
  26443. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26444. var normalizedZ = zRotationStep / totalZRotationSteps;
  26445. var angleZ = normalizedZ * Math.PI * slice;
  26446. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26447. var normalizedY = yRotationStep / totalYRotationSteps;
  26448. var angleY = normalizedY * Math.PI * 2 * arc;
  26449. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26450. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26451. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26452. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26453. var vertex = complete.multiply(radius);
  26454. var normal = complete.divide(radius).normalize();
  26455. positions.push(vertex.x, vertex.y, vertex.z);
  26456. normals.push(normal.x, normal.y, normal.z);
  26457. uvs.push(normalizedY, normalizedZ);
  26458. }
  26459. if (zRotationStep > 0) {
  26460. var verticesCount = positions.length / 3;
  26461. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26462. indices.push((firstIndex));
  26463. indices.push((firstIndex + 1));
  26464. indices.push(firstIndex + totalYRotationSteps + 1);
  26465. indices.push((firstIndex + totalYRotationSteps + 1));
  26466. indices.push((firstIndex + 1));
  26467. indices.push((firstIndex + totalYRotationSteps + 2));
  26468. }
  26469. }
  26470. }
  26471. // Sides
  26472. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26473. // Result
  26474. var vertexData = new VertexData();
  26475. vertexData.indices = indices;
  26476. vertexData.positions = positions;
  26477. vertexData.normals = normals;
  26478. vertexData.uvs = uvs;
  26479. return vertexData;
  26480. };
  26481. // Cylinder and cone
  26482. VertexData.CreateCylinder = function (options) {
  26483. var height = options.height || 2;
  26484. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26485. var diameterBottom = options.diameterBottom || options.diameter || 1;
  26486. var tessellation = options.tessellation || 24;
  26487. var subdivisions = options.subdivisions || 1;
  26488. var hasRings = options.hasRings;
  26489. var enclose = options.enclose;
  26490. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26491. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26492. var faceUV = options.faceUV || new Array(3);
  26493. var faceColors = options.faceColors;
  26494. // default face colors and UV if undefined
  26495. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26496. var ringNb = (hasRings) ? subdivisions : 1;
  26497. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26498. var f;
  26499. for (f = 0; f < surfaceNb; f++) {
  26500. if (faceColors && faceColors[f] === undefined) {
  26501. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26502. }
  26503. }
  26504. for (f = 0; f < surfaceNb; f++) {
  26505. if (faceUV && faceUV[f] === undefined) {
  26506. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26507. }
  26508. }
  26509. var indices = [];
  26510. var positions = [];
  26511. var normals = [];
  26512. var uvs = [];
  26513. var colors = [];
  26514. var angle_step = Math.PI * 2 * arc / tessellation;
  26515. var angle;
  26516. var h;
  26517. var radius;
  26518. var tan = (diameterBottom - diameterTop) / 2 / height;
  26519. var ringVertex = BABYLON.Vector3.Zero();
  26520. var ringNormal = BABYLON.Vector3.Zero();
  26521. var ringFirstVertex = BABYLON.Vector3.Zero();
  26522. var ringFirstNormal = BABYLON.Vector3.Zero();
  26523. var quadNormal = BABYLON.Vector3.Zero();
  26524. var Y = BABYLON.Axis.Y;
  26525. // positions, normals, uvs
  26526. var i;
  26527. var j;
  26528. var r;
  26529. var ringIdx = 1;
  26530. var s = 1; // surface index
  26531. var cs = 0;
  26532. var v = 0;
  26533. for (i = 0; i <= subdivisions; i++) {
  26534. h = i / subdivisions;
  26535. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26536. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26537. for (r = 0; r < ringIdx; r++) {
  26538. if (hasRings) {
  26539. s += r;
  26540. }
  26541. if (enclose) {
  26542. s += 2 * r;
  26543. }
  26544. for (j = 0; j <= tessellation; j++) {
  26545. angle = j * angle_step;
  26546. // position
  26547. ringVertex.x = Math.cos(-angle) * radius;
  26548. ringVertex.y = -height / 2 + h * height;
  26549. ringVertex.z = Math.sin(-angle) * radius;
  26550. // normal
  26551. if (diameterTop === 0 && i === subdivisions) {
  26552. // if no top cap, reuse former normals
  26553. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26554. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26555. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26556. }
  26557. else {
  26558. ringNormal.x = ringVertex.x;
  26559. ringNormal.z = ringVertex.z;
  26560. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26561. ringNormal.normalize();
  26562. }
  26563. // keep first ring vertex values for enclose
  26564. if (j === 0) {
  26565. ringFirstVertex.copyFrom(ringVertex);
  26566. ringFirstNormal.copyFrom(ringNormal);
  26567. }
  26568. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26569. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26570. if (hasRings) {
  26571. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26572. }
  26573. else {
  26574. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26575. }
  26576. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26577. if (faceColors) {
  26578. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26579. }
  26580. }
  26581. // if enclose, add four vertices and their dedicated normals
  26582. if (arc !== 1 && enclose) {
  26583. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26584. positions.push(0, ringVertex.y, 0);
  26585. positions.push(0, ringVertex.y, 0);
  26586. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26587. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26588. quadNormal.normalize();
  26589. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26590. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26591. quadNormal.normalize();
  26592. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26593. if (hasRings) {
  26594. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26595. }
  26596. else {
  26597. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26598. }
  26599. uvs.push(faceUV[s + 1].x, v);
  26600. uvs.push(faceUV[s + 1].z, v);
  26601. if (hasRings) {
  26602. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26603. }
  26604. else {
  26605. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26606. }
  26607. uvs.push(faceUV[s + 2].x, v);
  26608. uvs.push(faceUV[s + 2].z, v);
  26609. if (faceColors) {
  26610. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26611. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26612. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26613. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26614. }
  26615. }
  26616. if (cs !== s) {
  26617. cs = s;
  26618. }
  26619. }
  26620. }
  26621. // indices
  26622. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26623. var s;
  26624. i = 0;
  26625. for (s = 0; s < subdivisions; s++) {
  26626. for (j = 0; j < tessellation; j++) {
  26627. var i0 = i * (e + 1) + j;
  26628. var i1 = (i + 1) * (e + 1) + j;
  26629. var i2 = i * (e + 1) + (j + 1);
  26630. var i3 = (i + 1) * (e + 1) + (j + 1);
  26631. indices.push(i0, i1, i2);
  26632. indices.push(i3, i2, i1);
  26633. }
  26634. if (arc !== 1 && enclose) {
  26635. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26636. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26637. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26638. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26639. }
  26640. i = (hasRings) ? (i + 2) : (i + 1);
  26641. }
  26642. // Caps
  26643. var createCylinderCap = function (isTop) {
  26644. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26645. if (radius === 0) {
  26646. return;
  26647. }
  26648. // Cap positions, normals & uvs
  26649. var angle;
  26650. var circleVector;
  26651. var i;
  26652. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26653. var c;
  26654. if (faceColors) {
  26655. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26656. }
  26657. // cap center
  26658. var vbase = positions.length / 3;
  26659. var offset = isTop ? height / 2 : -height / 2;
  26660. var center = new BABYLON.Vector3(0, offset, 0);
  26661. positions.push(center.x, center.y, center.z);
  26662. normals.push(0, isTop ? 1 : -1, 0);
  26663. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26664. if (faceColors) {
  26665. colors.push(c.r, c.g, c.b, c.a);
  26666. }
  26667. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26668. for (i = 0; i <= tessellation; i++) {
  26669. angle = Math.PI * 2 * i * arc / tessellation;
  26670. var cos = Math.cos(-angle);
  26671. var sin = Math.sin(-angle);
  26672. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26673. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26674. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26675. normals.push(0, isTop ? 1 : -1, 0);
  26676. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26677. if (faceColors) {
  26678. colors.push(c.r, c.g, c.b, c.a);
  26679. }
  26680. }
  26681. // Cap indices
  26682. for (i = 0; i < tessellation; i++) {
  26683. if (!isTop) {
  26684. indices.push(vbase);
  26685. indices.push(vbase + (i + 1));
  26686. indices.push(vbase + (i + 2));
  26687. }
  26688. else {
  26689. indices.push(vbase);
  26690. indices.push(vbase + (i + 2));
  26691. indices.push(vbase + (i + 1));
  26692. }
  26693. }
  26694. };
  26695. // add caps to geometry
  26696. createCylinderCap(false);
  26697. createCylinderCap(true);
  26698. // Sides
  26699. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26700. var vertexData = new VertexData();
  26701. vertexData.indices = indices;
  26702. vertexData.positions = positions;
  26703. vertexData.normals = normals;
  26704. vertexData.uvs = uvs;
  26705. if (faceColors) {
  26706. vertexData.colors = colors;
  26707. }
  26708. return vertexData;
  26709. };
  26710. VertexData.CreateTorus = function (options) {
  26711. var indices = [];
  26712. var positions = [];
  26713. var normals = [];
  26714. var uvs = [];
  26715. var diameter = options.diameter || 1;
  26716. var thickness = options.thickness || 0.5;
  26717. var tessellation = options.tessellation || 16;
  26718. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26719. var stride = tessellation + 1;
  26720. for (var i = 0; i <= tessellation; i++) {
  26721. var u = i / tessellation;
  26722. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26723. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26724. for (var j = 0; j <= tessellation; j++) {
  26725. var v = 1 - j / tessellation;
  26726. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26727. var dx = Math.cos(innerAngle);
  26728. var dy = Math.sin(innerAngle);
  26729. // Create a vertex.
  26730. var normal = new BABYLON.Vector3(dx, dy, 0);
  26731. var position = normal.scale(thickness / 2);
  26732. var textureCoordinate = new BABYLON.Vector2(u, v);
  26733. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26734. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26735. positions.push(position.x, position.y, position.z);
  26736. normals.push(normal.x, normal.y, normal.z);
  26737. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26738. // And create indices for two triangles.
  26739. var nextI = (i + 1) % stride;
  26740. var nextJ = (j + 1) % stride;
  26741. indices.push(i * stride + j);
  26742. indices.push(i * stride + nextJ);
  26743. indices.push(nextI * stride + j);
  26744. indices.push(i * stride + nextJ);
  26745. indices.push(nextI * stride + nextJ);
  26746. indices.push(nextI * stride + j);
  26747. }
  26748. }
  26749. // Sides
  26750. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26751. // Result
  26752. var vertexData = new VertexData();
  26753. vertexData.indices = indices;
  26754. vertexData.positions = positions;
  26755. vertexData.normals = normals;
  26756. vertexData.uvs = uvs;
  26757. return vertexData;
  26758. };
  26759. VertexData.CreateLineSystem = function (options) {
  26760. var indices = [];
  26761. var positions = [];
  26762. var lines = options.lines;
  26763. var idx = 0;
  26764. for (var l = 0; l < lines.length; l++) {
  26765. var points = lines[l];
  26766. for (var index = 0; index < points.length; index++) {
  26767. positions.push(points[index].x, points[index].y, points[index].z);
  26768. if (index > 0) {
  26769. indices.push(idx - 1);
  26770. indices.push(idx);
  26771. }
  26772. idx++;
  26773. }
  26774. }
  26775. var vertexData = new VertexData();
  26776. vertexData.indices = indices;
  26777. vertexData.positions = positions;
  26778. return vertexData;
  26779. };
  26780. VertexData.CreateDashedLines = function (options) {
  26781. var dashSize = options.dashSize || 3;
  26782. var gapSize = options.gapSize || 1;
  26783. var dashNb = options.dashNb || 200;
  26784. var points = options.points;
  26785. var positions = new Array();
  26786. var indices = new Array();
  26787. var curvect = BABYLON.Vector3.Zero();
  26788. var lg = 0;
  26789. var nb = 0;
  26790. var shft = 0;
  26791. var dashshft = 0;
  26792. var curshft = 0;
  26793. var idx = 0;
  26794. var i = 0;
  26795. for (i = 0; i < points.length - 1; i++) {
  26796. points[i + 1].subtractToRef(points[i], curvect);
  26797. lg += curvect.length();
  26798. }
  26799. shft = lg / dashNb;
  26800. dashshft = dashSize * shft / (dashSize + gapSize);
  26801. for (i = 0; i < points.length - 1; i++) {
  26802. points[i + 1].subtractToRef(points[i], curvect);
  26803. nb = Math.floor(curvect.length() / shft);
  26804. curvect.normalize();
  26805. for (var j = 0; j < nb; j++) {
  26806. curshft = shft * j;
  26807. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26808. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26809. indices.push(idx, idx + 1);
  26810. idx += 2;
  26811. }
  26812. }
  26813. // Result
  26814. var vertexData = new VertexData();
  26815. vertexData.positions = positions;
  26816. vertexData.indices = indices;
  26817. return vertexData;
  26818. };
  26819. VertexData.CreateGround = function (options) {
  26820. var indices = [];
  26821. var positions = [];
  26822. var normals = [];
  26823. var uvs = [];
  26824. var row, col;
  26825. var width = options.width || 1;
  26826. var height = options.height || 1;
  26827. var subdivisions = options.subdivisions || 1;
  26828. for (row = 0; row <= subdivisions; row++) {
  26829. for (col = 0; col <= subdivisions; col++) {
  26830. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26831. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26832. positions.push(position.x, position.y, position.z);
  26833. normals.push(normal.x, normal.y, normal.z);
  26834. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26835. }
  26836. }
  26837. for (row = 0; row < subdivisions; row++) {
  26838. for (col = 0; col < subdivisions; col++) {
  26839. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26840. indices.push(col + 1 + row * (subdivisions + 1));
  26841. indices.push(col + row * (subdivisions + 1));
  26842. indices.push(col + (row + 1) * (subdivisions + 1));
  26843. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26844. indices.push(col + row * (subdivisions + 1));
  26845. }
  26846. }
  26847. // Result
  26848. var vertexData = new VertexData();
  26849. vertexData.indices = indices;
  26850. vertexData.positions = positions;
  26851. vertexData.normals = normals;
  26852. vertexData.uvs = uvs;
  26853. return vertexData;
  26854. };
  26855. VertexData.CreateTiledGround = function (options) {
  26856. var xmin = options.xmin;
  26857. var zmin = options.zmin;
  26858. var xmax = options.xmax;
  26859. var zmax = options.zmax;
  26860. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26861. var precision = options.precision || { w: 1, h: 1 };
  26862. var indices = [];
  26863. var positions = [];
  26864. var normals = [];
  26865. var uvs = [];
  26866. var row, col, tileRow, tileCol;
  26867. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26868. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26869. precision.w = (precision.w < 1) ? 1 : precision.w;
  26870. precision.h = (precision.h < 1) ? 1 : precision.h;
  26871. var tileSize = {
  26872. 'w': (xmax - xmin) / subdivisions.w,
  26873. 'h': (zmax - zmin) / subdivisions.h
  26874. };
  26875. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26876. // Indices
  26877. var base = positions.length / 3;
  26878. var rowLength = precision.w + 1;
  26879. for (row = 0; row < precision.h; row++) {
  26880. for (col = 0; col < precision.w; col++) {
  26881. var square = [
  26882. base + col + row * rowLength,
  26883. base + (col + 1) + row * rowLength,
  26884. base + (col + 1) + (row + 1) * rowLength,
  26885. base + col + (row + 1) * rowLength
  26886. ];
  26887. indices.push(square[1]);
  26888. indices.push(square[2]);
  26889. indices.push(square[3]);
  26890. indices.push(square[0]);
  26891. indices.push(square[1]);
  26892. indices.push(square[3]);
  26893. }
  26894. }
  26895. // Position, normals and uvs
  26896. var position = BABYLON.Vector3.Zero();
  26897. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26898. for (row = 0; row <= precision.h; row++) {
  26899. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26900. for (col = 0; col <= precision.w; col++) {
  26901. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26902. position.y = 0;
  26903. positions.push(position.x, position.y, position.z);
  26904. normals.push(normal.x, normal.y, normal.z);
  26905. uvs.push(col / precision.w, row / precision.h);
  26906. }
  26907. }
  26908. }
  26909. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26910. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26911. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26912. }
  26913. }
  26914. // Result
  26915. var vertexData = new VertexData();
  26916. vertexData.indices = indices;
  26917. vertexData.positions = positions;
  26918. vertexData.normals = normals;
  26919. vertexData.uvs = uvs;
  26920. return vertexData;
  26921. };
  26922. VertexData.CreateGroundFromHeightMap = function (options) {
  26923. var indices = [];
  26924. var positions = [];
  26925. var normals = [];
  26926. var uvs = [];
  26927. var row, col;
  26928. // Vertices
  26929. for (row = 0; row <= options.subdivisions; row++) {
  26930. for (col = 0; col <= options.subdivisions; col++) {
  26931. 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));
  26932. // Compute height
  26933. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26934. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26935. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26936. var r = options.buffer[pos] / 255.0;
  26937. var g = options.buffer[pos + 1] / 255.0;
  26938. var b = options.buffer[pos + 2] / 255.0;
  26939. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26940. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26941. // Add vertex
  26942. positions.push(position.x, position.y, position.z);
  26943. normals.push(0, 0, 0);
  26944. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26945. }
  26946. }
  26947. // Indices
  26948. for (row = 0; row < options.subdivisions; row++) {
  26949. for (col = 0; col < options.subdivisions; col++) {
  26950. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26951. indices.push(col + 1 + row * (options.subdivisions + 1));
  26952. indices.push(col + row * (options.subdivisions + 1));
  26953. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26954. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26955. indices.push(col + row * (options.subdivisions + 1));
  26956. }
  26957. }
  26958. // Normals
  26959. VertexData.ComputeNormals(positions, indices, normals);
  26960. // Result
  26961. var vertexData = new VertexData();
  26962. vertexData.indices = indices;
  26963. vertexData.positions = positions;
  26964. vertexData.normals = normals;
  26965. vertexData.uvs = uvs;
  26966. return vertexData;
  26967. };
  26968. VertexData.CreatePlane = function (options) {
  26969. var indices = [];
  26970. var positions = [];
  26971. var normals = [];
  26972. var uvs = [];
  26973. var width = options.width || options.size || 1;
  26974. var height = options.height || options.size || 1;
  26975. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26976. // Vertices
  26977. var halfWidth = width / 2.0;
  26978. var halfHeight = height / 2.0;
  26979. positions.push(-halfWidth, -halfHeight, 0);
  26980. normals.push(0, 0, -1.0);
  26981. uvs.push(0.0, 0.0);
  26982. positions.push(halfWidth, -halfHeight, 0);
  26983. normals.push(0, 0, -1.0);
  26984. uvs.push(1.0, 0.0);
  26985. positions.push(halfWidth, halfHeight, 0);
  26986. normals.push(0, 0, -1.0);
  26987. uvs.push(1.0, 1.0);
  26988. positions.push(-halfWidth, halfHeight, 0);
  26989. normals.push(0, 0, -1.0);
  26990. uvs.push(0.0, 1.0);
  26991. // Indices
  26992. indices.push(0);
  26993. indices.push(1);
  26994. indices.push(2);
  26995. indices.push(0);
  26996. indices.push(2);
  26997. indices.push(3);
  26998. // Sides
  26999. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27000. // Result
  27001. var vertexData = new VertexData();
  27002. vertexData.indices = indices;
  27003. vertexData.positions = positions;
  27004. vertexData.normals = normals;
  27005. vertexData.uvs = uvs;
  27006. return vertexData;
  27007. };
  27008. VertexData.CreateDisc = function (options) {
  27009. var positions = [];
  27010. var indices = [];
  27011. var normals = [];
  27012. var uvs = [];
  27013. var radius = options.radius || 0.5;
  27014. var tessellation = options.tessellation || 64;
  27015. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27016. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27017. // positions and uvs
  27018. positions.push(0, 0, 0); // disc center first
  27019. uvs.push(0.5, 0.5);
  27020. var theta = Math.PI * 2 * arc;
  27021. var step = theta / tessellation;
  27022. for (var a = 0; a < theta; a += step) {
  27023. var x = Math.cos(a);
  27024. var y = Math.sin(a);
  27025. var u = (x + 1) / 2;
  27026. var v = (1 - y) / 2;
  27027. positions.push(radius * x, radius * y, 0);
  27028. uvs.push(u, v);
  27029. }
  27030. if (arc === 1) {
  27031. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27032. uvs.push(uvs[2], uvs[3]);
  27033. }
  27034. //indices
  27035. var vertexNb = positions.length / 3;
  27036. for (var i = 1; i < vertexNb - 1; i++) {
  27037. indices.push(i + 1, 0, i);
  27038. }
  27039. // result
  27040. VertexData.ComputeNormals(positions, indices, normals);
  27041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27042. var vertexData = new VertexData();
  27043. vertexData.indices = indices;
  27044. vertexData.positions = positions;
  27045. vertexData.normals = normals;
  27046. vertexData.uvs = uvs;
  27047. return vertexData;
  27048. };
  27049. VertexData.CreateIcoSphere = function (options) {
  27050. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27051. var radius = options.radius || 1;
  27052. var flat = (options.flat === undefined) ? true : options.flat;
  27053. var subdivisions = options.subdivisions || 4;
  27054. var radiusX = options.radiusX || radius;
  27055. var radiusY = options.radiusY || radius;
  27056. var radiusZ = options.radiusZ || radius;
  27057. var t = (1 + Math.sqrt(5)) / 2;
  27058. // 12 vertex x,y,z
  27059. var ico_vertices = [
  27060. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27061. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27062. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27063. ];
  27064. // index of 3 vertex makes a face of icopshere
  27065. var ico_indices = [
  27066. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27067. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27068. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27069. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27070. ];
  27071. // vertex for uv have aliased position, not for UV
  27072. var vertices_unalias_id = [
  27073. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27074. // vertex alias
  27075. 0,
  27076. 2,
  27077. 3,
  27078. 3,
  27079. 3,
  27080. 4,
  27081. 7,
  27082. 8,
  27083. 9,
  27084. 9,
  27085. 10,
  27086. 11 // 23: B + 12
  27087. ];
  27088. // uv as integer step (not pixels !)
  27089. var ico_vertexuv = [
  27090. 5, 1, 3, 1, 6, 4, 0, 0,
  27091. 5, 3, 4, 2, 2, 2, 4, 0,
  27092. 2, 0, 1, 1, 6, 0, 6, 2,
  27093. // vertex alias (for same vertex on different faces)
  27094. 0, 4,
  27095. 3, 3,
  27096. 4, 4,
  27097. 3, 1,
  27098. 4, 2,
  27099. 4, 4,
  27100. 0, 2,
  27101. 1, 1,
  27102. 2, 2,
  27103. 3, 3,
  27104. 1, 3,
  27105. 2, 4 // 23: B + 12
  27106. ];
  27107. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27108. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27109. // First island of uv mapping
  27110. // v = 4h 3+ 2
  27111. // v = 3h 9+ 4
  27112. // v = 2h 9+ 5 B
  27113. // v = 1h 9 1 0
  27114. // v = 0h 3 8 7 A
  27115. // u = 0 1 2 3 4 5 6 *a
  27116. // Second island of uv mapping
  27117. // v = 4h 0+ B+ 4+
  27118. // v = 3h A+ 2+
  27119. // v = 2h 7+ 6 3+
  27120. // v = 1h 8+ 3+
  27121. // v = 0h
  27122. // u = 0 1 2 3 4 5 6 *a
  27123. // Face layout on texture UV mapping
  27124. // ============
  27125. // \ 4 /\ 16 / ======
  27126. // \ / \ / /\ 11 /
  27127. // \/ 7 \/ / \ /
  27128. // ======= / 10 \/
  27129. // /\ 17 /\ =======
  27130. // / \ / \ \ 15 /\
  27131. // / 8 \/ 12 \ \ / \
  27132. // ============ \/ 6 \
  27133. // \ 18 /\ ============
  27134. // \ / \ \ 5 /\ 0 /
  27135. // \/ 13 \ \ / \ /
  27136. // ======= \/ 1 \/
  27137. // =============
  27138. // /\ 19 /\ 2 /\
  27139. // / \ / \ / \
  27140. // / 14 \/ 9 \/ 3 \
  27141. // ===================
  27142. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27143. var ustep = 138 / 1024;
  27144. var vstep = 239 / 1024;
  27145. var uoffset = 60 / 1024;
  27146. var voffset = 26 / 1024;
  27147. // Second island should have margin, not to touch the first island
  27148. // avoid any borderline artefact in pixel rounding
  27149. var island_u_offset = -40 / 1024;
  27150. var island_v_offset = +20 / 1024;
  27151. // face is either island 0 or 1 :
  27152. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27153. var island = [
  27154. 0, 0, 0, 0, 1,
  27155. 0, 0, 1, 1, 0,
  27156. 0, 0, 1, 1, 0,
  27157. 0, 1, 1, 1, 0 // 15 - 19
  27158. ];
  27159. var indices = [];
  27160. var positions = [];
  27161. var normals = [];
  27162. var uvs = [];
  27163. var current_indice = 0;
  27164. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27165. var face_vertex_pos = new Array(3);
  27166. var face_vertex_uv = new Array(3);
  27167. var v012;
  27168. for (v012 = 0; v012 < 3; v012++) {
  27169. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27170. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27171. }
  27172. // create all with normals
  27173. for (var face = 0; face < 20; face++) {
  27174. // 3 vertex per face
  27175. for (v012 = 0; v012 < 3; v012++) {
  27176. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27177. var v_id = ico_indices[3 * face + v012];
  27178. // vertex have 3D position (x,y,z)
  27179. 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]);
  27180. // Normalize to get normal, then scale to radius
  27181. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27182. // uv Coordinates from vertex ID
  27183. 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);
  27184. }
  27185. // Subdivide the face (interpolate pos, norm, uv)
  27186. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27187. // - norm is linear interpolation of vertex corner normal
  27188. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27189. // - uv is linear interpolation
  27190. //
  27191. // Topology is as below for sub-divide by 2
  27192. // vertex shown as v0,v1,v2
  27193. // interp index is i1 to progress in range [v0,v1[
  27194. // interp index is i2 to progress in range [v0,v2[
  27195. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27196. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27197. //
  27198. //
  27199. // i2 v2
  27200. // ^ ^
  27201. // / / \
  27202. // / / \
  27203. // / / \
  27204. // / / (0,1) \
  27205. // / #---------\
  27206. // / / \ (0,0)'/ \
  27207. // / / \ / \
  27208. // / / \ / \
  27209. // / / (0,0) \ / (1,0) \
  27210. // / #---------#---------\
  27211. // v0 v1
  27212. //
  27213. // --------------------> i1
  27214. //
  27215. // interp of (i1,i2):
  27216. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27217. // along i1 : lerp(x0,x1, i1/(S-i2))
  27218. //
  27219. // centroid of triangle is needed to get help normal computation
  27220. // (c1,c2) are used for centroid location
  27221. var interp_vertex = function (i1, i2, c1, c2) {
  27222. // vertex is interpolated from
  27223. // - face_vertex_pos[0..2]
  27224. // - face_vertex_uv[0..2]
  27225. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27226. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27227. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27228. pos_interp.normalize();
  27229. var vertex_normal;
  27230. if (flat) {
  27231. // in flat mode, recalculate normal as face centroid normal
  27232. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27233. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27234. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27235. }
  27236. else {
  27237. // in smooth mode, recalculate normal from each single vertex position
  27238. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27239. }
  27240. // Vertex normal need correction due to X,Y,Z radius scaling
  27241. vertex_normal.x /= radiusX;
  27242. vertex_normal.y /= radiusY;
  27243. vertex_normal.z /= radiusZ;
  27244. vertex_normal.normalize();
  27245. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27246. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27247. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27248. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27249. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27250. uvs.push(uv_interp.x, uv_interp.y);
  27251. // push each vertex has member of a face
  27252. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27253. indices.push(current_indice);
  27254. current_indice++;
  27255. };
  27256. for (var i2 = 0; i2 < subdivisions; i2++) {
  27257. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27258. // face : (i1,i2) for /\ :
  27259. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27260. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27261. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27262. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27263. if (i1 + i2 + 1 < subdivisions) {
  27264. // face : (i1,i2)' for \/ :
  27265. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27266. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27267. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27268. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27269. }
  27270. }
  27271. }
  27272. }
  27273. // Sides
  27274. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27275. // Result
  27276. var vertexData = new VertexData();
  27277. vertexData.indices = indices;
  27278. vertexData.positions = positions;
  27279. vertexData.normals = normals;
  27280. vertexData.uvs = uvs;
  27281. return vertexData;
  27282. };
  27283. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27284. VertexData.CreatePolyhedron = function (options) {
  27285. // provided polyhedron types :
  27286. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27287. // 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)
  27288. var polyhedra = [];
  27289. 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]] };
  27290. 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]] };
  27291. polyhedra[2] = {
  27292. 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]],
  27293. 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]]
  27294. };
  27295. polyhedra[3] = {
  27296. 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]],
  27297. 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]]
  27298. };
  27299. polyhedra[4] = {
  27300. 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]],
  27301. 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]]
  27302. };
  27303. 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]] };
  27304. 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]] };
  27305. 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]] };
  27306. 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]] };
  27307. 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]] };
  27308. 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]] };
  27309. 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]] };
  27310. 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]] };
  27311. 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]] };
  27312. polyhedra[14] = {
  27313. 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]],
  27314. 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]]
  27315. };
  27316. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27317. var size = options.size;
  27318. var sizeX = options.sizeX || size || 1;
  27319. var sizeY = options.sizeY || size || 1;
  27320. var sizeZ = options.sizeZ || size || 1;
  27321. var data = options.custom || polyhedra[type];
  27322. var nbfaces = data.face.length;
  27323. var faceUV = options.faceUV || new Array(nbfaces);
  27324. var faceColors = options.faceColors;
  27325. var flat = (options.flat === undefined) ? true : options.flat;
  27326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27327. var positions = [];
  27328. var indices = [];
  27329. var normals = [];
  27330. var uvs = [];
  27331. var colors = [];
  27332. var index = 0;
  27333. var faceIdx = 0; // face cursor in the array "indexes"
  27334. var indexes = [];
  27335. var i = 0;
  27336. var f = 0;
  27337. var u, v, ang, x, y, tmp;
  27338. // default face colors and UV if undefined
  27339. if (flat) {
  27340. for (f = 0; f < nbfaces; f++) {
  27341. if (faceColors && faceColors[f] === undefined) {
  27342. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27343. }
  27344. if (faceUV && faceUV[f] === undefined) {
  27345. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27346. }
  27347. }
  27348. }
  27349. if (!flat) {
  27350. for (i = 0; i < data.vertex.length; i++) {
  27351. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27352. uvs.push(0, 0);
  27353. }
  27354. for (f = 0; f < nbfaces; f++) {
  27355. for (i = 0; i < data.face[f].length - 2; i++) {
  27356. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27357. }
  27358. }
  27359. }
  27360. else {
  27361. for (f = 0; f < nbfaces; f++) {
  27362. var fl = data.face[f].length; // number of vertices of the current face
  27363. ang = 2 * Math.PI / fl;
  27364. x = 0.5 * Math.tan(ang / 2);
  27365. y = 0.5;
  27366. // positions, uvs, colors
  27367. for (i = 0; i < fl; i++) {
  27368. // positions
  27369. 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);
  27370. indexes.push(index);
  27371. index++;
  27372. // uvs
  27373. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27374. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27375. uvs.push(u, v);
  27376. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27377. y = x * Math.sin(ang) + y * Math.cos(ang);
  27378. x = tmp;
  27379. // colors
  27380. if (faceColors) {
  27381. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27382. }
  27383. }
  27384. // indices from indexes
  27385. for (i = 0; i < fl - 2; i++) {
  27386. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27387. }
  27388. faceIdx += fl;
  27389. }
  27390. }
  27391. VertexData.ComputeNormals(positions, indices, normals);
  27392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27393. var vertexData = new VertexData();
  27394. vertexData.positions = positions;
  27395. vertexData.indices = indices;
  27396. vertexData.normals = normals;
  27397. vertexData.uvs = uvs;
  27398. if (faceColors && flat) {
  27399. vertexData.colors = colors;
  27400. }
  27401. return vertexData;
  27402. };
  27403. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27404. VertexData.CreateTorusKnot = function (options) {
  27405. var indices = [];
  27406. var positions = [];
  27407. var normals = [];
  27408. var uvs = [];
  27409. var radius = options.radius || 2;
  27410. var tube = options.tube || 0.5;
  27411. var radialSegments = options.radialSegments || 32;
  27412. var tubularSegments = options.tubularSegments || 32;
  27413. var p = options.p || 2;
  27414. var q = options.q || 3;
  27415. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27416. // Helper
  27417. var getPos = function (angle) {
  27418. var cu = Math.cos(angle);
  27419. var su = Math.sin(angle);
  27420. var quOverP = q / p * angle;
  27421. var cs = Math.cos(quOverP);
  27422. var tx = radius * (2 + cs) * 0.5 * cu;
  27423. var ty = radius * (2 + cs) * su * 0.5;
  27424. var tz = radius * Math.sin(quOverP) * 0.5;
  27425. return new BABYLON.Vector3(tx, ty, tz);
  27426. };
  27427. // Vertices
  27428. var i;
  27429. var j;
  27430. for (i = 0; i <= radialSegments; i++) {
  27431. var modI = i % radialSegments;
  27432. var u = modI / radialSegments * 2 * p * Math.PI;
  27433. var p1 = getPos(u);
  27434. var p2 = getPos(u + 0.01);
  27435. var tang = p2.subtract(p1);
  27436. var n = p2.add(p1);
  27437. var bitan = BABYLON.Vector3.Cross(tang, n);
  27438. n = BABYLON.Vector3.Cross(bitan, tang);
  27439. bitan.normalize();
  27440. n.normalize();
  27441. for (j = 0; j < tubularSegments; j++) {
  27442. var modJ = j % tubularSegments;
  27443. var v = modJ / tubularSegments * 2 * Math.PI;
  27444. var cx = -tube * Math.cos(v);
  27445. var cy = tube * Math.sin(v);
  27446. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27447. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27448. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27449. uvs.push(i / radialSegments);
  27450. uvs.push(j / tubularSegments);
  27451. }
  27452. }
  27453. for (i = 0; i < radialSegments; i++) {
  27454. for (j = 0; j < tubularSegments; j++) {
  27455. var jNext = (j + 1) % tubularSegments;
  27456. var a = i * tubularSegments + j;
  27457. var b = (i + 1) * tubularSegments + j;
  27458. var c = (i + 1) * tubularSegments + jNext;
  27459. var d = i * tubularSegments + jNext;
  27460. indices.push(d);
  27461. indices.push(b);
  27462. indices.push(a);
  27463. indices.push(d);
  27464. indices.push(c);
  27465. indices.push(b);
  27466. }
  27467. }
  27468. // Normals
  27469. VertexData.ComputeNormals(positions, indices, normals);
  27470. // Sides
  27471. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27472. // Result
  27473. var vertexData = new VertexData();
  27474. vertexData.indices = indices;
  27475. vertexData.positions = positions;
  27476. vertexData.normals = normals;
  27477. vertexData.uvs = uvs;
  27478. return vertexData;
  27479. };
  27480. // Tools
  27481. /**
  27482. * @param {any} - positions (number[] or Float32Array)
  27483. * @param {any} - indices (number[] or Uint16Array)
  27484. * @param {any} - normals (number[] or Float32Array)
  27485. */
  27486. VertexData.ComputeNormals = function (positions, indices, normals) {
  27487. var index = 0;
  27488. var p1p2x = 0.0;
  27489. var p1p2y = 0.0;
  27490. var p1p2z = 0.0;
  27491. var p3p2x = 0.0;
  27492. var p3p2y = 0.0;
  27493. var p3p2z = 0.0;
  27494. var faceNormalx = 0.0;
  27495. var faceNormaly = 0.0;
  27496. var faceNormalz = 0.0;
  27497. var length = 0.0;
  27498. var i1 = 0;
  27499. var i2 = 0;
  27500. var i3 = 0;
  27501. for (index = 0; index < positions.length; index++) {
  27502. normals[index] = 0.0;
  27503. }
  27504. // indice triplet = 1 face
  27505. var nbFaces = indices.length / 3;
  27506. for (index = 0; index < nbFaces; index++) {
  27507. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  27508. i2 = indices[index * 3 + 1];
  27509. i3 = indices[index * 3 + 2];
  27510. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  27511. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27512. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27513. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  27514. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27515. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27516. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  27517. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  27518. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  27519. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27520. length = (length === 0) ? 1.0 : length;
  27521. faceNormalx /= length; // normalize this normal
  27522. faceNormaly /= length;
  27523. faceNormalz /= length;
  27524. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  27525. normals[i1 * 3 + 1] += faceNormaly;
  27526. normals[i1 * 3 + 2] += faceNormalz;
  27527. normals[i2 * 3] += faceNormalx;
  27528. normals[i2 * 3 + 1] += faceNormaly;
  27529. normals[i2 * 3 + 2] += faceNormalz;
  27530. normals[i3 * 3] += faceNormalx;
  27531. normals[i3 * 3 + 1] += faceNormaly;
  27532. normals[i3 * 3 + 2] += faceNormalz;
  27533. }
  27534. // last normalization of each normal
  27535. for (index = 0; index < normals.length / 3; index++) {
  27536. faceNormalx = normals[index * 3];
  27537. faceNormaly = normals[index * 3 + 1];
  27538. faceNormalz = normals[index * 3 + 2];
  27539. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27540. length = (length === 0) ? 1.0 : length;
  27541. faceNormalx /= length;
  27542. faceNormaly /= length;
  27543. faceNormalz /= length;
  27544. normals[index * 3] = faceNormalx;
  27545. normals[index * 3 + 1] = faceNormaly;
  27546. normals[index * 3 + 2] = faceNormalz;
  27547. }
  27548. };
  27549. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27550. var li = indices.length;
  27551. var ln = normals.length;
  27552. var i;
  27553. var n;
  27554. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27555. switch (sideOrientation) {
  27556. case BABYLON.Mesh.FRONTSIDE:
  27557. // nothing changed
  27558. break;
  27559. case BABYLON.Mesh.BACKSIDE:
  27560. var tmp;
  27561. // indices
  27562. for (i = 0; i < li; i += 3) {
  27563. tmp = indices[i];
  27564. indices[i] = indices[i + 2];
  27565. indices[i + 2] = tmp;
  27566. }
  27567. // normals
  27568. for (n = 0; n < ln; n++) {
  27569. normals[n] = -normals[n];
  27570. }
  27571. break;
  27572. case BABYLON.Mesh.DOUBLESIDE:
  27573. // positions
  27574. var lp = positions.length;
  27575. var l = lp / 3;
  27576. for (var p = 0; p < lp; p++) {
  27577. positions[lp + p] = positions[p];
  27578. }
  27579. // indices
  27580. for (i = 0; i < li; i += 3) {
  27581. indices[i + li] = indices[i + 2] + l;
  27582. indices[i + 1 + li] = indices[i + 1] + l;
  27583. indices[i + 2 + li] = indices[i] + l;
  27584. }
  27585. // normals
  27586. for (n = 0; n < ln; n++) {
  27587. normals[ln + n] = -normals[n];
  27588. }
  27589. // uvs
  27590. var lu = uvs.length;
  27591. for (var u = 0; u < lu; u++) {
  27592. uvs[u + lu] = uvs[u];
  27593. }
  27594. break;
  27595. }
  27596. };
  27597. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27598. var vertexData = new VertexData();
  27599. // positions
  27600. var positions = parsedVertexData.positions;
  27601. if (positions) {
  27602. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27603. }
  27604. // normals
  27605. var normals = parsedVertexData.normals;
  27606. if (normals) {
  27607. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27608. }
  27609. // uvs
  27610. var uvs = parsedVertexData.uvs;
  27611. if (uvs) {
  27612. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27613. }
  27614. // uv2s
  27615. var uv2s = parsedVertexData.uv2s;
  27616. if (uv2s) {
  27617. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27618. }
  27619. // uv3s
  27620. var uv3s = parsedVertexData.uv3s;
  27621. if (uv3s) {
  27622. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27623. }
  27624. // uv4s
  27625. var uv4s = parsedVertexData.uv4s;
  27626. if (uv4s) {
  27627. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27628. }
  27629. // uv5s
  27630. var uv5s = parsedVertexData.uv5s;
  27631. if (uv5s) {
  27632. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27633. }
  27634. // uv6s
  27635. var uv6s = parsedVertexData.uv6s;
  27636. if (uv6s) {
  27637. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27638. }
  27639. // colors
  27640. var colors = parsedVertexData.colors;
  27641. if (colors) {
  27642. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27643. }
  27644. // matricesIndices
  27645. var matricesIndices = parsedVertexData.matricesIndices;
  27646. if (matricesIndices) {
  27647. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27648. }
  27649. // matricesWeights
  27650. var matricesWeights = parsedVertexData.matricesWeights;
  27651. if (matricesWeights) {
  27652. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27653. }
  27654. // indices
  27655. var indices = parsedVertexData.indices;
  27656. if (indices) {
  27657. vertexData.indices = indices;
  27658. }
  27659. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27660. };
  27661. return VertexData;
  27662. })();
  27663. BABYLON.VertexData = VertexData;
  27664. })(BABYLON || (BABYLON = {}));
  27665. var BABYLON;
  27666. (function (BABYLON) {
  27667. var Tags = (function () {
  27668. function Tags() {
  27669. }
  27670. Tags.EnableFor = function (obj) {
  27671. obj._tags = obj._tags || {};
  27672. obj.hasTags = function () {
  27673. return Tags.HasTags(obj);
  27674. };
  27675. obj.addTags = function (tagsString) {
  27676. return Tags.AddTagsTo(obj, tagsString);
  27677. };
  27678. obj.removeTags = function (tagsString) {
  27679. return Tags.RemoveTagsFrom(obj, tagsString);
  27680. };
  27681. obj.matchesTagsQuery = function (tagsQuery) {
  27682. return Tags.MatchesQuery(obj, tagsQuery);
  27683. };
  27684. };
  27685. Tags.DisableFor = function (obj) {
  27686. delete obj._tags;
  27687. delete obj.hasTags;
  27688. delete obj.addTags;
  27689. delete obj.removeTags;
  27690. delete obj.matchesTagsQuery;
  27691. };
  27692. Tags.HasTags = function (obj) {
  27693. if (!obj._tags) {
  27694. return false;
  27695. }
  27696. return !BABYLON.Tools.IsEmpty(obj._tags);
  27697. };
  27698. Tags.GetTags = function (obj, asString) {
  27699. if (asString === void 0) { asString = true; }
  27700. if (!obj._tags) {
  27701. return null;
  27702. }
  27703. if (asString) {
  27704. var tagsArray = [];
  27705. for (var tag in obj._tags) {
  27706. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  27707. tagsArray.push(tag);
  27708. }
  27709. }
  27710. return tagsArray.join(" ");
  27711. }
  27712. else {
  27713. return obj._tags;
  27714. }
  27715. };
  27716. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27717. // a tag cannot start with '||', '&&', and '!'
  27718. // it cannot contain whitespaces
  27719. Tags.AddTagsTo = function (obj, tagsString) {
  27720. if (!tagsString) {
  27721. return;
  27722. }
  27723. if (typeof tagsString !== "string") {
  27724. return;
  27725. }
  27726. var tags = tagsString.split(" ");
  27727. for (var t in tags) {
  27728. Tags._AddTagTo(obj, tags[t]);
  27729. }
  27730. };
  27731. Tags._AddTagTo = function (obj, tag) {
  27732. tag = tag.trim();
  27733. if (tag === "" || tag === "true" || tag === "false") {
  27734. return;
  27735. }
  27736. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27737. return;
  27738. }
  27739. Tags.EnableFor(obj);
  27740. obj._tags[tag] = true;
  27741. };
  27742. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27743. if (!Tags.HasTags(obj)) {
  27744. return;
  27745. }
  27746. var tags = tagsString.split(" ");
  27747. for (var t in tags) {
  27748. Tags._RemoveTagFrom(obj, tags[t]);
  27749. }
  27750. };
  27751. Tags._RemoveTagFrom = function (obj, tag) {
  27752. delete obj._tags[tag];
  27753. };
  27754. Tags.MatchesQuery = function (obj, tagsQuery) {
  27755. if (tagsQuery === undefined) {
  27756. return true;
  27757. }
  27758. if (tagsQuery === "") {
  27759. return Tags.HasTags(obj);
  27760. }
  27761. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27762. };
  27763. return Tags;
  27764. })();
  27765. BABYLON.Tags = Tags;
  27766. })(BABYLON || (BABYLON = {}));
  27767. var BABYLON;
  27768. (function (BABYLON) {
  27769. var Internals;
  27770. (function (Internals) {
  27771. var AndOrNotEvaluator = (function () {
  27772. function AndOrNotEvaluator() {
  27773. }
  27774. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27775. if (!query.match(/\([^\(\)]*\)/g)) {
  27776. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27777. }
  27778. else {
  27779. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27780. // remove parenthesis
  27781. r = r.slice(1, r.length - 1);
  27782. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27783. });
  27784. }
  27785. if (query === "true") {
  27786. return true;
  27787. }
  27788. if (query === "false") {
  27789. return false;
  27790. }
  27791. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27792. };
  27793. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27794. evaluateCallback = evaluateCallback || (function (r) {
  27795. return r === "true" ? true : false;
  27796. });
  27797. var result;
  27798. var or = parenthesisContent.split("||");
  27799. for (var i in or) {
  27800. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27801. var and = ori.split("&&");
  27802. if (and.length > 1) {
  27803. for (var j = 0; j < and.length; ++j) {
  27804. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27805. if (andj !== "true" && andj !== "false") {
  27806. if (andj[0] === "!") {
  27807. result = !evaluateCallback(andj.substring(1));
  27808. }
  27809. else {
  27810. result = evaluateCallback(andj);
  27811. }
  27812. }
  27813. else {
  27814. result = andj === "true" ? true : false;
  27815. }
  27816. if (!result) {
  27817. ori = "false";
  27818. break;
  27819. }
  27820. }
  27821. }
  27822. if (result || ori === "true") {
  27823. result = true;
  27824. break;
  27825. }
  27826. // result equals false (or undefined)
  27827. if (ori !== "true" && ori !== "false") {
  27828. if (ori[0] === "!") {
  27829. result = !evaluateCallback(ori.substring(1));
  27830. }
  27831. else {
  27832. result = evaluateCallback(ori);
  27833. }
  27834. }
  27835. else {
  27836. result = ori === "true" ? true : false;
  27837. }
  27838. }
  27839. // the whole parenthesis scope is replaced by 'true' or 'false'
  27840. return result ? "true" : "false";
  27841. };
  27842. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27843. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27844. // remove whitespaces
  27845. r = r.replace(/[\s]/g, function () { return ""; });
  27846. return r.length % 2 ? "!" : "";
  27847. });
  27848. booleanString = booleanString.trim();
  27849. if (booleanString === "!true") {
  27850. booleanString = "false";
  27851. }
  27852. else if (booleanString === "!false") {
  27853. booleanString = "true";
  27854. }
  27855. return booleanString;
  27856. };
  27857. return AndOrNotEvaluator;
  27858. })();
  27859. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27860. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27861. })(BABYLON || (BABYLON = {}));
  27862. var BABYLON;
  27863. (function (BABYLON) {
  27864. var PostProcessRenderPass = (function () {
  27865. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27866. this._enabled = true;
  27867. this._refCount = 0;
  27868. this._name = name;
  27869. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27870. this.setRenderList(renderList);
  27871. this._renderTexture.onBeforeRender = beforeRender;
  27872. this._renderTexture.onAfterRender = afterRender;
  27873. this._scene = scene;
  27874. this._renderList = renderList;
  27875. }
  27876. // private
  27877. PostProcessRenderPass.prototype._incRefCount = function () {
  27878. if (this._refCount === 0) {
  27879. this._scene.customRenderTargets.push(this._renderTexture);
  27880. }
  27881. return ++this._refCount;
  27882. };
  27883. PostProcessRenderPass.prototype._decRefCount = function () {
  27884. this._refCount--;
  27885. if (this._refCount <= 0) {
  27886. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27887. }
  27888. return this._refCount;
  27889. };
  27890. PostProcessRenderPass.prototype._update = function () {
  27891. this.setRenderList(this._renderList);
  27892. };
  27893. // public
  27894. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27895. this._renderTexture.renderList = renderList;
  27896. };
  27897. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27898. return this._renderTexture;
  27899. };
  27900. return PostProcessRenderPass;
  27901. })();
  27902. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27903. })(BABYLON || (BABYLON = {}));
  27904. var BABYLON;
  27905. (function (BABYLON) {
  27906. var PostProcessRenderEffect = (function () {
  27907. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27908. this._engine = engine;
  27909. this._name = name;
  27910. this._singleInstance = singleInstance || true;
  27911. this._getPostProcess = getPostProcess;
  27912. this._cameras = [];
  27913. this._indicesForCamera = [];
  27914. this._postProcesses = {};
  27915. this._renderPasses = {};
  27916. this._renderEffectAsPasses = {};
  27917. }
  27918. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  27919. get: function () {
  27920. for (var index in this._postProcesses) {
  27921. if (!this._postProcesses[index].isSupported) {
  27922. return false;
  27923. }
  27924. }
  27925. return true;
  27926. },
  27927. enumerable: true,
  27928. configurable: true
  27929. });
  27930. PostProcessRenderEffect.prototype._update = function () {
  27931. for (var renderPassName in this._renderPasses) {
  27932. this._renderPasses[renderPassName]._update();
  27933. }
  27934. };
  27935. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27936. this._renderPasses[renderPass._name] = renderPass;
  27937. this._linkParameters();
  27938. };
  27939. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27940. delete this._renderPasses[renderPass._name];
  27941. this._linkParameters();
  27942. };
  27943. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27944. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27945. this._linkParameters();
  27946. };
  27947. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27948. for (var renderPassName in this._renderPasses) {
  27949. if (renderPassName === passName) {
  27950. return this._renderPasses[passName];
  27951. }
  27952. }
  27953. };
  27954. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27955. this._renderPasses = {};
  27956. this._linkParameters();
  27957. };
  27958. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27959. var cameraKey;
  27960. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27961. for (var i = 0; i < _cam.length; i++) {
  27962. var camera = _cam[i];
  27963. var cameraName = camera.name;
  27964. if (this._singleInstance) {
  27965. cameraKey = 0;
  27966. }
  27967. else {
  27968. cameraKey = cameraName;
  27969. }
  27970. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27971. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27972. if (!this._indicesForCamera[cameraName]) {
  27973. this._indicesForCamera[cameraName] = [];
  27974. }
  27975. this._indicesForCamera[cameraName].push(index);
  27976. if (this._cameras.indexOf(camera) === -1) {
  27977. this._cameras[cameraName] = camera;
  27978. }
  27979. for (var passName in this._renderPasses) {
  27980. this._renderPasses[passName]._incRefCount();
  27981. }
  27982. }
  27983. this._linkParameters();
  27984. };
  27985. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27986. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27987. for (var i = 0; i < _cam.length; i++) {
  27988. var camera = _cam[i];
  27989. var cameraName = camera.name;
  27990. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27991. var index = this._cameras.indexOf(cameraName);
  27992. this._indicesForCamera.splice(index, 1);
  27993. this._cameras.splice(index, 1);
  27994. for (var passName in this._renderPasses) {
  27995. this._renderPasses[passName]._decRefCount();
  27996. }
  27997. }
  27998. };
  27999. PostProcessRenderEffect.prototype._enable = function (cameras) {
  28000. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28001. for (var i = 0; i < _cam.length; i++) {
  28002. var camera = _cam[i];
  28003. var cameraName = camera.name;
  28004. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  28005. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  28006. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  28007. }
  28008. }
  28009. for (var passName in this._renderPasses) {
  28010. this._renderPasses[passName]._incRefCount();
  28011. }
  28012. }
  28013. };
  28014. PostProcessRenderEffect.prototype._disable = function (cameras) {
  28015. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28016. for (var i = 0; i < _cam.length; i++) {
  28017. var camera = _cam[i];
  28018. var cameraName = camera.Name;
  28019. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28020. for (var passName in this._renderPasses) {
  28021. this._renderPasses[passName]._decRefCount();
  28022. }
  28023. }
  28024. };
  28025. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  28026. if (this._singleInstance) {
  28027. return this._postProcesses[0];
  28028. }
  28029. else {
  28030. return this._postProcesses[camera.name];
  28031. }
  28032. };
  28033. PostProcessRenderEffect.prototype._linkParameters = function () {
  28034. var _this = this;
  28035. for (var index in this._postProcesses) {
  28036. if (this.applyParameters) {
  28037. this.applyParameters(this._postProcesses[index]);
  28038. }
  28039. this._postProcesses[index].onBeforeRender = function (effect) {
  28040. _this._linkTextures(effect);
  28041. };
  28042. }
  28043. };
  28044. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  28045. for (var renderPassName in this._renderPasses) {
  28046. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  28047. }
  28048. for (var renderEffectName in this._renderEffectAsPasses) {
  28049. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  28050. }
  28051. };
  28052. return PostProcessRenderEffect;
  28053. })();
  28054. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  28055. })(BABYLON || (BABYLON = {}));
  28056. var BABYLON;
  28057. (function (BABYLON) {
  28058. var PostProcessRenderPipeline = (function () {
  28059. function PostProcessRenderPipeline(engine, name) {
  28060. this._engine = engine;
  28061. this._name = name;
  28062. this._renderEffects = {};
  28063. this._renderEffectsForIsolatedPass = {};
  28064. this._cameras = [];
  28065. }
  28066. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  28067. get: function () {
  28068. for (var renderEffectName in this._renderEffects) {
  28069. if (!this._renderEffects[renderEffectName].isSupported) {
  28070. return false;
  28071. }
  28072. }
  28073. return true;
  28074. },
  28075. enumerable: true,
  28076. configurable: true
  28077. });
  28078. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  28079. this._renderEffects[renderEffect._name] = renderEffect;
  28080. };
  28081. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  28082. var renderEffects = this._renderEffects[renderEffectName];
  28083. if (!renderEffects) {
  28084. return;
  28085. }
  28086. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28087. };
  28088. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  28089. var renderEffects = this._renderEffects[renderEffectName];
  28090. if (!renderEffects) {
  28091. return;
  28092. }
  28093. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28094. };
  28095. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  28096. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28097. var indicesToDelete = [];
  28098. var i;
  28099. for (i = 0; i < _cam.length; i++) {
  28100. var camera = _cam[i];
  28101. var cameraName = camera.name;
  28102. if (this._cameras.indexOf(camera) === -1) {
  28103. this._cameras[cameraName] = camera;
  28104. }
  28105. else if (unique) {
  28106. indicesToDelete.push(i);
  28107. }
  28108. }
  28109. for (i = 0; i < indicesToDelete.length; i++) {
  28110. cameras.splice(indicesToDelete[i], 1);
  28111. }
  28112. for (var renderEffectName in this._renderEffects) {
  28113. this._renderEffects[renderEffectName]._attachCameras(_cam);
  28114. }
  28115. };
  28116. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  28117. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28118. for (var renderEffectName in this._renderEffects) {
  28119. this._renderEffects[renderEffectName]._detachCameras(_cam);
  28120. }
  28121. for (var i = 0; i < _cam.length; i++) {
  28122. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  28123. }
  28124. };
  28125. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  28126. var _this = this;
  28127. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28128. var pass = null;
  28129. var renderEffectName;
  28130. for (renderEffectName in this._renderEffects) {
  28131. pass = this._renderEffects[renderEffectName].getPass(passName);
  28132. if (pass != null) {
  28133. break;
  28134. }
  28135. }
  28136. if (pass === null) {
  28137. return;
  28138. }
  28139. for (renderEffectName in this._renderEffects) {
  28140. this._renderEffects[renderEffectName]._disable(_cam);
  28141. }
  28142. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  28143. for (var i = 0; i < _cam.length; i++) {
  28144. var camera = _cam[i];
  28145. var cameraName = camera.name;
  28146. 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); });
  28147. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  28148. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  28149. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  28150. }
  28151. };
  28152. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  28153. var _this = this;
  28154. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28155. for (var i = 0; i < _cam.length; i++) {
  28156. var camera = _cam[i];
  28157. var cameraName = camera.name;
  28158. 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); });
  28159. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  28160. }
  28161. for (var renderEffectName in this._renderEffects) {
  28162. this._renderEffects[renderEffectName]._enable(_cam);
  28163. }
  28164. };
  28165. PostProcessRenderPipeline.prototype._update = function () {
  28166. for (var renderEffectName in this._renderEffects) {
  28167. this._renderEffects[renderEffectName]._update();
  28168. }
  28169. for (var i = 0; i < this._cameras.length; i++) {
  28170. var cameraName = this._cameras[i].name;
  28171. if (this._renderEffectsForIsolatedPass[cameraName]) {
  28172. this._renderEffectsForIsolatedPass[cameraName]._update();
  28173. }
  28174. }
  28175. };
  28176. PostProcessRenderPipeline.prototype.dispose = function () {
  28177. // Must be implemented by children
  28178. };
  28179. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  28180. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  28181. return PostProcessRenderPipeline;
  28182. })();
  28183. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  28184. })(BABYLON || (BABYLON = {}));
  28185. var BABYLON;
  28186. (function (BABYLON) {
  28187. var PostProcessRenderPipelineManager = (function () {
  28188. function PostProcessRenderPipelineManager() {
  28189. this._renderPipelines = {};
  28190. }
  28191. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  28192. this._renderPipelines[renderPipeline._name] = renderPipeline;
  28193. };
  28194. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  28195. var renderPipeline = this._renderPipelines[renderPipelineName];
  28196. if (!renderPipeline) {
  28197. return;
  28198. }
  28199. renderPipeline._attachCameras(cameras, unique);
  28200. };
  28201. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  28202. var renderPipeline = this._renderPipelines[renderPipelineName];
  28203. if (!renderPipeline) {
  28204. return;
  28205. }
  28206. renderPipeline._detachCameras(cameras);
  28207. };
  28208. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28209. var renderPipeline = this._renderPipelines[renderPipelineName];
  28210. if (!renderPipeline) {
  28211. return;
  28212. }
  28213. renderPipeline._enableEffect(renderEffectName, cameras);
  28214. };
  28215. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28216. var renderPipeline = this._renderPipelines[renderPipelineName];
  28217. if (!renderPipeline) {
  28218. return;
  28219. }
  28220. renderPipeline._disableEffect(renderEffectName, cameras);
  28221. };
  28222. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  28223. var renderPipeline = this._renderPipelines[renderPipelineName];
  28224. if (!renderPipeline) {
  28225. return;
  28226. }
  28227. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  28228. };
  28229. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  28230. var renderPipeline = this._renderPipelines[renderPipelineName];
  28231. if (!renderPipeline) {
  28232. return;
  28233. }
  28234. renderPipeline._disableDisplayOnlyPass(cameras);
  28235. };
  28236. PostProcessRenderPipelineManager.prototype.update = function () {
  28237. for (var renderPipelineName in this._renderPipelines) {
  28238. var pipeline = this._renderPipelines[renderPipelineName];
  28239. if (!pipeline.isSupported) {
  28240. pipeline.dispose();
  28241. delete this._renderPipelines[renderPipelineName];
  28242. }
  28243. else {
  28244. pipeline._update();
  28245. }
  28246. }
  28247. };
  28248. return PostProcessRenderPipelineManager;
  28249. })();
  28250. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  28251. })(BABYLON || (BABYLON = {}));
  28252. var BABYLON;
  28253. (function (BABYLON) {
  28254. var BoundingBoxRenderer = (function () {
  28255. function BoundingBoxRenderer(scene) {
  28256. this.frontColor = new BABYLON.Color3(1, 1, 1);
  28257. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  28258. this.showBackLines = true;
  28259. this.renderList = new BABYLON.SmartArray(32);
  28260. this._scene = scene;
  28261. }
  28262. BoundingBoxRenderer.prototype._prepareRessources = function () {
  28263. if (this._colorShader) {
  28264. return;
  28265. }
  28266. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  28267. attributes: ["position"],
  28268. uniforms: ["worldViewProjection", "color"]
  28269. });
  28270. var engine = this._scene.getEngine();
  28271. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  28272. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  28273. 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]);
  28274. };
  28275. BoundingBoxRenderer.prototype.reset = function () {
  28276. this.renderList.reset();
  28277. };
  28278. BoundingBoxRenderer.prototype.render = function () {
  28279. if (this.renderList.length === 0) {
  28280. return;
  28281. }
  28282. this._prepareRessources();
  28283. if (!this._colorShader.isReady()) {
  28284. return;
  28285. }
  28286. var engine = this._scene.getEngine();
  28287. engine.setDepthWrite(false);
  28288. this._colorShader._preBind();
  28289. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  28290. var boundingBox = this.renderList.data[boundingBoxIndex];
  28291. var min = boundingBox.minimum;
  28292. var max = boundingBox.maximum;
  28293. var diff = max.subtract(min);
  28294. var median = min.add(diff.scale(0.5));
  28295. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  28296. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  28297. .multiply(boundingBox.getWorldMatrix());
  28298. // VBOs
  28299. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  28300. if (this.showBackLines) {
  28301. // Back
  28302. engine.setDepthFunctionToGreaterOrEqual();
  28303. this._scene.resetCachedMaterial();
  28304. this._colorShader.setColor4("color", this.backColor.toColor4());
  28305. this._colorShader.bind(worldMatrix);
  28306. // Draw order
  28307. engine.draw(false, 0, 24);
  28308. }
  28309. // Front
  28310. engine.setDepthFunctionToLess();
  28311. this._scene.resetCachedMaterial();
  28312. this._colorShader.setColor4("color", this.frontColor.toColor4());
  28313. this._colorShader.bind(worldMatrix);
  28314. // Draw order
  28315. engine.draw(false, 0, 24);
  28316. }
  28317. this._colorShader.unbind();
  28318. engine.setDepthFunctionToLessOrEqual();
  28319. engine.setDepthWrite(true);
  28320. };
  28321. BoundingBoxRenderer.prototype.dispose = function () {
  28322. if (!this._colorShader) {
  28323. return;
  28324. }
  28325. this._colorShader.dispose();
  28326. this._vb.dispose();
  28327. this._scene.getEngine()._releaseBuffer(this._ib);
  28328. };
  28329. return BoundingBoxRenderer;
  28330. })();
  28331. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  28332. })(BABYLON || (BABYLON = {}));
  28333. var BABYLON;
  28334. (function (BABYLON) {
  28335. var Condition = (function () {
  28336. function Condition(actionManager) {
  28337. this._actionManager = actionManager;
  28338. }
  28339. Condition.prototype.isValid = function () {
  28340. return true;
  28341. };
  28342. Condition.prototype._getProperty = function (propertyPath) {
  28343. return this._actionManager._getProperty(propertyPath);
  28344. };
  28345. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  28346. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28347. };
  28348. return Condition;
  28349. })();
  28350. BABYLON.Condition = Condition;
  28351. var ValueCondition = (function (_super) {
  28352. __extends(ValueCondition, _super);
  28353. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  28354. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  28355. _super.call(this, actionManager);
  28356. this.propertyPath = propertyPath;
  28357. this.value = value;
  28358. this.operator = operator;
  28359. this._target = this._getEffectiveTarget(target, this.propertyPath);
  28360. this._property = this._getProperty(this.propertyPath);
  28361. }
  28362. Object.defineProperty(ValueCondition, "IsEqual", {
  28363. get: function () {
  28364. return ValueCondition._IsEqual;
  28365. },
  28366. enumerable: true,
  28367. configurable: true
  28368. });
  28369. Object.defineProperty(ValueCondition, "IsDifferent", {
  28370. get: function () {
  28371. return ValueCondition._IsDifferent;
  28372. },
  28373. enumerable: true,
  28374. configurable: true
  28375. });
  28376. Object.defineProperty(ValueCondition, "IsGreater", {
  28377. get: function () {
  28378. return ValueCondition._IsGreater;
  28379. },
  28380. enumerable: true,
  28381. configurable: true
  28382. });
  28383. Object.defineProperty(ValueCondition, "IsLesser", {
  28384. get: function () {
  28385. return ValueCondition._IsLesser;
  28386. },
  28387. enumerable: true,
  28388. configurable: true
  28389. });
  28390. // Methods
  28391. ValueCondition.prototype.isValid = function () {
  28392. switch (this.operator) {
  28393. case ValueCondition.IsGreater:
  28394. return this._target[this._property] > this.value;
  28395. case ValueCondition.IsLesser:
  28396. return this._target[this._property] < this.value;
  28397. case ValueCondition.IsEqual:
  28398. case ValueCondition.IsDifferent:
  28399. var check;
  28400. if (this.value.equals) {
  28401. check = this.value.equals(this._target[this._property]);
  28402. }
  28403. else {
  28404. check = this.value === this._target[this._property];
  28405. }
  28406. return this.operator === ValueCondition.IsEqual ? check : !check;
  28407. }
  28408. return false;
  28409. };
  28410. // Statics
  28411. ValueCondition._IsEqual = 0;
  28412. ValueCondition._IsDifferent = 1;
  28413. ValueCondition._IsGreater = 2;
  28414. ValueCondition._IsLesser = 3;
  28415. return ValueCondition;
  28416. })(Condition);
  28417. BABYLON.ValueCondition = ValueCondition;
  28418. var PredicateCondition = (function (_super) {
  28419. __extends(PredicateCondition, _super);
  28420. function PredicateCondition(actionManager, predicate) {
  28421. _super.call(this, actionManager);
  28422. this.predicate = predicate;
  28423. }
  28424. PredicateCondition.prototype.isValid = function () {
  28425. return this.predicate();
  28426. };
  28427. return PredicateCondition;
  28428. })(Condition);
  28429. BABYLON.PredicateCondition = PredicateCondition;
  28430. var StateCondition = (function (_super) {
  28431. __extends(StateCondition, _super);
  28432. function StateCondition(actionManager, target, value) {
  28433. _super.call(this, actionManager);
  28434. this.value = value;
  28435. this._target = target;
  28436. }
  28437. // Methods
  28438. StateCondition.prototype.isValid = function () {
  28439. return this._target.state === this.value;
  28440. };
  28441. return StateCondition;
  28442. })(Condition);
  28443. BABYLON.StateCondition = StateCondition;
  28444. })(BABYLON || (BABYLON = {}));
  28445. var BABYLON;
  28446. (function (BABYLON) {
  28447. var Action = (function () {
  28448. function Action(triggerOptions, condition) {
  28449. this.triggerOptions = triggerOptions;
  28450. if (triggerOptions.parameter) {
  28451. this.trigger = triggerOptions.trigger;
  28452. this._triggerParameter = triggerOptions.parameter;
  28453. }
  28454. else {
  28455. this.trigger = triggerOptions;
  28456. }
  28457. this._nextActiveAction = this;
  28458. this._condition = condition;
  28459. }
  28460. // Methods
  28461. Action.prototype._prepare = function () {
  28462. };
  28463. Action.prototype.getTriggerParameter = function () {
  28464. return this._triggerParameter;
  28465. };
  28466. Action.prototype._executeCurrent = function (evt) {
  28467. if (this._nextActiveAction._condition) {
  28468. var condition = this._nextActiveAction._condition;
  28469. var currentRenderId = this._actionManager.getScene().getRenderId();
  28470. // We cache the current evaluation for the current frame
  28471. if (condition._evaluationId === currentRenderId) {
  28472. if (!condition._currentResult) {
  28473. return;
  28474. }
  28475. }
  28476. else {
  28477. condition._evaluationId = currentRenderId;
  28478. if (!condition.isValid()) {
  28479. condition._currentResult = false;
  28480. return;
  28481. }
  28482. condition._currentResult = true;
  28483. }
  28484. }
  28485. this._nextActiveAction.execute(evt);
  28486. this.skipToNextActiveAction();
  28487. };
  28488. Action.prototype.execute = function (evt) {
  28489. };
  28490. Action.prototype.skipToNextActiveAction = function () {
  28491. if (this._nextActiveAction._child) {
  28492. if (!this._nextActiveAction._child._actionManager) {
  28493. this._nextActiveAction._child._actionManager = this._actionManager;
  28494. }
  28495. this._nextActiveAction = this._nextActiveAction._child;
  28496. }
  28497. else {
  28498. this._nextActiveAction = this;
  28499. }
  28500. };
  28501. Action.prototype.then = function (action) {
  28502. this._child = action;
  28503. action._actionManager = this._actionManager;
  28504. action._prepare();
  28505. return action;
  28506. };
  28507. Action.prototype._getProperty = function (propertyPath) {
  28508. return this._actionManager._getProperty(propertyPath);
  28509. };
  28510. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28511. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28512. };
  28513. return Action;
  28514. })();
  28515. BABYLON.Action = Action;
  28516. })(BABYLON || (BABYLON = {}));
  28517. var BABYLON;
  28518. (function (BABYLON) {
  28519. /**
  28520. * ActionEvent is the event beint sent when an action is triggered.
  28521. */
  28522. var ActionEvent = (function () {
  28523. /**
  28524. * @constructor
  28525. * @param source The mesh or sprite that triggered the action.
  28526. * @param pointerX The X mouse cursor position at the time of the event
  28527. * @param pointerY The Y mouse cursor position at the time of the event
  28528. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28529. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28530. */
  28531. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28532. this.source = source;
  28533. this.pointerX = pointerX;
  28534. this.pointerY = pointerY;
  28535. this.meshUnderPointer = meshUnderPointer;
  28536. this.sourceEvent = sourceEvent;
  28537. this.additionalData = additionalData;
  28538. }
  28539. /**
  28540. * Helper function to auto-create an ActionEvent from a source mesh.
  28541. * @param source The source mesh that triggered the event
  28542. * @param evt {Event} The original (browser) event
  28543. */
  28544. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28545. var scene = source.getScene();
  28546. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28547. };
  28548. /**
  28549. * Helper function to auto-create an ActionEvent from a source mesh.
  28550. * @param source The source sprite that triggered the event
  28551. * @param scene Scene associated with the sprite
  28552. * @param evt {Event} The original (browser) event
  28553. */
  28554. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  28555. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28556. };
  28557. /**
  28558. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28559. * @param scene the scene where the event occurred
  28560. * @param evt {Event} The original (browser) event
  28561. */
  28562. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28563. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28564. };
  28565. return ActionEvent;
  28566. })();
  28567. BABYLON.ActionEvent = ActionEvent;
  28568. /**
  28569. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28570. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28571. */
  28572. var ActionManager = (function () {
  28573. function ActionManager(scene) {
  28574. // Members
  28575. this.actions = new Array();
  28576. this._scene = scene;
  28577. scene._actionManagers.push(this);
  28578. }
  28579. Object.defineProperty(ActionManager, "NothingTrigger", {
  28580. get: function () {
  28581. return ActionManager._NothingTrigger;
  28582. },
  28583. enumerable: true,
  28584. configurable: true
  28585. });
  28586. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28587. get: function () {
  28588. return ActionManager._OnPickTrigger;
  28589. },
  28590. enumerable: true,
  28591. configurable: true
  28592. });
  28593. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28594. get: function () {
  28595. return ActionManager._OnLeftPickTrigger;
  28596. },
  28597. enumerable: true,
  28598. configurable: true
  28599. });
  28600. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28601. get: function () {
  28602. return ActionManager._OnRightPickTrigger;
  28603. },
  28604. enumerable: true,
  28605. configurable: true
  28606. });
  28607. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28608. get: function () {
  28609. return ActionManager._OnCenterPickTrigger;
  28610. },
  28611. enumerable: true,
  28612. configurable: true
  28613. });
  28614. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  28615. get: function () {
  28616. return ActionManager._OnPickDownTrigger;
  28617. },
  28618. enumerable: true,
  28619. configurable: true
  28620. });
  28621. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28622. get: function () {
  28623. return ActionManager._OnPickUpTrigger;
  28624. },
  28625. enumerable: true,
  28626. configurable: true
  28627. });
  28628. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  28629. /// This trigger will only be raised if you also declared a OnPickDown
  28630. get: function () {
  28631. return ActionManager._OnPickOutTrigger;
  28632. },
  28633. enumerable: true,
  28634. configurable: true
  28635. });
  28636. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  28637. get: function () {
  28638. return ActionManager._OnLongPressTrigger;
  28639. },
  28640. enumerable: true,
  28641. configurable: true
  28642. });
  28643. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28644. get: function () {
  28645. return ActionManager._OnPointerOverTrigger;
  28646. },
  28647. enumerable: true,
  28648. configurable: true
  28649. });
  28650. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28651. get: function () {
  28652. return ActionManager._OnPointerOutTrigger;
  28653. },
  28654. enumerable: true,
  28655. configurable: true
  28656. });
  28657. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28658. get: function () {
  28659. return ActionManager._OnEveryFrameTrigger;
  28660. },
  28661. enumerable: true,
  28662. configurable: true
  28663. });
  28664. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28665. get: function () {
  28666. return ActionManager._OnIntersectionEnterTrigger;
  28667. },
  28668. enumerable: true,
  28669. configurable: true
  28670. });
  28671. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28672. get: function () {
  28673. return ActionManager._OnIntersectionExitTrigger;
  28674. },
  28675. enumerable: true,
  28676. configurable: true
  28677. });
  28678. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28679. get: function () {
  28680. return ActionManager._OnKeyDownTrigger;
  28681. },
  28682. enumerable: true,
  28683. configurable: true
  28684. });
  28685. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28686. get: function () {
  28687. return ActionManager._OnKeyUpTrigger;
  28688. },
  28689. enumerable: true,
  28690. configurable: true
  28691. });
  28692. // Methods
  28693. ActionManager.prototype.dispose = function () {
  28694. var index = this._scene._actionManagers.indexOf(this);
  28695. if (index > -1) {
  28696. this._scene._actionManagers.splice(index, 1);
  28697. }
  28698. };
  28699. ActionManager.prototype.getScene = function () {
  28700. return this._scene;
  28701. };
  28702. /**
  28703. * Does this action manager handles actions of any of the given triggers
  28704. * @param {number[]} triggers - the triggers to be tested
  28705. * @return {boolean} whether one (or more) of the triggers is handeled
  28706. */
  28707. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28708. for (var index = 0; index < this.actions.length; index++) {
  28709. var action = this.actions[index];
  28710. if (triggers.indexOf(action.trigger) > -1) {
  28711. return true;
  28712. }
  28713. }
  28714. return false;
  28715. };
  28716. /**
  28717. * Does this action manager handles actions of a given trigger
  28718. * @param {number} trigger - the trigger to be tested
  28719. * @return {boolean} whether the trigger is handeled
  28720. */
  28721. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28722. for (var index = 0; index < this.actions.length; index++) {
  28723. var action = this.actions[index];
  28724. if (action.trigger === trigger) {
  28725. return true;
  28726. }
  28727. }
  28728. return false;
  28729. };
  28730. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28731. /**
  28732. * Does this action manager has pointer triggers
  28733. * @return {boolean} whether or not it has pointer triggers
  28734. */
  28735. get: function () {
  28736. for (var index = 0; index < this.actions.length; index++) {
  28737. var action = this.actions[index];
  28738. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28739. return true;
  28740. }
  28741. }
  28742. return false;
  28743. },
  28744. enumerable: true,
  28745. configurable: true
  28746. });
  28747. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28748. /**
  28749. * Does this action manager has pick triggers
  28750. * @return {boolean} whether or not it has pick triggers
  28751. */
  28752. get: function () {
  28753. for (var index = 0; index < this.actions.length; index++) {
  28754. var action = this.actions[index];
  28755. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  28756. return true;
  28757. }
  28758. }
  28759. return false;
  28760. },
  28761. enumerable: true,
  28762. configurable: true
  28763. });
  28764. /**
  28765. * Registers an action to this action manager
  28766. * @param {BABYLON.Action} action - the action to be registered
  28767. * @return {BABYLON.Action} the action amended (prepared) after registration
  28768. */
  28769. ActionManager.prototype.registerAction = function (action) {
  28770. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28771. if (this.getScene().actionManager !== this) {
  28772. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28773. return null;
  28774. }
  28775. }
  28776. this.actions.push(action);
  28777. action._actionManager = this;
  28778. action._prepare();
  28779. return action;
  28780. };
  28781. /**
  28782. * Process a specific trigger
  28783. * @param {number} trigger - the trigger to process
  28784. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28785. */
  28786. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28787. for (var index = 0; index < this.actions.length; index++) {
  28788. var action = this.actions[index];
  28789. if (action.trigger === trigger) {
  28790. if (trigger === ActionManager.OnKeyUpTrigger
  28791. || trigger === ActionManager.OnKeyDownTrigger) {
  28792. var parameter = action.getTriggerParameter();
  28793. if (parameter) {
  28794. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28795. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28796. if (actualkey !== parameter.toLowerCase()) {
  28797. continue;
  28798. }
  28799. }
  28800. }
  28801. action._executeCurrent(evt);
  28802. }
  28803. }
  28804. };
  28805. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28806. var properties = propertyPath.split(".");
  28807. for (var index = 0; index < properties.length - 1; index++) {
  28808. target = target[properties[index]];
  28809. }
  28810. return target;
  28811. };
  28812. ActionManager.prototype._getProperty = function (propertyPath) {
  28813. var properties = propertyPath.split(".");
  28814. return properties[properties.length - 1];
  28815. };
  28816. ActionManager.Parse = function (parsedActions, object, scene) {
  28817. var actionManager = new BABYLON.ActionManager(scene);
  28818. if (object === null)
  28819. scene.actionManager = actionManager;
  28820. else
  28821. object.actionManager = actionManager;
  28822. // instanciate a new object
  28823. var instanciate = function (name, params) {
  28824. var newInstance = Object.create(BABYLON[name].prototype);
  28825. newInstance.constructor.apply(newInstance, params);
  28826. return newInstance;
  28827. };
  28828. var parseParameter = function (name, value, target, propertyPath) {
  28829. if (propertyPath === null) {
  28830. // String, boolean or float
  28831. var floatValue = parseFloat(value);
  28832. if (value === "true" || value === "false")
  28833. return value === "true";
  28834. else
  28835. return isNaN(floatValue) ? value : floatValue;
  28836. }
  28837. var effectiveTarget = propertyPath.split(".");
  28838. var values = value.split(",");
  28839. // Get effective Target
  28840. for (var i = 0; i < effectiveTarget.length; i++) {
  28841. target = target[effectiveTarget[i]];
  28842. }
  28843. // Return appropriate value with its type
  28844. if (typeof (target) === "boolean")
  28845. return values[0] === "true";
  28846. if (typeof (target) === "string")
  28847. return values[0];
  28848. // Parameters with multiple values such as Vector3 etc.
  28849. var split = new Array();
  28850. for (var i = 0; i < values.length; i++)
  28851. split.push(parseFloat(values[i]));
  28852. if (target instanceof BABYLON.Vector3)
  28853. return BABYLON.Vector3.FromArray(split);
  28854. if (target instanceof BABYLON.Vector4)
  28855. return BABYLON.Vector4.FromArray(split);
  28856. if (target instanceof BABYLON.Color3)
  28857. return BABYLON.Color3.FromArray(split);
  28858. if (target instanceof BABYLON.Color4)
  28859. return BABYLON.Color4.FromArray(split);
  28860. return parseFloat(values[0]);
  28861. };
  28862. // traverse graph per trigger
  28863. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  28864. if (combineArray === void 0) { combineArray = null; }
  28865. if (parsedAction.detached)
  28866. return;
  28867. var parameters = new Array();
  28868. var target = null;
  28869. var propertyPath = null;
  28870. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  28871. // Parameters
  28872. if (parsedAction.type === 2)
  28873. parameters.push(actionManager);
  28874. else
  28875. parameters.push(trigger);
  28876. if (combine) {
  28877. var actions = new Array();
  28878. for (var j = 0; j < parsedAction.combine.length; j++) {
  28879. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  28880. }
  28881. parameters.push(actions);
  28882. }
  28883. else {
  28884. for (var i = 0; i < parsedAction.properties.length; i++) {
  28885. var value = parsedAction.properties[i].value;
  28886. var name = parsedAction.properties[i].name;
  28887. var targetType = parsedAction.properties[i].targetType;
  28888. if (name === "target")
  28889. if (targetType !== null && targetType === "SceneProperties")
  28890. value = target = scene;
  28891. else
  28892. value = target = scene.getNodeByName(value);
  28893. else if (name === "parent")
  28894. value = scene.getNodeByName(value);
  28895. else if (name === "sound")
  28896. value = scene.getSoundByName(value);
  28897. else if (name !== "propertyPath") {
  28898. if (parsedAction.type === 2 && name === "operator")
  28899. value = BABYLON.ValueCondition[value];
  28900. else
  28901. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  28902. }
  28903. else {
  28904. propertyPath = value;
  28905. }
  28906. parameters.push(value);
  28907. }
  28908. }
  28909. if (combineArray === null) {
  28910. parameters.push(condition);
  28911. }
  28912. else {
  28913. parameters.push(null);
  28914. }
  28915. // If interpolate value action
  28916. if (parsedAction.name === "InterpolateValueAction") {
  28917. var param = parameters[parameters.length - 2];
  28918. parameters[parameters.length - 1] = param;
  28919. parameters[parameters.length - 2] = condition;
  28920. }
  28921. // Action or condition(s) and not CombineAction
  28922. var newAction = instanciate(parsedAction.name, parameters);
  28923. if (newAction instanceof BABYLON.Condition && condition !== null) {
  28924. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  28925. if (action)
  28926. action.then(nothing);
  28927. else
  28928. actionManager.registerAction(nothing);
  28929. action = nothing;
  28930. }
  28931. if (combineArray === null) {
  28932. if (newAction instanceof BABYLON.Condition) {
  28933. condition = newAction;
  28934. newAction = action;
  28935. }
  28936. else {
  28937. condition = null;
  28938. if (action)
  28939. action.then(newAction);
  28940. else
  28941. actionManager.registerAction(newAction);
  28942. }
  28943. }
  28944. else {
  28945. combineArray.push(newAction);
  28946. }
  28947. for (var i = 0; i < parsedAction.children.length; i++)
  28948. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  28949. };
  28950. // triggers
  28951. for (var i = 0; i < parsedActions.children.length; i++) {
  28952. var triggerParams;
  28953. var trigger = parsedActions.children[i];
  28954. if (trigger.properties.length > 0) {
  28955. var param = trigger.properties[0].value;
  28956. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  28957. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  28958. }
  28959. else
  28960. triggerParams = BABYLON.ActionManager[trigger.name];
  28961. for (var j = 0; j < trigger.children.length; j++) {
  28962. if (!trigger.detached)
  28963. traverse(trigger.children[j], triggerParams, null, null);
  28964. }
  28965. }
  28966. };
  28967. // Statics
  28968. ActionManager._NothingTrigger = 0;
  28969. ActionManager._OnPickTrigger = 1;
  28970. ActionManager._OnLeftPickTrigger = 2;
  28971. ActionManager._OnRightPickTrigger = 3;
  28972. ActionManager._OnCenterPickTrigger = 4;
  28973. ActionManager._OnPickDownTrigger = 5;
  28974. ActionManager._OnPickUpTrigger = 6;
  28975. ActionManager._OnLongPressTrigger = 7;
  28976. ActionManager._OnPointerOverTrigger = 8;
  28977. ActionManager._OnPointerOutTrigger = 9;
  28978. ActionManager._OnEveryFrameTrigger = 10;
  28979. ActionManager._OnIntersectionEnterTrigger = 11;
  28980. ActionManager._OnIntersectionExitTrigger = 12;
  28981. ActionManager._OnKeyDownTrigger = 13;
  28982. ActionManager._OnKeyUpTrigger = 14;
  28983. ActionManager._OnPickOutTrigger = 15;
  28984. ActionManager.DragMovementThreshold = 10; // in pixels
  28985. ActionManager.LongPressDelay = 500; // in milliseconds
  28986. return ActionManager;
  28987. })();
  28988. BABYLON.ActionManager = ActionManager;
  28989. })(BABYLON || (BABYLON = {}));
  28990. var BABYLON;
  28991. (function (BABYLON) {
  28992. var InterpolateValueAction = (function (_super) {
  28993. __extends(InterpolateValueAction, _super);
  28994. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  28995. if (duration === void 0) { duration = 1000; }
  28996. _super.call(this, triggerOptions, condition);
  28997. this.propertyPath = propertyPath;
  28998. this.value = value;
  28999. this.duration = duration;
  29000. this.stopOtherAnimations = stopOtherAnimations;
  29001. this.onInterpolationDone = onInterpolationDone;
  29002. this._target = target;
  29003. }
  29004. InterpolateValueAction.prototype._prepare = function () {
  29005. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29006. this._property = this._getProperty(this.propertyPath);
  29007. };
  29008. InterpolateValueAction.prototype.execute = function () {
  29009. var scene = this._actionManager.getScene();
  29010. var keys = [
  29011. {
  29012. frame: 0,
  29013. value: this._target[this._property]
  29014. }, {
  29015. frame: 100,
  29016. value: this.value
  29017. }
  29018. ];
  29019. var dataType;
  29020. if (typeof this.value === "number") {
  29021. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  29022. }
  29023. else if (this.value instanceof BABYLON.Color3) {
  29024. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  29025. }
  29026. else if (this.value instanceof BABYLON.Vector3) {
  29027. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  29028. }
  29029. else if (this.value instanceof BABYLON.Matrix) {
  29030. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  29031. }
  29032. else if (this.value instanceof BABYLON.Quaternion) {
  29033. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  29034. }
  29035. else {
  29036. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  29037. return;
  29038. }
  29039. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  29040. animation.setKeys(keys);
  29041. if (this.stopOtherAnimations) {
  29042. scene.stopAnimation(this._target);
  29043. }
  29044. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  29045. };
  29046. return InterpolateValueAction;
  29047. })(BABYLON.Action);
  29048. BABYLON.InterpolateValueAction = InterpolateValueAction;
  29049. })(BABYLON || (BABYLON = {}));
  29050. var BABYLON;
  29051. (function (BABYLON) {
  29052. var SwitchBooleanAction = (function (_super) {
  29053. __extends(SwitchBooleanAction, _super);
  29054. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  29055. _super.call(this, triggerOptions, condition);
  29056. this.propertyPath = propertyPath;
  29057. this._target = target;
  29058. }
  29059. SwitchBooleanAction.prototype._prepare = function () {
  29060. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29061. this._property = this._getProperty(this.propertyPath);
  29062. };
  29063. SwitchBooleanAction.prototype.execute = function () {
  29064. this._target[this._property] = !this._target[this._property];
  29065. };
  29066. return SwitchBooleanAction;
  29067. })(BABYLON.Action);
  29068. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  29069. var SetStateAction = (function (_super) {
  29070. __extends(SetStateAction, _super);
  29071. function SetStateAction(triggerOptions, target, value, condition) {
  29072. _super.call(this, triggerOptions, condition);
  29073. this.value = value;
  29074. this._target = target;
  29075. }
  29076. SetStateAction.prototype.execute = function () {
  29077. this._target.state = this.value;
  29078. };
  29079. return SetStateAction;
  29080. })(BABYLON.Action);
  29081. BABYLON.SetStateAction = SetStateAction;
  29082. var SetValueAction = (function (_super) {
  29083. __extends(SetValueAction, _super);
  29084. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  29085. _super.call(this, triggerOptions, condition);
  29086. this.propertyPath = propertyPath;
  29087. this.value = value;
  29088. this._target = target;
  29089. }
  29090. SetValueAction.prototype._prepare = function () {
  29091. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29092. this._property = this._getProperty(this.propertyPath);
  29093. };
  29094. SetValueAction.prototype.execute = function () {
  29095. this._target[this._property] = this.value;
  29096. };
  29097. return SetValueAction;
  29098. })(BABYLON.Action);
  29099. BABYLON.SetValueAction = SetValueAction;
  29100. var IncrementValueAction = (function (_super) {
  29101. __extends(IncrementValueAction, _super);
  29102. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  29103. _super.call(this, triggerOptions, condition);
  29104. this.propertyPath = propertyPath;
  29105. this.value = value;
  29106. this._target = target;
  29107. }
  29108. IncrementValueAction.prototype._prepare = function () {
  29109. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29110. this._property = this._getProperty(this.propertyPath);
  29111. if (typeof this._target[this._property] !== "number") {
  29112. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  29113. }
  29114. };
  29115. IncrementValueAction.prototype.execute = function () {
  29116. this._target[this._property] += this.value;
  29117. };
  29118. return IncrementValueAction;
  29119. })(BABYLON.Action);
  29120. BABYLON.IncrementValueAction = IncrementValueAction;
  29121. var PlayAnimationAction = (function (_super) {
  29122. __extends(PlayAnimationAction, _super);
  29123. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  29124. _super.call(this, triggerOptions, condition);
  29125. this.from = from;
  29126. this.to = to;
  29127. this.loop = loop;
  29128. this._target = target;
  29129. }
  29130. PlayAnimationAction.prototype._prepare = function () {
  29131. };
  29132. PlayAnimationAction.prototype.execute = function () {
  29133. var scene = this._actionManager.getScene();
  29134. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  29135. };
  29136. return PlayAnimationAction;
  29137. })(BABYLON.Action);
  29138. BABYLON.PlayAnimationAction = PlayAnimationAction;
  29139. var StopAnimationAction = (function (_super) {
  29140. __extends(StopAnimationAction, _super);
  29141. function StopAnimationAction(triggerOptions, target, condition) {
  29142. _super.call(this, triggerOptions, condition);
  29143. this._target = target;
  29144. }
  29145. StopAnimationAction.prototype._prepare = function () {
  29146. };
  29147. StopAnimationAction.prototype.execute = function () {
  29148. var scene = this._actionManager.getScene();
  29149. scene.stopAnimation(this._target);
  29150. };
  29151. return StopAnimationAction;
  29152. })(BABYLON.Action);
  29153. BABYLON.StopAnimationAction = StopAnimationAction;
  29154. var DoNothingAction = (function (_super) {
  29155. __extends(DoNothingAction, _super);
  29156. function DoNothingAction(triggerOptions, condition) {
  29157. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  29158. _super.call(this, triggerOptions, condition);
  29159. }
  29160. DoNothingAction.prototype.execute = function () {
  29161. };
  29162. return DoNothingAction;
  29163. })(BABYLON.Action);
  29164. BABYLON.DoNothingAction = DoNothingAction;
  29165. var CombineAction = (function (_super) {
  29166. __extends(CombineAction, _super);
  29167. function CombineAction(triggerOptions, children, condition) {
  29168. _super.call(this, triggerOptions, condition);
  29169. this.children = children;
  29170. }
  29171. CombineAction.prototype._prepare = function () {
  29172. for (var index = 0; index < this.children.length; index++) {
  29173. this.children[index]._actionManager = this._actionManager;
  29174. this.children[index]._prepare();
  29175. }
  29176. };
  29177. CombineAction.prototype.execute = function (evt) {
  29178. for (var index = 0; index < this.children.length; index++) {
  29179. this.children[index].execute(evt);
  29180. }
  29181. };
  29182. return CombineAction;
  29183. })(BABYLON.Action);
  29184. BABYLON.CombineAction = CombineAction;
  29185. var ExecuteCodeAction = (function (_super) {
  29186. __extends(ExecuteCodeAction, _super);
  29187. function ExecuteCodeAction(triggerOptions, func, condition) {
  29188. _super.call(this, triggerOptions, condition);
  29189. this.func = func;
  29190. }
  29191. ExecuteCodeAction.prototype.execute = function (evt) {
  29192. this.func(evt);
  29193. };
  29194. return ExecuteCodeAction;
  29195. })(BABYLON.Action);
  29196. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  29197. var SetParentAction = (function (_super) {
  29198. __extends(SetParentAction, _super);
  29199. function SetParentAction(triggerOptions, target, parent, condition) {
  29200. _super.call(this, triggerOptions, condition);
  29201. this._target = target;
  29202. this._parent = parent;
  29203. }
  29204. SetParentAction.prototype._prepare = function () {
  29205. };
  29206. SetParentAction.prototype.execute = function () {
  29207. if (this._target.parent === this._parent) {
  29208. return;
  29209. }
  29210. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  29211. invertParentWorldMatrix.invert();
  29212. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  29213. this._target.parent = this._parent;
  29214. };
  29215. return SetParentAction;
  29216. })(BABYLON.Action);
  29217. BABYLON.SetParentAction = SetParentAction;
  29218. var PlaySoundAction = (function (_super) {
  29219. __extends(PlaySoundAction, _super);
  29220. function PlaySoundAction(triggerOptions, sound, condition) {
  29221. _super.call(this, triggerOptions, condition);
  29222. this._sound = sound;
  29223. }
  29224. PlaySoundAction.prototype._prepare = function () {
  29225. };
  29226. PlaySoundAction.prototype.execute = function () {
  29227. if (this._sound !== undefined)
  29228. this._sound.play();
  29229. };
  29230. return PlaySoundAction;
  29231. })(BABYLON.Action);
  29232. BABYLON.PlaySoundAction = PlaySoundAction;
  29233. var StopSoundAction = (function (_super) {
  29234. __extends(StopSoundAction, _super);
  29235. function StopSoundAction(triggerOptions, sound, condition) {
  29236. _super.call(this, triggerOptions, condition);
  29237. this._sound = sound;
  29238. }
  29239. StopSoundAction.prototype._prepare = function () {
  29240. };
  29241. StopSoundAction.prototype.execute = function () {
  29242. if (this._sound !== undefined)
  29243. this._sound.stop();
  29244. };
  29245. return StopSoundAction;
  29246. })(BABYLON.Action);
  29247. BABYLON.StopSoundAction = StopSoundAction;
  29248. })(BABYLON || (BABYLON = {}));
  29249. var BABYLON;
  29250. (function (BABYLON) {
  29251. var Geometry = (function () {
  29252. function Geometry(id, scene, vertexData, updatable, mesh) {
  29253. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29254. this._totalVertices = 0;
  29255. this._isDisposed = false;
  29256. this.id = id;
  29257. this._engine = scene.getEngine();
  29258. this._meshes = [];
  29259. this._scene = scene;
  29260. //Init vertex buffer cache
  29261. this._vertexBuffers = {};
  29262. this._indices = [];
  29263. // vertexData
  29264. if (vertexData) {
  29265. this.setAllVerticesData(vertexData, updatable);
  29266. }
  29267. else {
  29268. this._totalVertices = 0;
  29269. this._indices = [];
  29270. }
  29271. // applyToMesh
  29272. if (mesh) {
  29273. this.applyToMesh(mesh);
  29274. mesh.computeWorldMatrix(true);
  29275. }
  29276. }
  29277. Object.defineProperty(Geometry.prototype, "extend", {
  29278. get: function () {
  29279. return this._extend;
  29280. },
  29281. enumerable: true,
  29282. configurable: true
  29283. });
  29284. Geometry.prototype.getScene = function () {
  29285. return this._scene;
  29286. };
  29287. Geometry.prototype.getEngine = function () {
  29288. return this._engine;
  29289. };
  29290. Geometry.prototype.isReady = function () {
  29291. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29292. };
  29293. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29294. vertexData.applyToGeometry(this, updatable);
  29295. this.notifyUpdate();
  29296. };
  29297. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29298. if (this._vertexBuffers[kind]) {
  29299. this._vertexBuffers[kind].dispose();
  29300. }
  29301. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29302. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29303. stride = this._vertexBuffers[kind].getStrideSize();
  29304. this._totalVertices = data.length / stride;
  29305. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29306. var meshes = this._meshes;
  29307. var numOfMeshes = meshes.length;
  29308. for (var index = 0; index < numOfMeshes; index++) {
  29309. var mesh = meshes[index];
  29310. mesh._resetPointsArrayCache();
  29311. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29312. mesh._createGlobalSubMesh();
  29313. mesh.computeWorldMatrix(true);
  29314. }
  29315. }
  29316. this.notifyUpdate(kind);
  29317. };
  29318. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29319. var vertexBuffer = this.getVertexBuffer(kind);
  29320. if (!vertexBuffer) {
  29321. return;
  29322. }
  29323. vertexBuffer.updateDirectly(data, offset);
  29324. this.notifyUpdate(kind);
  29325. };
  29326. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29327. var vertexBuffer = this.getVertexBuffer(kind);
  29328. if (!vertexBuffer) {
  29329. return;
  29330. }
  29331. vertexBuffer.update(data);
  29332. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29333. var stride = vertexBuffer.getStrideSize();
  29334. this._totalVertices = data.length / stride;
  29335. if (updateExtends) {
  29336. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29337. }
  29338. var meshes = this._meshes;
  29339. var numOfMeshes = meshes.length;
  29340. for (var index = 0; index < numOfMeshes; index++) {
  29341. var mesh = meshes[index];
  29342. mesh._resetPointsArrayCache();
  29343. if (updateExtends) {
  29344. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29345. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29346. var subMesh = mesh.subMeshes[subIndex];
  29347. subMesh.refreshBoundingInfo();
  29348. }
  29349. }
  29350. }
  29351. }
  29352. this.notifyUpdate(kind);
  29353. };
  29354. Geometry.prototype.getTotalVertices = function () {
  29355. if (!this.isReady()) {
  29356. return 0;
  29357. }
  29358. return this._totalVertices;
  29359. };
  29360. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  29361. var vertexBuffer = this.getVertexBuffer(kind);
  29362. if (!vertexBuffer) {
  29363. return null;
  29364. }
  29365. var orig = vertexBuffer.getData();
  29366. if (!copyWhenShared || this._meshes.length === 1) {
  29367. return orig;
  29368. }
  29369. else {
  29370. var len = orig.length;
  29371. var copy = [];
  29372. for (var i = 0; i < len; i++) {
  29373. copy.push(orig[i]);
  29374. }
  29375. return copy;
  29376. }
  29377. };
  29378. Geometry.prototype.getVertexBuffer = function (kind) {
  29379. if (!this.isReady()) {
  29380. return null;
  29381. }
  29382. return this._vertexBuffers[kind];
  29383. };
  29384. Geometry.prototype.getVertexBuffers = function () {
  29385. if (!this.isReady()) {
  29386. return null;
  29387. }
  29388. return this._vertexBuffers;
  29389. };
  29390. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29391. if (!this._vertexBuffers) {
  29392. if (this._delayInfo) {
  29393. return this._delayInfo.indexOf(kind) !== -1;
  29394. }
  29395. return false;
  29396. }
  29397. return this._vertexBuffers[kind] !== undefined;
  29398. };
  29399. Geometry.prototype.getVerticesDataKinds = function () {
  29400. var result = [];
  29401. var kind;
  29402. if (!this._vertexBuffers && this._delayInfo) {
  29403. for (kind in this._delayInfo) {
  29404. result.push(kind);
  29405. }
  29406. }
  29407. else {
  29408. for (kind in this._vertexBuffers) {
  29409. result.push(kind);
  29410. }
  29411. }
  29412. return result;
  29413. };
  29414. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29415. if (this._indexBuffer) {
  29416. this._engine._releaseBuffer(this._indexBuffer);
  29417. }
  29418. this._indices = indices;
  29419. if (this._meshes.length !== 0 && this._indices) {
  29420. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29421. }
  29422. if (totalVertices !== undefined) {
  29423. this._totalVertices = totalVertices;
  29424. }
  29425. var meshes = this._meshes;
  29426. var numOfMeshes = meshes.length;
  29427. for (var index = 0; index < numOfMeshes; index++) {
  29428. meshes[index]._createGlobalSubMesh();
  29429. }
  29430. this.notifyUpdate();
  29431. };
  29432. Geometry.prototype.getTotalIndices = function () {
  29433. if (!this.isReady()) {
  29434. return 0;
  29435. }
  29436. return this._indices.length;
  29437. };
  29438. Geometry.prototype.getIndices = function (copyWhenShared) {
  29439. if (!this.isReady()) {
  29440. return null;
  29441. }
  29442. var orig = this._indices;
  29443. if (!copyWhenShared || this._meshes.length === 1) {
  29444. return orig;
  29445. }
  29446. else {
  29447. var len = orig.length;
  29448. var copy = [];
  29449. for (var i = 0; i < len; i++) {
  29450. copy.push(orig[i]);
  29451. }
  29452. return copy;
  29453. }
  29454. };
  29455. Geometry.prototype.getIndexBuffer = function () {
  29456. if (!this.isReady()) {
  29457. return null;
  29458. }
  29459. return this._indexBuffer;
  29460. };
  29461. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29462. var meshes = this._meshes;
  29463. var index = meshes.indexOf(mesh);
  29464. if (index === -1) {
  29465. return;
  29466. }
  29467. for (var kind in this._vertexBuffers) {
  29468. this._vertexBuffers[kind].dispose();
  29469. }
  29470. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  29471. this._indexBuffer = null;
  29472. }
  29473. meshes.splice(index, 1);
  29474. mesh._geometry = null;
  29475. if (meshes.length === 0 && shouldDispose) {
  29476. this.dispose();
  29477. }
  29478. };
  29479. Geometry.prototype.applyToMesh = function (mesh) {
  29480. if (mesh._geometry === this) {
  29481. return;
  29482. }
  29483. var previousGeometry = mesh._geometry;
  29484. if (previousGeometry) {
  29485. previousGeometry.releaseForMesh(mesh);
  29486. }
  29487. var meshes = this._meshes;
  29488. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29489. mesh._geometry = this;
  29490. this._scene.pushGeometry(this);
  29491. meshes.push(mesh);
  29492. if (this.isReady()) {
  29493. this._applyToMesh(mesh);
  29494. }
  29495. else {
  29496. mesh._boundingInfo = this._boundingInfo;
  29497. }
  29498. };
  29499. Geometry.prototype._applyToMesh = function (mesh) {
  29500. var numOfMeshes = this._meshes.length;
  29501. // vertexBuffers
  29502. for (var kind in this._vertexBuffers) {
  29503. if (numOfMeshes === 1) {
  29504. this._vertexBuffers[kind].create();
  29505. }
  29506. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  29507. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29508. mesh._resetPointsArrayCache();
  29509. if (!this._extend) {
  29510. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  29511. }
  29512. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29513. mesh._createGlobalSubMesh();
  29514. //bounding info was just created again, world matrix should be applied again.
  29515. mesh._updateBoundingInfo();
  29516. }
  29517. }
  29518. // indexBuffer
  29519. if (numOfMeshes === 1 && this._indices) {
  29520. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29521. }
  29522. if (this._indexBuffer) {
  29523. this._indexBuffer.references = numOfMeshes;
  29524. }
  29525. };
  29526. Geometry.prototype.notifyUpdate = function (kind) {
  29527. if (this.onGeometryUpdated) {
  29528. this.onGeometryUpdated(this, kind);
  29529. }
  29530. };
  29531. Geometry.prototype.load = function (scene, onLoaded) {
  29532. var _this = this;
  29533. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29534. return;
  29535. }
  29536. if (this.isReady()) {
  29537. if (onLoaded) {
  29538. onLoaded();
  29539. }
  29540. return;
  29541. }
  29542. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29543. scene._addPendingData(this);
  29544. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29545. _this._delayLoadingFunction(JSON.parse(data), _this);
  29546. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29547. _this._delayInfo = [];
  29548. scene._removePendingData(_this);
  29549. var meshes = _this._meshes;
  29550. var numOfMeshes = meshes.length;
  29551. for (var index = 0; index < numOfMeshes; index++) {
  29552. _this._applyToMesh(meshes[index]);
  29553. }
  29554. if (onLoaded) {
  29555. onLoaded();
  29556. }
  29557. }, function () { }, scene.database);
  29558. };
  29559. Geometry.prototype.isDisposed = function () {
  29560. return this._isDisposed;
  29561. };
  29562. Geometry.prototype.dispose = function () {
  29563. var meshes = this._meshes;
  29564. var numOfMeshes = meshes.length;
  29565. var index;
  29566. for (index = 0; index < numOfMeshes; index++) {
  29567. this.releaseForMesh(meshes[index]);
  29568. }
  29569. this._meshes = [];
  29570. for (var kind in this._vertexBuffers) {
  29571. this._vertexBuffers[kind].dispose();
  29572. }
  29573. this._vertexBuffers = [];
  29574. this._totalVertices = 0;
  29575. if (this._indexBuffer) {
  29576. this._engine._releaseBuffer(this._indexBuffer);
  29577. }
  29578. this._indexBuffer = null;
  29579. this._indices = [];
  29580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29581. this.delayLoadingFile = null;
  29582. this._delayLoadingFunction = null;
  29583. this._delayInfo = [];
  29584. this._boundingInfo = null;
  29585. this._scene.removeGeometry(this);
  29586. this._isDisposed = true;
  29587. };
  29588. Geometry.prototype.copy = function (id) {
  29589. var vertexData = new BABYLON.VertexData();
  29590. vertexData.indices = [];
  29591. var indices = this.getIndices();
  29592. for (var index = 0; index < indices.length; index++) {
  29593. vertexData.indices.push(indices[index]);
  29594. }
  29595. var updatable = false;
  29596. var stopChecking = false;
  29597. var kind;
  29598. for (kind in this._vertexBuffers) {
  29599. // using slice() to make a copy of the array and not just reference it
  29600. var data = this.getVerticesData(kind);
  29601. if (data instanceof Float32Array) {
  29602. vertexData.set(new Float32Array(data), kind);
  29603. }
  29604. else {
  29605. vertexData.set(data.slice(0), kind);
  29606. }
  29607. if (!stopChecking) {
  29608. updatable = this.getVertexBuffer(kind).isUpdatable();
  29609. stopChecking = !updatable;
  29610. }
  29611. }
  29612. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29613. geometry.delayLoadState = this.delayLoadState;
  29614. geometry.delayLoadingFile = this.delayLoadingFile;
  29615. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29616. for (kind in this._delayInfo) {
  29617. geometry._delayInfo = geometry._delayInfo || [];
  29618. geometry._delayInfo.push(kind);
  29619. }
  29620. // Bounding info
  29621. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29622. return geometry;
  29623. };
  29624. Geometry.prototype.serialize = function () {
  29625. var serializationObject = {};
  29626. serializationObject.id = this.id;
  29627. if (BABYLON.Tags.HasTags(this)) {
  29628. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29629. }
  29630. return serializationObject;
  29631. };
  29632. Geometry.prototype.serializeVerticeData = function () {
  29633. var serializationObject = this.serialize();
  29634. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29635. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29636. }
  29637. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29638. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29639. }
  29640. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29641. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29642. }
  29643. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29644. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29645. }
  29646. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29647. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29648. }
  29649. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29650. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29651. }
  29652. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29653. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29654. }
  29655. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29656. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29657. }
  29658. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29659. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29660. }
  29661. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29662. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29663. serializationObject.matricesIndices._isExpanded = true;
  29664. }
  29665. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29666. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29667. }
  29668. serializationObject.indices = this.getIndices();
  29669. return serializationObject;
  29670. };
  29671. // Statics
  29672. Geometry.ExtractFromMesh = function (mesh, id) {
  29673. var geometry = mesh._geometry;
  29674. if (!geometry) {
  29675. return null;
  29676. }
  29677. return geometry.copy(id);
  29678. };
  29679. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29680. // be aware Math.random() could cause collisions
  29681. Geometry.RandomId = function () {
  29682. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  29683. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  29684. return v.toString(16);
  29685. });
  29686. };
  29687. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29688. var scene = mesh.getScene();
  29689. // Geometry
  29690. var geometryId = parsedGeometry.geometryId;
  29691. if (geometryId) {
  29692. var geometry = scene.getGeometryByID(geometryId);
  29693. if (geometry) {
  29694. geometry.applyToMesh(mesh);
  29695. }
  29696. }
  29697. else if (parsedGeometry instanceof ArrayBuffer) {
  29698. var binaryInfo = mesh._binaryInfo;
  29699. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29700. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29701. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29702. }
  29703. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29704. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29705. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29706. }
  29707. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29708. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29709. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29710. }
  29711. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29712. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29713. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29714. }
  29715. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29716. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29717. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29718. }
  29719. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29720. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29721. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29722. }
  29723. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29724. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29725. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29726. }
  29727. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29728. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29729. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29730. }
  29731. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29732. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29733. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29734. }
  29735. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29736. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29737. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29738. }
  29739. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29740. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29741. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29742. }
  29743. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29744. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29745. mesh.setIndices(indicesData);
  29746. }
  29747. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29748. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29749. mesh.subMeshes = [];
  29750. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29751. var materialIndex = subMeshesData[(i * 5) + 0];
  29752. var verticesStart = subMeshesData[(i * 5) + 1];
  29753. var verticesCount = subMeshesData[(i * 5) + 2];
  29754. var indexStart = subMeshesData[(i * 5) + 3];
  29755. var indexCount = subMeshesData[(i * 5) + 4];
  29756. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29757. }
  29758. }
  29759. }
  29760. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29761. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  29762. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  29763. if (parsedGeometry.uvs) {
  29764. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  29765. }
  29766. if (parsedGeometry.uvs2) {
  29767. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  29768. }
  29769. if (parsedGeometry.uvs3) {
  29770. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  29771. }
  29772. if (parsedGeometry.uvs4) {
  29773. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  29774. }
  29775. if (parsedGeometry.uvs5) {
  29776. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  29777. }
  29778. if (parsedGeometry.uvs6) {
  29779. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  29780. }
  29781. if (parsedGeometry.colors) {
  29782. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  29783. }
  29784. if (parsedGeometry.matricesIndices) {
  29785. if (!parsedGeometry.matricesIndices._isExpanded) {
  29786. var floatIndices = [];
  29787. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29788. var matricesIndex = parsedGeometry.matricesIndices[i];
  29789. floatIndices.push(matricesIndex & 0x000000FF);
  29790. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29791. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29792. floatIndices.push(matricesIndex >> 24);
  29793. }
  29794. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  29795. }
  29796. else {
  29797. delete parsedGeometry.matricesIndices._isExpanded;
  29798. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  29799. }
  29800. }
  29801. if (parsedGeometry.matricesIndicesExtra) {
  29802. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29803. var floatIndices = [];
  29804. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29805. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29806. floatIndices.push(matricesIndex & 0x000000FF);
  29807. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29808. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29809. floatIndices.push(matricesIndex >> 24);
  29810. }
  29811. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  29812. }
  29813. else {
  29814. delete parsedGeometry.matricesIndices._isExpanded;
  29815. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  29816. }
  29817. }
  29818. if (parsedGeometry.matricesWeights) {
  29819. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  29820. }
  29821. if (parsedGeometry.matricesWeightsExtra) {
  29822. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  29823. }
  29824. mesh.setIndices(parsedGeometry.indices);
  29825. }
  29826. // SubMeshes
  29827. if (parsedGeometry.subMeshes) {
  29828. mesh.subMeshes = [];
  29829. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29830. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29831. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29832. }
  29833. }
  29834. // Flat shading
  29835. if (mesh._shouldGenerateFlatShading) {
  29836. mesh.convertToFlatShadedMesh();
  29837. delete mesh._shouldGenerateFlatShading;
  29838. }
  29839. // Update
  29840. mesh.computeWorldMatrix(true);
  29841. // Octree
  29842. if (scene['_selectionOctree']) {
  29843. scene['_selectionOctree'].addMesh(mesh);
  29844. }
  29845. };
  29846. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29847. if (scene.getGeometryByID(parsedVertexData.id)) {
  29848. return null; // null since geometry could be something else than a box...
  29849. }
  29850. var geometry = new Geometry(parsedVertexData.id, scene);
  29851. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29852. if (parsedVertexData.delayLoadingFile) {
  29853. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29854. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29855. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29856. geometry._delayInfo = [];
  29857. if (parsedVertexData.hasUVs) {
  29858. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29859. }
  29860. if (parsedVertexData.hasUVs2) {
  29861. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29862. }
  29863. if (parsedVertexData.hasUVs3) {
  29864. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29865. }
  29866. if (parsedVertexData.hasUVs4) {
  29867. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29868. }
  29869. if (parsedVertexData.hasUVs5) {
  29870. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29871. }
  29872. if (parsedVertexData.hasUVs6) {
  29873. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29874. }
  29875. if (parsedVertexData.hasColors) {
  29876. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29877. }
  29878. if (parsedVertexData.hasMatricesIndices) {
  29879. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29880. }
  29881. if (parsedVertexData.hasMatricesWeights) {
  29882. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29883. }
  29884. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29885. }
  29886. else {
  29887. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29888. }
  29889. scene.pushGeometry(geometry, true);
  29890. return geometry;
  29891. };
  29892. return Geometry;
  29893. })();
  29894. BABYLON.Geometry = Geometry;
  29895. /////// Primitives //////////////////////////////////////////////
  29896. var Geometry;
  29897. (function (Geometry) {
  29898. var Primitives;
  29899. (function (Primitives) {
  29900. /// Abstract class
  29901. var _Primitive = (function (_super) {
  29902. __extends(_Primitive, _super);
  29903. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29904. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  29905. this._canBeRegenerated = _canBeRegenerated;
  29906. this._beingRegenerated = true;
  29907. this.regenerate();
  29908. this._beingRegenerated = false;
  29909. }
  29910. _Primitive.prototype.canBeRegenerated = function () {
  29911. return this._canBeRegenerated;
  29912. };
  29913. _Primitive.prototype.regenerate = function () {
  29914. if (!this._canBeRegenerated) {
  29915. return;
  29916. }
  29917. this._beingRegenerated = true;
  29918. this.setAllVerticesData(this._regenerateVertexData(), false);
  29919. this._beingRegenerated = false;
  29920. };
  29921. _Primitive.prototype.asNewGeometry = function (id) {
  29922. return _super.prototype.copy.call(this, id);
  29923. };
  29924. // overrides
  29925. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29926. if (!this._beingRegenerated) {
  29927. return;
  29928. }
  29929. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29930. };
  29931. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29932. if (!this._beingRegenerated) {
  29933. return;
  29934. }
  29935. _super.prototype.setVerticesData.call(this, kind, data, false);
  29936. };
  29937. // to override
  29938. // protected
  29939. _Primitive.prototype._regenerateVertexData = function () {
  29940. throw new Error("Abstract method");
  29941. };
  29942. _Primitive.prototype.copy = function (id) {
  29943. throw new Error("Must be overriden in sub-classes.");
  29944. };
  29945. _Primitive.prototype.serialize = function () {
  29946. var serializationObject = _super.prototype.serialize.call(this);
  29947. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29948. return serializationObject;
  29949. };
  29950. return _Primitive;
  29951. })(Geometry);
  29952. Primitives._Primitive = _Primitive;
  29953. var Ribbon = (function (_super) {
  29954. __extends(Ribbon, _super);
  29955. // Members
  29956. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29957. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29958. _super.call(this, id, scene, canBeRegenerated, mesh);
  29959. this.pathArray = pathArray;
  29960. this.closeArray = closeArray;
  29961. this.closePath = closePath;
  29962. this.offset = offset;
  29963. this.side = side;
  29964. }
  29965. Ribbon.prototype._regenerateVertexData = function () {
  29966. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29967. };
  29968. Ribbon.prototype.copy = function (id) {
  29969. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29970. };
  29971. return Ribbon;
  29972. })(_Primitive);
  29973. Primitives.Ribbon = Ribbon;
  29974. var Box = (function (_super) {
  29975. __extends(Box, _super);
  29976. // Members
  29977. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29978. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29979. _super.call(this, id, scene, canBeRegenerated, mesh);
  29980. this.size = size;
  29981. this.side = side;
  29982. }
  29983. Box.prototype._regenerateVertexData = function () {
  29984. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29985. };
  29986. Box.prototype.copy = function (id) {
  29987. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29988. };
  29989. Box.prototype.serialize = function () {
  29990. var serializationObject = _super.prototype.serialize.call(this);
  29991. serializationObject.size = this.size;
  29992. return serializationObject;
  29993. };
  29994. Box.Parse = function (parsedBox, scene) {
  29995. if (scene.getGeometryByID(parsedBox.id)) {
  29996. return null; // null since geometry could be something else than a box...
  29997. }
  29998. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29999. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30000. scene.pushGeometry(box, true);
  30001. return box;
  30002. };
  30003. return Box;
  30004. })(_Primitive);
  30005. Primitives.Box = Box;
  30006. var Sphere = (function (_super) {
  30007. __extends(Sphere, _super);
  30008. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30009. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30010. _super.call(this, id, scene, canBeRegenerated, mesh);
  30011. this.segments = segments;
  30012. this.diameter = diameter;
  30013. this.side = side;
  30014. }
  30015. Sphere.prototype._regenerateVertexData = function () {
  30016. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30017. };
  30018. Sphere.prototype.copy = function (id) {
  30019. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30020. };
  30021. Sphere.prototype.serialize = function () {
  30022. var serializationObject = _super.prototype.serialize.call(this);
  30023. serializationObject.segments = this.segments;
  30024. serializationObject.diameter = this.diameter;
  30025. return serializationObject;
  30026. };
  30027. Sphere.Parse = function (parsedSphere, scene) {
  30028. if (scene.getGeometryByID(parsedSphere.id)) {
  30029. return null; // null since geometry could be something else than a sphere...
  30030. }
  30031. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30032. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30033. scene.pushGeometry(sphere, true);
  30034. return sphere;
  30035. };
  30036. return Sphere;
  30037. })(_Primitive);
  30038. Primitives.Sphere = Sphere;
  30039. var Disc = (function (_super) {
  30040. __extends(Disc, _super);
  30041. // Members
  30042. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30043. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30044. _super.call(this, id, scene, canBeRegenerated, mesh);
  30045. this.radius = radius;
  30046. this.tessellation = tessellation;
  30047. this.side = side;
  30048. }
  30049. Disc.prototype._regenerateVertexData = function () {
  30050. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30051. };
  30052. Disc.prototype.copy = function (id) {
  30053. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30054. };
  30055. return Disc;
  30056. })(_Primitive);
  30057. Primitives.Disc = Disc;
  30058. var Cylinder = (function (_super) {
  30059. __extends(Cylinder, _super);
  30060. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30061. if (subdivisions === void 0) { subdivisions = 1; }
  30062. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30063. _super.call(this, id, scene, canBeRegenerated, mesh);
  30064. this.height = height;
  30065. this.diameterTop = diameterTop;
  30066. this.diameterBottom = diameterBottom;
  30067. this.tessellation = tessellation;
  30068. this.subdivisions = subdivisions;
  30069. this.side = side;
  30070. }
  30071. Cylinder.prototype._regenerateVertexData = function () {
  30072. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30073. };
  30074. Cylinder.prototype.copy = function (id) {
  30075. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30076. };
  30077. Cylinder.prototype.serialize = function () {
  30078. var serializationObject = _super.prototype.serialize.call(this);
  30079. serializationObject.height = this.height;
  30080. serializationObject.diameterTop = this.diameterTop;
  30081. serializationObject.diameterBottom = this.diameterBottom;
  30082. serializationObject.tessellation = this.tessellation;
  30083. return serializationObject;
  30084. };
  30085. Cylinder.Parse = function (parsedCylinder, scene) {
  30086. if (scene.getGeometryByID(parsedCylinder.id)) {
  30087. return null; // null since geometry could be something else than a cylinder...
  30088. }
  30089. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30090. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30091. scene.pushGeometry(cylinder, true);
  30092. return cylinder;
  30093. };
  30094. return Cylinder;
  30095. })(_Primitive);
  30096. Primitives.Cylinder = Cylinder;
  30097. var Torus = (function (_super) {
  30098. __extends(Torus, _super);
  30099. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30100. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30101. _super.call(this, id, scene, canBeRegenerated, mesh);
  30102. this.diameter = diameter;
  30103. this.thickness = thickness;
  30104. this.tessellation = tessellation;
  30105. this.side = side;
  30106. }
  30107. Torus.prototype._regenerateVertexData = function () {
  30108. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30109. };
  30110. Torus.prototype.copy = function (id) {
  30111. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30112. };
  30113. Torus.prototype.serialize = function () {
  30114. var serializationObject = _super.prototype.serialize.call(this);
  30115. serializationObject.diameter = this.diameter;
  30116. serializationObject.thickness = this.thickness;
  30117. serializationObject.tessellation = this.tessellation;
  30118. return serializationObject;
  30119. };
  30120. Torus.Parse = function (parsedTorus, scene) {
  30121. if (scene.getGeometryByID(parsedTorus.id)) {
  30122. return null; // null since geometry could be something else than a torus...
  30123. }
  30124. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30125. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30126. scene.pushGeometry(torus, true);
  30127. return torus;
  30128. };
  30129. return Torus;
  30130. })(_Primitive);
  30131. Primitives.Torus = Torus;
  30132. var Ground = (function (_super) {
  30133. __extends(Ground, _super);
  30134. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30135. _super.call(this, id, scene, canBeRegenerated, mesh);
  30136. this.width = width;
  30137. this.height = height;
  30138. this.subdivisions = subdivisions;
  30139. }
  30140. Ground.prototype._regenerateVertexData = function () {
  30141. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30142. };
  30143. Ground.prototype.copy = function (id) {
  30144. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30145. };
  30146. Ground.prototype.serialize = function () {
  30147. var serializationObject = _super.prototype.serialize.call(this);
  30148. serializationObject.width = this.width;
  30149. serializationObject.height = this.height;
  30150. serializationObject.subdivisions = this.subdivisions;
  30151. return serializationObject;
  30152. };
  30153. Ground.Parse = function (parsedGround, scene) {
  30154. if (scene.getGeometryByID(parsedGround.id)) {
  30155. return null; // null since geometry could be something else than a ground...
  30156. }
  30157. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30158. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30159. scene.pushGeometry(ground, true);
  30160. return ground;
  30161. };
  30162. return Ground;
  30163. })(_Primitive);
  30164. Primitives.Ground = Ground;
  30165. var TiledGround = (function (_super) {
  30166. __extends(TiledGround, _super);
  30167. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30168. _super.call(this, id, scene, canBeRegenerated, mesh);
  30169. this.xmin = xmin;
  30170. this.zmin = zmin;
  30171. this.xmax = xmax;
  30172. this.zmax = zmax;
  30173. this.subdivisions = subdivisions;
  30174. this.precision = precision;
  30175. }
  30176. TiledGround.prototype._regenerateVertexData = function () {
  30177. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30178. };
  30179. TiledGround.prototype.copy = function (id) {
  30180. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30181. };
  30182. return TiledGround;
  30183. })(_Primitive);
  30184. Primitives.TiledGround = TiledGround;
  30185. var Plane = (function (_super) {
  30186. __extends(Plane, _super);
  30187. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30188. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30189. _super.call(this, id, scene, canBeRegenerated, mesh);
  30190. this.size = size;
  30191. this.side = side;
  30192. }
  30193. Plane.prototype._regenerateVertexData = function () {
  30194. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30195. };
  30196. Plane.prototype.copy = function (id) {
  30197. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30198. };
  30199. Plane.prototype.serialize = function () {
  30200. var serializationObject = _super.prototype.serialize.call(this);
  30201. serializationObject.size = this.size;
  30202. return serializationObject;
  30203. };
  30204. Plane.Parse = function (parsedPlane, scene) {
  30205. if (scene.getGeometryByID(parsedPlane.id)) {
  30206. return null; // null since geometry could be something else than a ground...
  30207. }
  30208. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30209. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30210. scene.pushGeometry(plane, true);
  30211. return plane;
  30212. };
  30213. return Plane;
  30214. })(_Primitive);
  30215. Primitives.Plane = Plane;
  30216. var TorusKnot = (function (_super) {
  30217. __extends(TorusKnot, _super);
  30218. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30219. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30220. _super.call(this, id, scene, canBeRegenerated, mesh);
  30221. this.radius = radius;
  30222. this.tube = tube;
  30223. this.radialSegments = radialSegments;
  30224. this.tubularSegments = tubularSegments;
  30225. this.p = p;
  30226. this.q = q;
  30227. this.side = side;
  30228. }
  30229. TorusKnot.prototype._regenerateVertexData = function () {
  30230. 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 });
  30231. };
  30232. TorusKnot.prototype.copy = function (id) {
  30233. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30234. };
  30235. TorusKnot.prototype.serialize = function () {
  30236. var serializationObject = _super.prototype.serialize.call(this);
  30237. serializationObject.radius = this.radius;
  30238. serializationObject.tube = this.tube;
  30239. serializationObject.radialSegments = this.radialSegments;
  30240. serializationObject.tubularSegments = this.tubularSegments;
  30241. serializationObject.p = this.p;
  30242. serializationObject.q = this.q;
  30243. return serializationObject;
  30244. };
  30245. ;
  30246. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30247. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30248. return null; // null since geometry could be something else than a ground...
  30249. }
  30250. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30251. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30252. scene.pushGeometry(torusKnot, true);
  30253. return torusKnot;
  30254. };
  30255. return TorusKnot;
  30256. })(_Primitive);
  30257. Primitives.TorusKnot = TorusKnot;
  30258. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30259. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30260. })(BABYLON || (BABYLON = {}));
  30261. var BABYLON;
  30262. (function (BABYLON) {
  30263. var GroundMesh = (function (_super) {
  30264. __extends(GroundMesh, _super);
  30265. function GroundMesh(name, scene) {
  30266. _super.call(this, name, scene);
  30267. this.generateOctree = false;
  30268. this._worldInverse = new BABYLON.Matrix();
  30269. }
  30270. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  30271. get: function () {
  30272. return this._subdivisions;
  30273. },
  30274. enumerable: true,
  30275. configurable: true
  30276. });
  30277. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  30278. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  30279. this._subdivisions = chunksCount;
  30280. this.subdivide(this._subdivisions);
  30281. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  30282. };
  30283. /**
  30284. * Returns a height (y) value in the Worl system :
  30285. * the ground altitude at the coordinates (x, z) expressed in the World system.
  30286. * Returns the ground y position if (x, z) are outside the ground surface.
  30287. * Not pertinent if the ground is rotated.
  30288. */
  30289. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  30290. // express x and y in the ground local system
  30291. x -= this.position.x;
  30292. z -= this.position.z;
  30293. x /= this.scaling.x;
  30294. z /= this.scaling.z;
  30295. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  30296. return this.position.y;
  30297. }
  30298. if (!this._heightQuads || this._heightQuads.length == 0) {
  30299. this._initHeightQuads();
  30300. this._computeHeightQuads();
  30301. }
  30302. var facet = this._getFacetAt(x, z);
  30303. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  30304. // return y in the World system
  30305. return y * this.scaling.y + this.position.y;
  30306. };
  30307. /**
  30308. * Returns a normalized vector (Vector3) orthogonal to the ground
  30309. * at the ground coordinates (x, z) expressed in the World system.
  30310. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  30311. * Not pertinent if the ground is rotated.
  30312. */
  30313. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  30314. var normal = new BABYLON.Vector3(0, 1, 0);
  30315. this.getNormalAtCoordinatesToRef(x, z, normal);
  30316. return normal;
  30317. };
  30318. /**
  30319. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  30320. * at the ground coordinates (x, z) expressed in the World system.
  30321. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  30322. * Not pertinent if the ground is rotated.
  30323. */
  30324. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  30325. // express x and y in the ground local system
  30326. x -= this.position.x;
  30327. z -= this.position.z;
  30328. x /= this.scaling.x;
  30329. z /= this.scaling.z;
  30330. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  30331. return;
  30332. }
  30333. if (!this._heightQuads || this._heightQuads.length == 0) {
  30334. this._initHeightQuads();
  30335. this._computeHeightQuads();
  30336. }
  30337. var facet = this._getFacetAt(x, z);
  30338. ref.x = facet.x;
  30339. ref.y = facet.y;
  30340. ref.z = facet.z;
  30341. };
  30342. /**
  30343. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  30344. * if the ground has been updated.
  30345. * This can be used in the render loop
  30346. */
  30347. GroundMesh.prototype.updateCoordinateHeights = function () {
  30348. if (!this._heightQuads || this._heightQuads.length == 0) {
  30349. this._initHeightQuads();
  30350. }
  30351. this._computeHeightQuads();
  30352. };
  30353. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  30354. GroundMesh.prototype._getFacetAt = function (x, z) {
  30355. // retrieve col and row from x, z coordinates in the ground local system
  30356. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  30357. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  30358. var quad = this._heightQuads[row * this._subdivisions + col];
  30359. var facet;
  30360. if (z < quad.slope.x * x + quad.slope.y) {
  30361. facet = quad.facet1;
  30362. }
  30363. else {
  30364. facet = quad.facet2;
  30365. }
  30366. return facet;
  30367. };
  30368. // Creates and populates the heightMap array with "facet" elements :
  30369. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  30370. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  30371. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  30372. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  30373. GroundMesh.prototype._initHeightQuads = function () {
  30374. this._heightQuads = new Array();
  30375. for (var row = 0; row < this._subdivisions; row++) {
  30376. for (var col = 0; col < this._subdivisions; col++) {
  30377. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  30378. this._heightQuads[row * this._subdivisions + col] = quad;
  30379. }
  30380. }
  30381. };
  30382. // Compute each quad element values and update the the heightMap array :
  30383. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  30384. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  30385. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  30386. GroundMesh.prototype._computeHeightQuads = function () {
  30387. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30388. var v1 = BABYLON.Tmp.Vector3[0];
  30389. var v2 = BABYLON.Tmp.Vector3[1];
  30390. var v3 = BABYLON.Tmp.Vector3[2];
  30391. var v4 = BABYLON.Tmp.Vector3[3];
  30392. var v1v2 = BABYLON.Tmp.Vector3[4];
  30393. var v1v3 = BABYLON.Tmp.Vector3[5];
  30394. var v1v4 = BABYLON.Tmp.Vector3[6];
  30395. var norm1 = BABYLON.Tmp.Vector3[7];
  30396. var norm2 = BABYLON.Tmp.Vector3[8];
  30397. var i = 0;
  30398. var j = 0;
  30399. var k = 0;
  30400. var cd = 0; // 2D slope coefficient : z = cd * x + h
  30401. var h = 0;
  30402. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  30403. var d2 = 0;
  30404. for (var row = 0; row < this._subdivisions; row++) {
  30405. for (var col = 0; col < this._subdivisions; col++) {
  30406. i = col * 3;
  30407. j = row * (this._subdivisions + 1) * 3;
  30408. k = (row + 1) * (this._subdivisions + 1) * 3;
  30409. v1.x = positions[j + i];
  30410. v1.y = positions[j + i + 1];
  30411. v1.z = positions[j + i + 2];
  30412. v2.x = positions[j + i + 3];
  30413. v2.y = positions[j + i + 4];
  30414. v2.z = positions[j + i + 5];
  30415. v3.x = positions[k + i];
  30416. v3.y = positions[k + i + 1];
  30417. v3.z = positions[k + i + 2];
  30418. v4.x = positions[k + i + 3];
  30419. v4.y = positions[k + i + 4];
  30420. v4.z = positions[k + i + 5];
  30421. // 2D slope V1V4
  30422. cd = (v4.z - v1.z) / (v4.x - v1.x);
  30423. h = v1.z - cd * v1.x; // v1 belongs to the slope
  30424. // facet equations :
  30425. // we compute each facet normal vector
  30426. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  30427. // we compute the value d by applying the equation to v1 which belongs to the plane
  30428. // then we store the facet equation in a Vector4
  30429. v2.subtractToRef(v1, v1v2);
  30430. v3.subtractToRef(v1, v1v3);
  30431. v4.subtractToRef(v1, v1v4);
  30432. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  30433. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  30434. norm1.normalize();
  30435. norm2.normalize();
  30436. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  30437. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  30438. var quad = this._heightQuads[row * this._subdivisions + col];
  30439. quad.slope.copyFromFloats(cd, h);
  30440. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  30441. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  30442. }
  30443. }
  30444. };
  30445. return GroundMesh;
  30446. })(BABYLON.Mesh);
  30447. BABYLON.GroundMesh = GroundMesh;
  30448. })(BABYLON || (BABYLON = {}));
  30449. var BABYLON;
  30450. (function (BABYLON) {
  30451. var LinesMesh = (function (_super) {
  30452. __extends(LinesMesh, _super);
  30453. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  30454. if (parent === void 0) { parent = null; }
  30455. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  30456. this.color = new BABYLON.Color3(1, 1, 1);
  30457. this.alpha = 1;
  30458. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  30459. attributes: ["position"],
  30460. uniforms: ["worldViewProjection", "color"],
  30461. needAlphaBlending: true
  30462. });
  30463. }
  30464. Object.defineProperty(LinesMesh.prototype, "material", {
  30465. get: function () {
  30466. return this._colorShader;
  30467. },
  30468. enumerable: true,
  30469. configurable: true
  30470. });
  30471. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  30472. get: function () {
  30473. return false;
  30474. },
  30475. enumerable: true,
  30476. configurable: true
  30477. });
  30478. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  30479. get: function () {
  30480. return false;
  30481. },
  30482. enumerable: true,
  30483. configurable: true
  30484. });
  30485. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  30486. var engine = this.getScene().getEngine();
  30487. var indexToBind = this._geometry.getIndexBuffer();
  30488. // VBOs
  30489. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  30490. // Color
  30491. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  30492. };
  30493. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  30494. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  30495. return;
  30496. }
  30497. var engine = this.getScene().getEngine();
  30498. // Draw order
  30499. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  30500. };
  30501. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  30502. return null;
  30503. };
  30504. LinesMesh.prototype.dispose = function (doNotRecurse) {
  30505. this._colorShader.dispose();
  30506. _super.prototype.dispose.call(this, doNotRecurse);
  30507. };
  30508. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  30509. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  30510. };
  30511. return LinesMesh;
  30512. })(BABYLON.Mesh);
  30513. BABYLON.LinesMesh = LinesMesh;
  30514. })(BABYLON || (BABYLON = {}));
  30515. var BABYLON;
  30516. (function (BABYLON) {
  30517. var DebugLayer = (function () {
  30518. function DebugLayer(scene) {
  30519. var _this = this;
  30520. this._transformationMatrix = BABYLON.Matrix.Identity();
  30521. this._enabled = false;
  30522. this._labelsEnabled = false;
  30523. this._displayStatistics = true;
  30524. this._displayTree = false;
  30525. this._displayLogs = false;
  30526. this._skeletonViewers = new Array();
  30527. this._identityMatrix = BABYLON.Matrix.Identity();
  30528. this.axisRatio = 0.02;
  30529. this.accentColor = "orange";
  30530. this._scene = scene;
  30531. this._syncPositions = function () {
  30532. var engine = _this._scene.getEngine();
  30533. var canvasRect = engine.getRenderingCanvasClientRect();
  30534. if (_this._showUI) {
  30535. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30536. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30537. _this._statsDiv.style.width = "400px";
  30538. _this._statsDiv.style.height = "auto";
  30539. _this._statsSubsetDiv.style.maxHeight = "240px";
  30540. _this._optionsDiv.style.left = "0px";
  30541. _this._optionsDiv.style.top = "10px";
  30542. _this._optionsDiv.style.width = "200px";
  30543. _this._optionsDiv.style.height = "auto";
  30544. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30545. _this._logDiv.style.left = "0px";
  30546. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30547. _this._logDiv.style.width = "600px";
  30548. _this._logDiv.style.height = "160px";
  30549. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30550. _this._treeDiv.style.top = "10px";
  30551. _this._treeDiv.style.width = "300px";
  30552. _this._treeDiv.style.height = "auto";
  30553. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30554. }
  30555. _this._globalDiv.style.left = canvasRect.left + "px";
  30556. _this._globalDiv.style.top = canvasRect.top + "px";
  30557. _this._drawingCanvas.style.left = "0px";
  30558. _this._drawingCanvas.style.top = "0px";
  30559. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30560. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30561. var devicePixelRatio = window.devicePixelRatio || 1;
  30562. var context = _this._drawingContext;
  30563. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30564. context.mozBackingStorePixelRatio ||
  30565. context.msBackingStorePixelRatio ||
  30566. context.oBackingStorePixelRatio ||
  30567. context.backingStorePixelRatio || 1;
  30568. _this._ratio = devicePixelRatio / backingStoreRatio;
  30569. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30570. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30571. };
  30572. this._onCanvasClick = function (evt) {
  30573. _this._clickPosition = {
  30574. x: evt.clientX * _this._ratio,
  30575. y: evt.clientY * _this._ratio
  30576. };
  30577. };
  30578. this._syncUI = function () {
  30579. if (_this._showUI) {
  30580. if (_this._displayStatistics) {
  30581. _this._displayStats();
  30582. _this._statsDiv.style.display = "";
  30583. }
  30584. else {
  30585. _this._statsDiv.style.display = "none";
  30586. }
  30587. if (_this._displayLogs) {
  30588. _this._logDiv.style.display = "";
  30589. }
  30590. else {
  30591. _this._logDiv.style.display = "none";
  30592. }
  30593. if (_this._displayTree) {
  30594. _this._treeDiv.style.display = "";
  30595. if (_this._needToRefreshMeshesTree) {
  30596. _this._needToRefreshMeshesTree = false;
  30597. _this._refreshMeshesTreeContent();
  30598. }
  30599. }
  30600. else {
  30601. _this._treeDiv.style.display = "none";
  30602. }
  30603. }
  30604. };
  30605. this._syncData = function () {
  30606. if (_this._labelsEnabled || !_this._showUI) {
  30607. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30608. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30609. var engine = _this._scene.getEngine();
  30610. var viewport = _this._camera.viewport;
  30611. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  30612. // Meshes
  30613. var meshes = _this._camera.getActiveMeshes();
  30614. var index;
  30615. var projectedPosition;
  30616. for (index = 0; index < meshes.length; index++) {
  30617. var mesh = meshes.data[index];
  30618. var position = mesh.getBoundingInfo().boundingSphere.center;
  30619. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30620. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30621. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30622. }
  30623. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30624. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30625. }
  30626. }
  30627. // Cameras
  30628. var cameras = _this._scene.cameras;
  30629. for (index = 0; index < cameras.length; index++) {
  30630. var camera = cameras[index];
  30631. if (camera === _this._camera) {
  30632. continue;
  30633. }
  30634. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30635. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30636. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30637. _this._camera.detachControl(engine.getRenderingCanvas());
  30638. _this._camera = camera;
  30639. _this._camera.attachControl(engine.getRenderingCanvas());
  30640. }, function () { return "purple"; });
  30641. }
  30642. }
  30643. // Lights
  30644. var lights = _this._scene.lights;
  30645. for (index = 0; index < lights.length; index++) {
  30646. var light = lights[index];
  30647. if (light.position) {
  30648. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30649. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30650. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30651. light.setEnabled(!light.isEnabled());
  30652. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30653. }
  30654. }
  30655. }
  30656. }
  30657. _this._clickPosition = undefined;
  30658. };
  30659. }
  30660. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30661. while (this._treeSubsetDiv.hasChildNodes()) {
  30662. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30663. }
  30664. // Add meshes
  30665. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30666. sortedArray.sort(function (a, b) {
  30667. if (a.name === b.name) {
  30668. return 0;
  30669. }
  30670. return (a.name > b.name) ? 1 : -1;
  30671. });
  30672. for (var index = 0; index < sortedArray.length; index++) {
  30673. var mesh = sortedArray[index];
  30674. if (!mesh.isEnabled()) {
  30675. continue;
  30676. }
  30677. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30678. m.isVisible = element.checked;
  30679. }, mesh);
  30680. }
  30681. };
  30682. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30683. this._drawingContext.beginPath();
  30684. this._drawingContext.moveTo(zero.x, zero.y);
  30685. this._drawingContext.lineTo(unit.x, unit.y);
  30686. this._drawingContext.strokeStyle = color;
  30687. this._drawingContext.lineWidth = 4;
  30688. this._drawingContext.stroke();
  30689. this._drawingContext.font = "normal 14px Segoe UI";
  30690. this._drawingContext.fillStyle = color;
  30691. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30692. };
  30693. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30694. var position = mesh.getBoundingInfo().boundingSphere.center;
  30695. var worldMatrix = mesh.getWorldMatrix();
  30696. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30697. var unit = (unprojectedVector.subtract(position)).length();
  30698. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30699. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30700. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30701. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30702. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30703. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30704. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30705. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30706. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30707. };
  30708. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30709. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30710. this._drawingContext.font = "normal 12px Segoe UI";
  30711. var textMetrics = this._drawingContext.measureText(text);
  30712. var centerX = projectedPosition.x - textMetrics.width / 2;
  30713. var centerY = projectedPosition.y;
  30714. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30715. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30716. onClick();
  30717. }
  30718. this._drawingContext.beginPath();
  30719. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30720. this._drawingContext.fillStyle = getFillStyle();
  30721. this._drawingContext.globalAlpha = 0.5;
  30722. this._drawingContext.fill();
  30723. this._drawingContext.globalAlpha = 1.0;
  30724. this._drawingContext.strokeStyle = '#FFFFFF';
  30725. this._drawingContext.lineWidth = 1;
  30726. this._drawingContext.stroke();
  30727. this._drawingContext.fillStyle = "#FFFFFF";
  30728. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30729. this._drawingContext.beginPath();
  30730. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30731. this._drawingContext.fill();
  30732. }
  30733. };
  30734. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30735. if (!this._clickPosition) {
  30736. return false;
  30737. }
  30738. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30739. return false;
  30740. }
  30741. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30742. return false;
  30743. }
  30744. return true;
  30745. };
  30746. DebugLayer.prototype.isVisible = function () {
  30747. return this._enabled;
  30748. };
  30749. DebugLayer.prototype.hide = function () {
  30750. if (!this._enabled) {
  30751. return;
  30752. }
  30753. this._enabled = false;
  30754. var engine = this._scene.getEngine();
  30755. this._scene.unregisterBeforeRender(this._syncData);
  30756. this._scene.unregisterAfterRender(this._syncUI);
  30757. this._rootElement.removeChild(this._globalDiv);
  30758. this._scene.forceShowBoundingBoxes = false;
  30759. this._scene.forceWireframe = false;
  30760. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30761. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30762. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30763. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30764. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30765. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30766. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30767. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  30768. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  30769. this._scene.shadowsEnabled = true;
  30770. this._scene.particlesEnabled = true;
  30771. this._scene.postProcessesEnabled = true;
  30772. this._scene.collisionsEnabled = true;
  30773. this._scene.lightsEnabled = true;
  30774. this._scene.texturesEnabled = true;
  30775. this._scene.lensFlaresEnabled = true;
  30776. this._scene.proceduralTexturesEnabled = true;
  30777. this._scene.renderTargetsEnabled = true;
  30778. this._scene.probesEnabled = true;
  30779. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30780. this._clearSkeletonViewers();
  30781. };
  30782. DebugLayer.prototype._clearSkeletonViewers = function () {
  30783. for (var index = 0; index < this._skeletonViewers.length; index++) {
  30784. this._skeletonViewers[index].dispose();
  30785. }
  30786. this._skeletonViewers = [];
  30787. };
  30788. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  30789. if (showUI === void 0) { showUI = true; }
  30790. if (camera === void 0) { camera = null; }
  30791. if (rootElement === void 0) { rootElement = null; }
  30792. if (this._enabled) {
  30793. return;
  30794. }
  30795. this._enabled = true;
  30796. if (camera) {
  30797. this._camera = camera;
  30798. }
  30799. else {
  30800. this._camera = this._scene.activeCamera;
  30801. }
  30802. this._showUI = showUI;
  30803. var engine = this._scene.getEngine();
  30804. this._globalDiv = document.createElement("div");
  30805. this._rootElement = rootElement || document.body;
  30806. this._rootElement.appendChild(this._globalDiv);
  30807. this._generateDOMelements();
  30808. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30809. this._syncPositions();
  30810. this._scene.registerBeforeRender(this._syncData);
  30811. this._scene.registerAfterRender(this._syncUI);
  30812. };
  30813. DebugLayer.prototype._clearLabels = function () {
  30814. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30815. for (var index = 0; index < this._scene.meshes.length; index++) {
  30816. var mesh = this._scene.meshes[index];
  30817. mesh.renderOverlay = false;
  30818. }
  30819. };
  30820. DebugLayer.prototype._generateheader = function (root, text) {
  30821. var header = document.createElement("div");
  30822. header.innerHTML = text + "&nbsp;";
  30823. header.style.textAlign = "right";
  30824. header.style.width = "100%";
  30825. header.style.color = "white";
  30826. header.style.backgroundColor = "Black";
  30827. header.style.padding = "5px 5px 4px 0px";
  30828. header.style.marginLeft = "-5px";
  30829. header.style.fontWeight = "bold";
  30830. root.appendChild(header);
  30831. };
  30832. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30833. var label = document.createElement("label");
  30834. label.innerHTML = title;
  30835. label.style.color = color;
  30836. root.appendChild(label);
  30837. root.appendChild(document.createElement("br"));
  30838. };
  30839. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30840. if (tag === void 0) { tag = null; }
  30841. var label = document.createElement("label");
  30842. var boundingBoxesCheckbox = document.createElement("input");
  30843. boundingBoxesCheckbox.type = "checkbox";
  30844. boundingBoxesCheckbox.checked = initialState;
  30845. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30846. task(evt.target, tag);
  30847. });
  30848. label.appendChild(boundingBoxesCheckbox);
  30849. var container = document.createElement("span");
  30850. var leftPart = document.createElement("span");
  30851. var rightPart = document.createElement("span");
  30852. rightPart.style.cssFloat = "right";
  30853. leftPart.innerHTML = leftTitle;
  30854. rightPart.innerHTML = rightTitle;
  30855. rightPart.style.fontSize = "12px";
  30856. rightPart.style.maxWidth = "200px";
  30857. container.appendChild(leftPart);
  30858. container.appendChild(rightPart);
  30859. label.appendChild(container);
  30860. root.appendChild(label);
  30861. root.appendChild(document.createElement("br"));
  30862. };
  30863. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30864. if (tag === void 0) { tag = null; }
  30865. var label = document.createElement("label");
  30866. var checkBox = document.createElement("input");
  30867. checkBox.type = "checkbox";
  30868. checkBox.checked = initialState;
  30869. checkBox.addEventListener("change", function (evt) {
  30870. task(evt.target, tag);
  30871. });
  30872. label.appendChild(checkBox);
  30873. label.appendChild(document.createTextNode(title));
  30874. root.appendChild(label);
  30875. root.appendChild(document.createElement("br"));
  30876. };
  30877. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30878. if (tag === void 0) { tag = null; }
  30879. var button = document.createElement("button");
  30880. button.innerHTML = title;
  30881. button.style.height = "24px";
  30882. button.style.width = "150px";
  30883. button.style.marginBottom = "5px";
  30884. button.style.color = "#444444";
  30885. button.style.border = "1px solid white";
  30886. button.className = "debugLayerButton";
  30887. button.addEventListener("click", function (evt) {
  30888. task(evt.target, tag);
  30889. });
  30890. root.appendChild(button);
  30891. root.appendChild(document.createElement("br"));
  30892. };
  30893. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30894. if (tag === void 0) { tag = null; }
  30895. var label = document.createElement("label");
  30896. var boundingBoxesRadio = document.createElement("input");
  30897. boundingBoxesRadio.type = "radio";
  30898. boundingBoxesRadio.name = name;
  30899. boundingBoxesRadio.checked = initialState;
  30900. boundingBoxesRadio.addEventListener("change", function (evt) {
  30901. task(evt.target, tag);
  30902. });
  30903. label.appendChild(boundingBoxesRadio);
  30904. label.appendChild(document.createTextNode(title));
  30905. root.appendChild(label);
  30906. root.appendChild(document.createElement("br"));
  30907. };
  30908. DebugLayer.prototype._generateDOMelements = function () {
  30909. var _this = this;
  30910. this._globalDiv.id = "DebugLayer";
  30911. this._globalDiv.style.position = "absolute";
  30912. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30913. this._globalDiv.style.fontSize = "14px";
  30914. this._globalDiv.style.color = "white";
  30915. // Drawing canvas
  30916. this._drawingCanvas = document.createElement("canvas");
  30917. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30918. this._drawingCanvas.style.position = "absolute";
  30919. this._drawingCanvas.style.pointerEvents = "none";
  30920. this._drawingCanvas.style.backgroundColor = "transparent";
  30921. this._drawingContext = this._drawingCanvas.getContext("2d");
  30922. this._globalDiv.appendChild(this._drawingCanvas);
  30923. if (this._showUI) {
  30924. var background = "rgba(128, 128, 128, 0.4)";
  30925. var border = "rgb(180, 180, 180) solid 1px";
  30926. // Stats
  30927. this._statsDiv = document.createElement("div");
  30928. this._statsDiv.id = "DebugLayerStats";
  30929. this._statsDiv.style.border = border;
  30930. this._statsDiv.style.position = "absolute";
  30931. this._statsDiv.style.background = background;
  30932. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30933. this._generateheader(this._statsDiv, "STATISTICS");
  30934. this._statsSubsetDiv = document.createElement("div");
  30935. this._statsSubsetDiv.style.paddingTop = "5px";
  30936. this._statsSubsetDiv.style.paddingBottom = "5px";
  30937. this._statsSubsetDiv.style.overflowY = "auto";
  30938. this._statsDiv.appendChild(this._statsSubsetDiv);
  30939. // Tree
  30940. this._treeDiv = document.createElement("div");
  30941. this._treeDiv.id = "DebugLayerTree";
  30942. this._treeDiv.style.border = border;
  30943. this._treeDiv.style.position = "absolute";
  30944. this._treeDiv.style.background = background;
  30945. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30946. this._treeDiv.style.display = "none";
  30947. this._generateheader(this._treeDiv, "MESHES TREE");
  30948. this._treeSubsetDiv = document.createElement("div");
  30949. this._treeSubsetDiv.style.paddingTop = "5px";
  30950. this._treeSubsetDiv.style.paddingRight = "5px";
  30951. this._treeSubsetDiv.style.overflowY = "auto";
  30952. this._treeSubsetDiv.style.maxHeight = "300px";
  30953. this._treeDiv.appendChild(this._treeSubsetDiv);
  30954. this._needToRefreshMeshesTree = true;
  30955. // Logs
  30956. this._logDiv = document.createElement("div");
  30957. this._logDiv.style.border = border;
  30958. this._logDiv.id = "DebugLayerLogs";
  30959. this._logDiv.style.position = "absolute";
  30960. this._logDiv.style.background = background;
  30961. this._logDiv.style.padding = "0px 0px 0px 5px";
  30962. this._logDiv.style.display = "none";
  30963. this._generateheader(this._logDiv, "LOGS");
  30964. this._logSubsetDiv = document.createElement("div");
  30965. this._logSubsetDiv.style.height = "127px";
  30966. this._logSubsetDiv.style.paddingTop = "5px";
  30967. this._logSubsetDiv.style.overflowY = "auto";
  30968. this._logSubsetDiv.style.fontSize = "12px";
  30969. this._logSubsetDiv.style.fontFamily = "consolas";
  30970. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30971. this._logDiv.appendChild(this._logSubsetDiv);
  30972. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30973. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30974. };
  30975. // Options
  30976. this._optionsDiv = document.createElement("div");
  30977. this._optionsDiv.id = "DebugLayerOptions";
  30978. this._optionsDiv.style.border = border;
  30979. this._optionsDiv.style.position = "absolute";
  30980. this._optionsDiv.style.background = background;
  30981. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30982. this._optionsDiv.style.overflowY = "auto";
  30983. this._generateheader(this._optionsDiv, "OPTIONS");
  30984. this._optionsSubsetDiv = document.createElement("div");
  30985. this._optionsSubsetDiv.style.paddingTop = "5px";
  30986. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30987. this._optionsSubsetDiv.style.overflowY = "auto";
  30988. this._optionsSubsetDiv.style.maxHeight = "200px";
  30989. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30990. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30991. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30992. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30993. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  30994. _this._displayTree = element.checked;
  30995. _this._needToRefreshMeshesTree = true;
  30996. });
  30997. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30998. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  30999. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31000. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31001. _this._labelsEnabled = element.checked;
  31002. if (!_this._labelsEnabled) {
  31003. _this._clearLabels();
  31004. }
  31005. });
  31006. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31007. if (element.checked) {
  31008. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31009. }
  31010. else {
  31011. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31012. }
  31013. });
  31014. ;
  31015. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31016. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31017. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31018. if (element.checked) {
  31019. _this._scene.forceWireframe = false;
  31020. _this._scene.forcePointsCloud = false;
  31021. }
  31022. });
  31023. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31024. if (element.checked) {
  31025. _this._scene.forceWireframe = true;
  31026. _this._scene.forcePointsCloud = false;
  31027. }
  31028. });
  31029. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31030. if (element.checked) {
  31031. _this._scene.forceWireframe = false;
  31032. _this._scene.forcePointsCloud = true;
  31033. }
  31034. });
  31035. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31036. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31037. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31038. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31039. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31040. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31041. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31042. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31043. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31044. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  31045. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  31046. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31047. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31048. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31049. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31050. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31051. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31052. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31053. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31054. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31055. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31056. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  31057. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31058. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31059. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31060. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31061. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31062. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31063. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  31064. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31065. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31066. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31067. if (element.checked) {
  31068. _this._scene.headphone = true;
  31069. }
  31070. });
  31071. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31072. if (element.checked) {
  31073. _this._scene.headphone = false;
  31074. }
  31075. });
  31076. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31077. _this._scene.audioEnabled = !element.checked;
  31078. });
  31079. }
  31080. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31081. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  31082. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  31083. if (!element.checked) {
  31084. _this._clearSkeletonViewers();
  31085. return;
  31086. }
  31087. for (var index = 0; index < _this._scene.meshes.length; index++) {
  31088. var mesh = _this._scene.meshes[index];
  31089. if (mesh.skeleton) {
  31090. var found = false;
  31091. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  31092. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  31093. found = true;
  31094. break;
  31095. }
  31096. }
  31097. if (found) {
  31098. continue;
  31099. }
  31100. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  31101. viewer.isEnabled = true;
  31102. _this._skeletonViewers.push(viewer);
  31103. }
  31104. }
  31105. });
  31106. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31107. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31108. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31109. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  31110. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  31111. if (_this._camera) {
  31112. console.log(_this._camera);
  31113. }
  31114. else {
  31115. console.warn("No camera defined, or debug layer created before camera creation!");
  31116. }
  31117. });
  31118. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31119. this._globalDiv.appendChild(this._statsDiv);
  31120. this._globalDiv.appendChild(this._logDiv);
  31121. this._globalDiv.appendChild(this._optionsDiv);
  31122. this._globalDiv.appendChild(this._treeDiv);
  31123. }
  31124. };
  31125. DebugLayer.prototype._displayStats = function () {
  31126. var scene = this._scene;
  31127. var engine = scene.getEngine();
  31128. var glInfo = engine.getGlInfo();
  31129. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31130. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31131. + "<b>Count</b><br>"
  31132. + "Total meshes: " + scene.meshes.length + "<br>"
  31133. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31134. + "Total materials: " + scene.materials.length + "<br>"
  31135. + "Total textures: " + scene.textures.length + "<br>"
  31136. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31137. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31138. + "Active bones: " + scene.getActiveBones() + "<br>"
  31139. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31140. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  31141. + "<b>Duration</b><br>"
  31142. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31143. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31144. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31145. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31146. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31147. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31148. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  31149. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  31150. + "</div>"
  31151. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31152. + "<b>Extensions</b><br>"
  31153. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31154. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31155. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31156. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  31157. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31158. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  31159. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  31160. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  31161. + "</div><br>"
  31162. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31163. + "<b>Caps.</b><br>"
  31164. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31165. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31166. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  31167. + "<b>Info</b><br>"
  31168. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  31169. + glInfo.version + "<br>"
  31170. + "</div><br>"
  31171. + glInfo.renderer + "<br>";
  31172. if (this.customStatsFunction) {
  31173. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31174. }
  31175. };
  31176. return DebugLayer;
  31177. })();
  31178. BABYLON.DebugLayer = DebugLayer;
  31179. })(BABYLON || (BABYLON = {}));
  31180. var BABYLON;
  31181. (function (BABYLON) {
  31182. var DefaultLoadingScreen = (function () {
  31183. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  31184. var _this = this;
  31185. if (_loadingText === void 0) { _loadingText = ""; }
  31186. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  31187. this._renderingCanvas = _renderingCanvas;
  31188. this._loadingText = _loadingText;
  31189. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  31190. // Resize
  31191. this._resizeLoadingUI = function () {
  31192. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  31193. _this._loadingDiv.style.position = "absolute";
  31194. _this._loadingDiv.style.left = canvasRect.left + "px";
  31195. _this._loadingDiv.style.top = canvasRect.top + "px";
  31196. _this._loadingDiv.style.width = canvasRect.width + "px";
  31197. _this._loadingDiv.style.height = canvasRect.height + "px";
  31198. };
  31199. }
  31200. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  31201. var _this = this;
  31202. if (this._loadingDiv) {
  31203. // Do not add a loading screen if there is already one
  31204. return;
  31205. }
  31206. this._loadingDiv = document.createElement("div");
  31207. this._loadingDiv.id = "babylonjsLoadingDiv";
  31208. this._loadingDiv.style.opacity = "0";
  31209. this._loadingDiv.style.transition = "opacity 1.5s ease";
  31210. // Loading text
  31211. this._loadingTextDiv = document.createElement("div");
  31212. this._loadingTextDiv.style.position = "absolute";
  31213. this._loadingTextDiv.style.left = "0";
  31214. this._loadingTextDiv.style.top = "50%";
  31215. this._loadingTextDiv.style.marginTop = "80px";
  31216. this._loadingTextDiv.style.width = "100%";
  31217. this._loadingTextDiv.style.height = "20px";
  31218. this._loadingTextDiv.style.fontFamily = "Arial";
  31219. this._loadingTextDiv.style.fontSize = "14px";
  31220. this._loadingTextDiv.style.color = "white";
  31221. this._loadingTextDiv.style.textAlign = "center";
  31222. this._loadingTextDiv.innerHTML = "Loading";
  31223. this._loadingDiv.appendChild(this._loadingTextDiv);
  31224. //set the predefined text
  31225. this._loadingTextDiv.innerHTML = this._loadingText;
  31226. // Loading img
  31227. var imgBack = new Image();
  31228. 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==";
  31229. imgBack.style.position = "absolute";
  31230. imgBack.style.left = "50%";
  31231. imgBack.style.top = "50%";
  31232. imgBack.style.marginLeft = "-50px";
  31233. imgBack.style.marginTop = "-50px";
  31234. imgBack.style.transition = "transform 1.0s ease";
  31235. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  31236. var deg = 360;
  31237. var onTransitionEnd = function () {
  31238. deg += 360;
  31239. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  31240. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  31241. };
  31242. imgBack.addEventListener("transitionend", onTransitionEnd);
  31243. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  31244. this._loadingDiv.appendChild(imgBack);
  31245. // front image
  31246. var imgFront = new Image();
  31247. 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=";
  31248. imgFront.style.position = "absolute";
  31249. imgFront.style.left = "50%";
  31250. imgFront.style.top = "50%";
  31251. imgFront.style.marginLeft = "-50px";
  31252. imgFront.style.marginTop = "-50px";
  31253. this._loadingDiv.appendChild(imgFront);
  31254. this._resizeLoadingUI();
  31255. window.addEventListener("resize", this._resizeLoadingUI);
  31256. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  31257. document.body.appendChild(this._loadingDiv);
  31258. setTimeout(function () {
  31259. _this._loadingDiv.style.opacity = "1";
  31260. imgBack.style.transform = "rotateZ(360deg)";
  31261. imgBack.style.webkitTransform = "rotateZ(360deg)";
  31262. }, 0);
  31263. };
  31264. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  31265. var _this = this;
  31266. if (!this._loadingDiv) {
  31267. return;
  31268. }
  31269. var onTransitionEnd = function () {
  31270. if (!_this._loadingDiv) {
  31271. return;
  31272. }
  31273. document.body.removeChild(_this._loadingDiv);
  31274. window.removeEventListener("resize", _this._resizeLoadingUI);
  31275. _this._loadingDiv = null;
  31276. };
  31277. this._loadingDiv.style.opacity = "0";
  31278. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  31279. };
  31280. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  31281. set: function (text) {
  31282. this._loadingText = text;
  31283. if (this._loadingTextDiv) {
  31284. this._loadingTextDiv.innerHTML = this._loadingText;
  31285. }
  31286. },
  31287. enumerable: true,
  31288. configurable: true
  31289. });
  31290. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  31291. get: function () {
  31292. return this._loadingDivBackgroundColor;
  31293. },
  31294. set: function (color) {
  31295. this._loadingDivBackgroundColor = color;
  31296. if (!this._loadingDiv) {
  31297. return;
  31298. }
  31299. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  31300. },
  31301. enumerable: true,
  31302. configurable: true
  31303. });
  31304. return DefaultLoadingScreen;
  31305. })();
  31306. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  31307. })(BABYLON || (BABYLON = {}));
  31308. var BABYLON;
  31309. (function (BABYLON) {
  31310. var AudioEngine = (function () {
  31311. function AudioEngine() {
  31312. this._audioContext = null;
  31313. this._audioContextInitialized = false;
  31314. this.canUseWebAudio = false;
  31315. this.WarnedWebAudioUnsupported = false;
  31316. this.unlocked = false;
  31317. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  31318. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  31319. this.canUseWebAudio = true;
  31320. }
  31321. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  31322. this._unlockiOSaudio();
  31323. }
  31324. else {
  31325. this.unlocked = true;
  31326. }
  31327. }
  31328. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  31329. get: function () {
  31330. if (!this._audioContextInitialized) {
  31331. this._initializeAudioContext();
  31332. }
  31333. return this._audioContext;
  31334. },
  31335. enumerable: true,
  31336. configurable: true
  31337. });
  31338. AudioEngine.prototype._unlockiOSaudio = function () {
  31339. var _this = this;
  31340. var unlockaudio = function () {
  31341. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  31342. var source = _this.audioContext.createBufferSource();
  31343. source.buffer = buffer;
  31344. source.connect(_this.audioContext.destination);
  31345. source.start(0);
  31346. setTimeout(function () {
  31347. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  31348. _this.unlocked = true;
  31349. window.removeEventListener('touchend', unlockaudio, false);
  31350. if (_this.onAudioUnlocked) {
  31351. _this.onAudioUnlocked();
  31352. }
  31353. }
  31354. }, 0);
  31355. };
  31356. window.addEventListener('touchend', unlockaudio, false);
  31357. };
  31358. AudioEngine.prototype._initializeAudioContext = function () {
  31359. try {
  31360. if (this.canUseWebAudio) {
  31361. this._audioContext = new AudioContext();
  31362. // create a global volume gain node
  31363. this.masterGain = this._audioContext.createGain();
  31364. this.masterGain.gain.value = 1;
  31365. this.masterGain.connect(this._audioContext.destination);
  31366. this._audioContextInitialized = true;
  31367. }
  31368. }
  31369. catch (e) {
  31370. this.canUseWebAudio = false;
  31371. BABYLON.Tools.Error("Web Audio: " + e.message);
  31372. }
  31373. };
  31374. AudioEngine.prototype.dispose = function () {
  31375. if (this.canUseWebAudio && this._audioContextInitialized) {
  31376. if (this._connectedAnalyser) {
  31377. this._connectedAnalyser.stopDebugCanvas();
  31378. this._connectedAnalyser.dispose();
  31379. this.masterGain.disconnect();
  31380. this.masterGain.connect(this._audioContext.destination);
  31381. this._connectedAnalyser = null;
  31382. }
  31383. this.masterGain.gain.value = 1;
  31384. }
  31385. this.WarnedWebAudioUnsupported = false;
  31386. };
  31387. AudioEngine.prototype.getGlobalVolume = function () {
  31388. if (this.canUseWebAudio && this._audioContextInitialized) {
  31389. return this.masterGain.gain.value;
  31390. }
  31391. else {
  31392. return -1;
  31393. }
  31394. };
  31395. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  31396. if (this.canUseWebAudio && this._audioContextInitialized) {
  31397. this.masterGain.gain.value = newVolume;
  31398. }
  31399. };
  31400. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  31401. if (this._connectedAnalyser) {
  31402. this._connectedAnalyser.stopDebugCanvas();
  31403. }
  31404. if (this.canUseWebAudio && this._audioContextInitialized) {
  31405. this._connectedAnalyser = analyser;
  31406. this.masterGain.disconnect();
  31407. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  31408. }
  31409. };
  31410. return AudioEngine;
  31411. })();
  31412. BABYLON.AudioEngine = AudioEngine;
  31413. })(BABYLON || (BABYLON = {}));
  31414. var BABYLON;
  31415. (function (BABYLON) {
  31416. var Sound = (function () {
  31417. /**
  31418. * Create a sound and attach it to a scene
  31419. * @param name Name of your sound
  31420. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  31421. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  31422. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  31423. */
  31424. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  31425. var _this = this;
  31426. this.autoplay = false;
  31427. this.loop = false;
  31428. this.useCustomAttenuation = false;
  31429. this.spatialSound = false;
  31430. this.refDistance = 1;
  31431. this.rolloffFactor = 1;
  31432. this.maxDistance = 100;
  31433. this.distanceModel = "linear";
  31434. this._panningModel = "equalpower";
  31435. this._playbackRate = 1;
  31436. this._streaming = false;
  31437. this._startTime = 0;
  31438. this._startOffset = 0;
  31439. this._position = BABYLON.Vector3.Zero();
  31440. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  31441. this._volume = 1;
  31442. this._isLoaded = false;
  31443. this._isReadyToPlay = false;
  31444. this.isPlaying = false;
  31445. this.isPaused = false;
  31446. this._isDirectional = false;
  31447. // Used if you'd like to create a directional sound.
  31448. // If not set, the sound will be omnidirectional
  31449. this._coneInnerAngle = 360;
  31450. this._coneOuterAngle = 360;
  31451. this._coneOuterGain = 0;
  31452. this._isOutputConnected = false;
  31453. this.name = name;
  31454. this._scene = scene;
  31455. this._readyToPlayCallback = readyToPlayCallback;
  31456. // Default custom attenuation function is a linear attenuation
  31457. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  31458. if (currentDistance < maxDistance) {
  31459. return currentVolume * (1 - currentDistance / maxDistance);
  31460. }
  31461. else {
  31462. return 0;
  31463. }
  31464. };
  31465. if (options) {
  31466. this.autoplay = options.autoplay || false;
  31467. this.loop = options.loop || false;
  31468. // if volume === 0, we need another way to check this option
  31469. if (options.volume !== undefined) {
  31470. this._volume = options.volume;
  31471. }
  31472. this.spatialSound = options.spatialSound || false;
  31473. this.maxDistance = options.maxDistance || 100;
  31474. this.useCustomAttenuation = options.useCustomAttenuation || false;
  31475. this.rolloffFactor = options.rolloffFactor || 1;
  31476. this.refDistance = options.refDistance || 1;
  31477. this.distanceModel = options.distanceModel || "linear";
  31478. this._playbackRate = options.playbackRate || 1;
  31479. this._streaming = options.streaming || false;
  31480. }
  31481. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31482. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  31483. this._soundGain.gain.value = this._volume;
  31484. this._inputAudioNode = this._soundGain;
  31485. this._ouputAudioNode = this._soundGain;
  31486. if (this.spatialSound) {
  31487. this._createSpatialParameters();
  31488. }
  31489. this._scene.mainSoundTrack.AddSound(this);
  31490. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  31491. if (urlOrArrayBuffer) {
  31492. // If it's an URL
  31493. if (typeof (urlOrArrayBuffer) === "string") {
  31494. // Loading sound using XHR2
  31495. if (!this._streaming) {
  31496. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  31497. }
  31498. else {
  31499. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  31500. this._htmlAudioElement.controls = false;
  31501. this._htmlAudioElement.loop = this.loop;
  31502. this._htmlAudioElement.crossOrigin = "anonymous";
  31503. this._htmlAudioElement.preload = "auto";
  31504. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  31505. _this._isReadyToPlay = true;
  31506. if (_this.autoplay) {
  31507. _this.play();
  31508. }
  31509. if (_this._readyToPlayCallback) {
  31510. _this._readyToPlayCallback();
  31511. }
  31512. });
  31513. document.body.appendChild(this._htmlAudioElement);
  31514. }
  31515. }
  31516. else {
  31517. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  31518. if (urlOrArrayBuffer.byteLength > 0) {
  31519. this._soundLoaded(urlOrArrayBuffer);
  31520. }
  31521. }
  31522. else {
  31523. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  31524. }
  31525. }
  31526. }
  31527. }
  31528. else {
  31529. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  31530. this._scene.mainSoundTrack.AddSound(this);
  31531. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  31532. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  31533. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  31534. }
  31535. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  31536. if (this._readyToPlayCallback) {
  31537. window.setTimeout(function () {
  31538. _this._readyToPlayCallback();
  31539. }, 1000);
  31540. }
  31541. }
  31542. }
  31543. Sound.prototype.dispose = function () {
  31544. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  31545. if (this.isPlaying) {
  31546. this.stop();
  31547. }
  31548. this._isReadyToPlay = false;
  31549. if (this.soundTrackId === -1) {
  31550. this._scene.mainSoundTrack.RemoveSound(this);
  31551. }
  31552. else {
  31553. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  31554. }
  31555. if (this._soundGain) {
  31556. this._soundGain.disconnect();
  31557. this._soundGain = null;
  31558. }
  31559. if (this._soundPanner) {
  31560. this._soundPanner.disconnect();
  31561. this._soundPanner = null;
  31562. }
  31563. if (this._soundSource) {
  31564. this._soundSource.disconnect();
  31565. this._soundSource = null;
  31566. }
  31567. this._audioBuffer = null;
  31568. if (this._htmlAudioElement) {
  31569. this._htmlAudioElement.pause();
  31570. this._htmlAudioElement.src = "";
  31571. document.body.removeChild(this._htmlAudioElement);
  31572. }
  31573. if (this._connectedMesh) {
  31574. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  31575. this._connectedMesh = null;
  31576. }
  31577. }
  31578. };
  31579. Sound.prototype._soundLoaded = function (audioData) {
  31580. var _this = this;
  31581. this._isLoaded = true;
  31582. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  31583. _this._audioBuffer = buffer;
  31584. _this._isReadyToPlay = true;
  31585. if (_this.autoplay) {
  31586. _this.play();
  31587. }
  31588. if (_this._readyToPlayCallback) {
  31589. _this._readyToPlayCallback();
  31590. }
  31591. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  31592. };
  31593. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  31594. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31595. this._audioBuffer = audioBuffer;
  31596. this._isReadyToPlay = true;
  31597. }
  31598. };
  31599. Sound.prototype.updateOptions = function (options) {
  31600. if (options) {
  31601. this.loop = options.loop || this.loop;
  31602. this.maxDistance = options.maxDistance || this.maxDistance;
  31603. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  31604. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  31605. this.refDistance = options.refDistance || this.refDistance;
  31606. this.distanceModel = options.distanceModel || this.distanceModel;
  31607. this._playbackRate = options.playbackRate || this._playbackRate;
  31608. this._updateSpatialParameters();
  31609. if (this.isPlaying) {
  31610. if (this._streaming) {
  31611. this._htmlAudioElement.playbackRate = this._playbackRate;
  31612. }
  31613. else {
  31614. this._soundSource.playbackRate.value = this._playbackRate;
  31615. }
  31616. }
  31617. }
  31618. };
  31619. Sound.prototype._createSpatialParameters = function () {
  31620. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31621. if (this._scene.headphone) {
  31622. this._panningModel = "HRTF";
  31623. }
  31624. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  31625. this._updateSpatialParameters();
  31626. this._soundPanner.connect(this._ouputAudioNode);
  31627. this._inputAudioNode = this._soundPanner;
  31628. }
  31629. };
  31630. Sound.prototype._updateSpatialParameters = function () {
  31631. if (this.spatialSound) {
  31632. if (this.useCustomAttenuation) {
  31633. // Tricks to disable in a way embedded Web Audio attenuation
  31634. this._soundPanner.distanceModel = "linear";
  31635. this._soundPanner.maxDistance = Number.MAX_VALUE;
  31636. this._soundPanner.refDistance = 1;
  31637. this._soundPanner.rolloffFactor = 1;
  31638. this._soundPanner.panningModel = this._panningModel;
  31639. }
  31640. else {
  31641. this._soundPanner.distanceModel = this.distanceModel;
  31642. this._soundPanner.maxDistance = this.maxDistance;
  31643. this._soundPanner.refDistance = this.refDistance;
  31644. this._soundPanner.rolloffFactor = this.rolloffFactor;
  31645. this._soundPanner.panningModel = this._panningModel;
  31646. }
  31647. }
  31648. };
  31649. Sound.prototype.switchPanningModelToHRTF = function () {
  31650. this._panningModel = "HRTF";
  31651. this._switchPanningModel();
  31652. };
  31653. Sound.prototype.switchPanningModelToEqualPower = function () {
  31654. this._panningModel = "equalpower";
  31655. this._switchPanningModel();
  31656. };
  31657. Sound.prototype._switchPanningModel = function () {
  31658. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31659. this._soundPanner.panningModel = this._panningModel;
  31660. }
  31661. };
  31662. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  31663. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31664. if (this._isOutputConnected) {
  31665. this._ouputAudioNode.disconnect();
  31666. }
  31667. this._ouputAudioNode.connect(soundTrackAudioNode);
  31668. this._isOutputConnected = true;
  31669. }
  31670. };
  31671. /**
  31672. * Transform this sound into a directional source
  31673. * @param coneInnerAngle Size of the inner cone in degree
  31674. * @param coneOuterAngle Size of the outer cone in degree
  31675. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  31676. */
  31677. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  31678. if (coneOuterAngle < coneInnerAngle) {
  31679. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  31680. return;
  31681. }
  31682. this._coneInnerAngle = coneInnerAngle;
  31683. this._coneOuterAngle = coneOuterAngle;
  31684. this._coneOuterGain = coneOuterGain;
  31685. this._isDirectional = true;
  31686. if (this.isPlaying && this.loop) {
  31687. this.stop();
  31688. this.play();
  31689. }
  31690. };
  31691. Sound.prototype.setPosition = function (newPosition) {
  31692. this._position = newPosition;
  31693. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31694. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31695. }
  31696. };
  31697. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  31698. this._localDirection = newLocalDirection;
  31699. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  31700. this._updateDirection();
  31701. }
  31702. };
  31703. Sound.prototype._updateDirection = function () {
  31704. var mat = this._connectedMesh.getWorldMatrix();
  31705. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  31706. direction.normalize();
  31707. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  31708. };
  31709. Sound.prototype.updateDistanceFromListener = function () {
  31710. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  31711. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  31712. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  31713. }
  31714. };
  31715. Sound.prototype.setAttenuationFunction = function (callback) {
  31716. this._customAttenuationFunction = callback;
  31717. };
  31718. /**
  31719. * Play the sound
  31720. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  31721. */
  31722. Sound.prototype.play = function (time) {
  31723. var _this = this;
  31724. if (this._isReadyToPlay && this._scene.audioEnabled) {
  31725. try {
  31726. if (this._startOffset < 0) {
  31727. time = -this._startOffset;
  31728. this._startOffset = 0;
  31729. }
  31730. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  31731. if (!this._soundSource || !this._streamingSource) {
  31732. if (this.spatialSound) {
  31733. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31734. if (this._isDirectional) {
  31735. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  31736. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  31737. this._soundPanner.coneOuterGain = this._coneOuterGain;
  31738. if (this._connectedMesh) {
  31739. this._updateDirection();
  31740. }
  31741. else {
  31742. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  31743. }
  31744. }
  31745. }
  31746. }
  31747. if (this._streaming) {
  31748. if (!this._streamingSource) {
  31749. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  31750. this._htmlAudioElement.onended = function () { _this._onended(); };
  31751. this._htmlAudioElement.playbackRate = this._playbackRate;
  31752. }
  31753. this._streamingSource.disconnect();
  31754. this._streamingSource.connect(this._inputAudioNode);
  31755. this._htmlAudioElement.play();
  31756. }
  31757. else {
  31758. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  31759. this._soundSource.buffer = this._audioBuffer;
  31760. this._soundSource.connect(this._inputAudioNode);
  31761. this._soundSource.loop = this.loop;
  31762. this._soundSource.playbackRate.value = this._playbackRate;
  31763. this._soundSource.onended = function () { _this._onended(); };
  31764. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  31765. }
  31766. this._startTime = startTime;
  31767. this.isPlaying = true;
  31768. this.isPaused = false;
  31769. }
  31770. catch (ex) {
  31771. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  31772. }
  31773. }
  31774. };
  31775. Sound.prototype._onended = function () {
  31776. this.isPlaying = false;
  31777. if (this.onended) {
  31778. this.onended();
  31779. }
  31780. };
  31781. /**
  31782. * Stop the sound
  31783. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  31784. */
  31785. Sound.prototype.stop = function (time) {
  31786. if (this.isPlaying) {
  31787. if (this._streaming) {
  31788. this._htmlAudioElement.pause();
  31789. // Test needed for Firefox or it will generate an Invalid State Error
  31790. if (this._htmlAudioElement.currentTime > 0) {
  31791. this._htmlAudioElement.currentTime = 0;
  31792. }
  31793. }
  31794. else {
  31795. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  31796. this._soundSource.stop(stopTime);
  31797. if (!this.isPaused) {
  31798. this._startOffset = 0;
  31799. }
  31800. }
  31801. this.isPlaying = false;
  31802. }
  31803. };
  31804. Sound.prototype.pause = function () {
  31805. if (this.isPlaying) {
  31806. this.isPaused = true;
  31807. if (this._streaming) {
  31808. this._htmlAudioElement.pause();
  31809. }
  31810. else {
  31811. this.stop(0);
  31812. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  31813. }
  31814. }
  31815. };
  31816. Sound.prototype.setVolume = function (newVolume, time) {
  31817. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31818. if (time) {
  31819. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  31820. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  31821. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  31822. }
  31823. else {
  31824. this._soundGain.gain.value = newVolume;
  31825. }
  31826. }
  31827. this._volume = newVolume;
  31828. };
  31829. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  31830. this._playbackRate = newPlaybackRate;
  31831. if (this.isPlaying) {
  31832. if (this._streaming) {
  31833. this._htmlAudioElement.playbackRate = this._playbackRate;
  31834. }
  31835. else {
  31836. this._soundSource.playbackRate.value = this._playbackRate;
  31837. }
  31838. }
  31839. };
  31840. Sound.prototype.getVolume = function () {
  31841. return this._volume;
  31842. };
  31843. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  31844. var _this = this;
  31845. if (this._connectedMesh) {
  31846. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  31847. this._registerFunc = null;
  31848. }
  31849. this._connectedMesh = meshToConnectTo;
  31850. if (!this.spatialSound) {
  31851. this.spatialSound = true;
  31852. this._createSpatialParameters();
  31853. if (this.isPlaying && this.loop) {
  31854. this.stop();
  31855. this.play();
  31856. }
  31857. }
  31858. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  31859. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  31860. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  31861. };
  31862. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  31863. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  31864. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  31865. this._updateDirection();
  31866. }
  31867. };
  31868. Sound.prototype.clone = function () {
  31869. var _this = this;
  31870. if (!this._streaming) {
  31871. var setBufferAndRun = function () {
  31872. if (_this._isReadyToPlay) {
  31873. clonedSound._audioBuffer = _this.getAudioBuffer();
  31874. clonedSound._isReadyToPlay = true;
  31875. if (clonedSound.autoplay) {
  31876. clonedSound.play();
  31877. }
  31878. }
  31879. else {
  31880. window.setTimeout(setBufferAndRun, 300);
  31881. }
  31882. };
  31883. var currentOptions = {
  31884. autoplay: this.autoplay, loop: this.loop,
  31885. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  31886. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  31887. refDistance: this.refDistance, distanceModel: this.distanceModel
  31888. };
  31889. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  31890. if (this.useCustomAttenuation) {
  31891. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  31892. }
  31893. clonedSound.setPosition(this._position);
  31894. clonedSound.setPlaybackRate(this._playbackRate);
  31895. setBufferAndRun();
  31896. return clonedSound;
  31897. }
  31898. else {
  31899. return null;
  31900. }
  31901. };
  31902. Sound.prototype.getAudioBuffer = function () {
  31903. return this._audioBuffer;
  31904. };
  31905. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  31906. var soundName = parsedSound.name;
  31907. var soundUrl;
  31908. if (parsedSound.url) {
  31909. soundUrl = rootUrl + parsedSound.url;
  31910. }
  31911. else {
  31912. soundUrl = rootUrl + soundName;
  31913. }
  31914. var options = {
  31915. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  31916. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  31917. rolloffFactor: parsedSound.rolloffFactor,
  31918. refDistance: parsedSound.refDistance,
  31919. distanceModel: parsedSound.distanceModel,
  31920. playbackRate: parsedSound.playbackRate
  31921. };
  31922. var newSound;
  31923. if (!sourceSound) {
  31924. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  31925. scene._addPendingData(newSound);
  31926. }
  31927. else {
  31928. var setBufferAndRun = function () {
  31929. if (sourceSound._isReadyToPlay) {
  31930. newSound._audioBuffer = sourceSound.getAudioBuffer();
  31931. newSound._isReadyToPlay = true;
  31932. if (newSound.autoplay) {
  31933. newSound.play();
  31934. }
  31935. }
  31936. else {
  31937. window.setTimeout(setBufferAndRun, 300);
  31938. }
  31939. };
  31940. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  31941. setBufferAndRun();
  31942. }
  31943. if (parsedSound.position) {
  31944. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  31945. newSound.setPosition(soundPosition);
  31946. }
  31947. if (parsedSound.isDirectional) {
  31948. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  31949. if (parsedSound.localDirectionToMesh) {
  31950. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  31951. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  31952. }
  31953. }
  31954. if (parsedSound.connectedMeshId) {
  31955. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  31956. if (connectedMesh) {
  31957. newSound.attachToMesh(connectedMesh);
  31958. }
  31959. }
  31960. return newSound;
  31961. };
  31962. return Sound;
  31963. })();
  31964. BABYLON.Sound = Sound;
  31965. })(BABYLON || (BABYLON = {}));
  31966. var BABYLON;
  31967. (function (BABYLON) {
  31968. var SoundTrack = (function () {
  31969. function SoundTrack(scene, options) {
  31970. this.id = -1;
  31971. this._isMainTrack = false;
  31972. this._isInitialized = false;
  31973. this._scene = scene;
  31974. this.soundCollection = new Array();
  31975. this._options = options;
  31976. if (!this._isMainTrack) {
  31977. this._scene.soundTracks.push(this);
  31978. this.id = this._scene.soundTracks.length - 1;
  31979. }
  31980. }
  31981. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  31982. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31983. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  31984. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  31985. if (this._options) {
  31986. if (this._options.volume) {
  31987. this._outputAudioNode.gain.value = this._options.volume;
  31988. }
  31989. if (this._options.mainTrack) {
  31990. this._isMainTrack = this._options.mainTrack;
  31991. }
  31992. }
  31993. this._isInitialized = true;
  31994. }
  31995. };
  31996. SoundTrack.prototype.dispose = function () {
  31997. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31998. if (this._connectedAnalyser) {
  31999. this._connectedAnalyser.stopDebugCanvas();
  32000. }
  32001. while (this.soundCollection.length) {
  32002. this.soundCollection[0].dispose();
  32003. }
  32004. if (this._outputAudioNode) {
  32005. this._outputAudioNode.disconnect();
  32006. }
  32007. this._outputAudioNode = null;
  32008. }
  32009. };
  32010. SoundTrack.prototype.AddSound = function (sound) {
  32011. if (!this._isInitialized) {
  32012. this._initializeSoundTrackAudioGraph();
  32013. }
  32014. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32015. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  32016. }
  32017. if (sound.soundTrackId) {
  32018. if (sound.soundTrackId === -1) {
  32019. this._scene.mainSoundTrack.RemoveSound(sound);
  32020. }
  32021. else {
  32022. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  32023. }
  32024. }
  32025. this.soundCollection.push(sound);
  32026. sound.soundTrackId = this.id;
  32027. };
  32028. SoundTrack.prototype.RemoveSound = function (sound) {
  32029. var index = this.soundCollection.indexOf(sound);
  32030. if (index !== -1) {
  32031. this.soundCollection.splice(index, 1);
  32032. }
  32033. };
  32034. SoundTrack.prototype.setVolume = function (newVolume) {
  32035. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32036. this._outputAudioNode.gain.value = newVolume;
  32037. }
  32038. };
  32039. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  32040. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32041. for (var i = 0; i < this.soundCollection.length; i++) {
  32042. this.soundCollection[i].switchPanningModelToHRTF();
  32043. }
  32044. }
  32045. };
  32046. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  32047. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32048. for (var i = 0; i < this.soundCollection.length; i++) {
  32049. this.soundCollection[i].switchPanningModelToEqualPower();
  32050. }
  32051. }
  32052. };
  32053. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  32054. if (this._connectedAnalyser) {
  32055. this._connectedAnalyser.stopDebugCanvas();
  32056. }
  32057. this._connectedAnalyser = analyser;
  32058. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32059. this._outputAudioNode.disconnect();
  32060. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  32061. }
  32062. };
  32063. return SoundTrack;
  32064. })();
  32065. BABYLON.SoundTrack = SoundTrack;
  32066. })(BABYLON || (BABYLON = {}));
  32067. var BABYLON;
  32068. (function (BABYLON) {
  32069. var SIMDVector3 = (function () {
  32070. function SIMDVector3() {
  32071. }
  32072. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  32073. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  32074. var m0 = SIMD.float32x4.load(transformation.m, 0);
  32075. var m1 = SIMD.float32x4.load(transformation.m, 4);
  32076. var m2 = SIMD.float32x4.load(transformation.m, 8);
  32077. var m3 = SIMD.float32x4.load(transformation.m, 12);
  32078. 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));
  32079. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  32080. SIMD.float32x4.storeXYZ(result._data, 0, r);
  32081. };
  32082. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  32083. var v0 = SIMD.float32x4.splat(x);
  32084. var v1 = SIMD.float32x4.splat(y);
  32085. var v2 = SIMD.float32x4.splat(z);
  32086. var m0 = SIMD.float32x4.load(transformation.m, 0);
  32087. var m1 = SIMD.float32x4.load(transformation.m, 4);
  32088. var m2 = SIMD.float32x4.load(transformation.m, 8);
  32089. var m3 = SIMD.float32x4.load(transformation.m, 12);
  32090. 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));
  32091. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  32092. SIMD.float32x4.storeXYZ(result._data, 0, r);
  32093. };
  32094. return SIMDVector3;
  32095. })();
  32096. BABYLON.SIMDVector3 = SIMDVector3;
  32097. var SIMDMatrix = (function () {
  32098. function SIMDMatrix() {
  32099. }
  32100. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  32101. if (offset === void 0) { offset = 0; }
  32102. var tm = this.m;
  32103. var om = other.m;
  32104. var om0 = SIMD.float32x4.load(om, 0);
  32105. var om1 = SIMD.float32x4.load(om, 4);
  32106. var om2 = SIMD.float32x4.load(om, 8);
  32107. var om3 = SIMD.float32x4.load(om, 12);
  32108. var tm0 = SIMD.float32x4.load(tm, 0);
  32109. 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)))));
  32110. var tm1 = SIMD.float32x4.load(tm, 4);
  32111. 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)))));
  32112. var tm2 = SIMD.float32x4.load(tm, 8);
  32113. 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)))));
  32114. var tm3 = SIMD.float32x4.load(tm, 12);
  32115. 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)))));
  32116. };
  32117. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  32118. var src = this.m;
  32119. var dest = other.m;
  32120. var row0, row1, row2, row3;
  32121. var tmp1;
  32122. var minor0, minor1, minor2, minor3;
  32123. var det;
  32124. // Load the 4 rows
  32125. var src0 = SIMD.float32x4.load(src, 0);
  32126. var src1 = SIMD.float32x4.load(src, 4);
  32127. var src2 = SIMD.float32x4.load(src, 8);
  32128. var src3 = SIMD.float32x4.load(src, 12);
  32129. // Transpose the source matrix. Sort of. Not a true transpose operation
  32130. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  32131. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  32132. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  32133. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  32134. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  32135. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  32136. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  32137. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  32138. // This is a true transposition, but it will lead to an incorrect result
  32139. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  32140. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  32141. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  32142. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  32143. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  32144. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  32145. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  32146. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  32147. // ----
  32148. tmp1 = SIMD.float32x4.mul(row2, row3);
  32149. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32150. minor0 = SIMD.float32x4.mul(row1, tmp1);
  32151. minor1 = SIMD.float32x4.mul(row0, tmp1);
  32152. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32153. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  32154. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  32155. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  32156. // ----
  32157. tmp1 = SIMD.float32x4.mul(row1, row2);
  32158. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32159. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  32160. minor3 = SIMD.float32x4.mul(row0, tmp1);
  32161. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32162. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  32163. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  32164. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  32165. // ----
  32166. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  32167. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32168. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  32169. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  32170. minor2 = SIMD.float32x4.mul(row0, tmp1);
  32171. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32172. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  32173. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  32174. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  32175. // ----
  32176. tmp1 = SIMD.float32x4.mul(row0, row1);
  32177. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32178. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  32179. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  32180. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32181. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  32182. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  32183. // ----
  32184. tmp1 = SIMD.float32x4.mul(row0, row3);
  32185. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32186. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  32187. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  32188. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32189. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  32190. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  32191. // ----
  32192. tmp1 = SIMD.float32x4.mul(row0, row2);
  32193. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32194. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  32195. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  32196. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32197. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  32198. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  32199. // Compute determinant
  32200. det = SIMD.float32x4.mul(row0, minor0);
  32201. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  32202. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  32203. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  32204. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  32205. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  32206. // These shuffles aren't necessary if the faulty transposition is done
  32207. // up at the top of this function.
  32208. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  32209. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  32210. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  32211. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  32212. // Compute final values by multiplying with 1/det
  32213. minor0 = SIMD.float32x4.mul(det, minor0);
  32214. minor1 = SIMD.float32x4.mul(det, minor1);
  32215. minor2 = SIMD.float32x4.mul(det, minor2);
  32216. minor3 = SIMD.float32x4.mul(det, minor3);
  32217. SIMD.float32x4.store(dest, 0, minor0);
  32218. SIMD.float32x4.store(dest, 4, minor1);
  32219. SIMD.float32x4.store(dest, 8, minor2);
  32220. SIMD.float32x4.store(dest, 12, minor3);
  32221. return this;
  32222. };
  32223. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  32224. var out = result.m;
  32225. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  32226. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  32227. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  32228. // cc.kmVec3Subtract(f, pCenter, pEye);
  32229. var f = SIMD.float32x4.sub(center, eye);
  32230. // cc.kmVec3Normalize(f, f);
  32231. var tmp = SIMD.float32x4.mul(f, f);
  32232. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32233. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32234. // cc.kmVec3Assign(up, pUp);
  32235. // cc.kmVec3Normalize(up, up);
  32236. tmp = SIMD.float32x4.mul(up, up);
  32237. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32238. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32239. // cc.kmVec3Cross(s, f, up);
  32240. 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)));
  32241. // cc.kmVec3Normalize(s, s);
  32242. tmp = SIMD.float32x4.mul(s, s);
  32243. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32244. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32245. // cc.kmVec3Cross(u, s, f);
  32246. 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)));
  32247. // cc.kmVec3Normalize(s, s);
  32248. tmp = SIMD.float32x4.mul(s, s);
  32249. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32250. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32251. var zero = SIMD.float32x4.splat(0.0);
  32252. s = SIMD.float32x4.neg(s);
  32253. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  32254. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  32255. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  32256. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  32257. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  32258. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  32259. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  32260. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  32261. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  32262. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  32263. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  32264. var b3 = SIMD.float32x4.neg(eye);
  32265. b3 = SIMD.float32x4.withW(b3, 1.0);
  32266. 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)))));
  32267. 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)))));
  32268. 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)))));
  32269. 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)))));
  32270. };
  32271. return SIMDMatrix;
  32272. })();
  32273. BABYLON.SIMDMatrix = SIMDMatrix;
  32274. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  32275. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  32276. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  32277. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  32278. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  32279. var SIMDHelper = (function () {
  32280. function SIMDHelper() {
  32281. }
  32282. Object.defineProperty(SIMDHelper, "IsEnabled", {
  32283. get: function () {
  32284. return SIMDHelper._isEnabled;
  32285. },
  32286. enumerable: true,
  32287. configurable: true
  32288. });
  32289. SIMDHelper.DisableSIMD = function () {
  32290. // Replace functions
  32291. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  32292. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  32293. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  32294. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  32295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  32296. SIMDHelper._isEnabled = false;
  32297. };
  32298. SIMDHelper.EnableSIMD = function () {
  32299. if (window.SIMD === undefined) {
  32300. return;
  32301. }
  32302. // Replace functions
  32303. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  32304. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  32305. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  32306. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  32307. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  32308. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  32309. get: function () { return this._data[0]; },
  32310. set: function (value) {
  32311. if (!this._data) {
  32312. this._data = new Float32Array(3);
  32313. }
  32314. this._data[0] = value;
  32315. }
  32316. });
  32317. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  32318. get: function () { return this._data[1]; },
  32319. set: function (value) {
  32320. this._data[1] = value;
  32321. }
  32322. });
  32323. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  32324. get: function () { return this._data[2]; },
  32325. set: function (value) {
  32326. this._data[2] = value;
  32327. }
  32328. });
  32329. SIMDHelper._isEnabled = true;
  32330. };
  32331. SIMDHelper._isEnabled = false;
  32332. return SIMDHelper;
  32333. })();
  32334. BABYLON.SIMDHelper = SIMDHelper;
  32335. })(BABYLON || (BABYLON = {}));
  32336. var BABYLON;
  32337. (function (BABYLON) {
  32338. var ShaderMaterial = (function (_super) {
  32339. __extends(ShaderMaterial, _super);
  32340. function ShaderMaterial(name, scene, shaderPath, options) {
  32341. _super.call(this, name, scene);
  32342. this._textures = {};
  32343. this._floats = {};
  32344. this._floatsArrays = {};
  32345. this._colors3 = {};
  32346. this._colors4 = {};
  32347. this._vectors2 = {};
  32348. this._vectors3 = {};
  32349. this._vectors4 = {};
  32350. this._matrices = {};
  32351. this._matrices3x3 = {};
  32352. this._matrices2x2 = {};
  32353. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  32354. this._shaderPath = shaderPath;
  32355. options.needAlphaBlending = options.needAlphaBlending || false;
  32356. options.needAlphaTesting = options.needAlphaTesting || false;
  32357. options.attributes = options.attributes || ["position", "normal", "uv"];
  32358. options.uniforms = options.uniforms || ["worldViewProjection"];
  32359. options.samplers = options.samplers || [];
  32360. options.defines = options.defines || [];
  32361. this._options = options;
  32362. }
  32363. ShaderMaterial.prototype.needAlphaBlending = function () {
  32364. return this._options.needAlphaBlending;
  32365. };
  32366. ShaderMaterial.prototype.needAlphaTesting = function () {
  32367. return this._options.needAlphaTesting;
  32368. };
  32369. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  32370. if (this._options.uniforms.indexOf(uniformName) === -1) {
  32371. this._options.uniforms.push(uniformName);
  32372. }
  32373. };
  32374. ShaderMaterial.prototype.setTexture = function (name, texture) {
  32375. if (this._options.samplers.indexOf(name) === -1) {
  32376. this._options.samplers.push(name);
  32377. }
  32378. this._textures[name] = texture;
  32379. return this;
  32380. };
  32381. ShaderMaterial.prototype.setFloat = function (name, value) {
  32382. this._checkUniform(name);
  32383. this._floats[name] = value;
  32384. return this;
  32385. };
  32386. ShaderMaterial.prototype.setFloats = function (name, value) {
  32387. this._checkUniform(name);
  32388. this._floatsArrays[name] = value;
  32389. return this;
  32390. };
  32391. ShaderMaterial.prototype.setColor3 = function (name, value) {
  32392. this._checkUniform(name);
  32393. this._colors3[name] = value;
  32394. return this;
  32395. };
  32396. ShaderMaterial.prototype.setColor4 = function (name, value) {
  32397. this._checkUniform(name);
  32398. this._colors4[name] = value;
  32399. return this;
  32400. };
  32401. ShaderMaterial.prototype.setVector2 = function (name, value) {
  32402. this._checkUniform(name);
  32403. this._vectors2[name] = value;
  32404. return this;
  32405. };
  32406. ShaderMaterial.prototype.setVector3 = function (name, value) {
  32407. this._checkUniform(name);
  32408. this._vectors3[name] = value;
  32409. return this;
  32410. };
  32411. ShaderMaterial.prototype.setVector4 = function (name, value) {
  32412. this._checkUniform(name);
  32413. this._vectors4[name] = value;
  32414. return this;
  32415. };
  32416. ShaderMaterial.prototype.setMatrix = function (name, value) {
  32417. this._checkUniform(name);
  32418. this._matrices[name] = value;
  32419. return this;
  32420. };
  32421. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  32422. this._checkUniform(name);
  32423. this._matrices3x3[name] = value;
  32424. return this;
  32425. };
  32426. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  32427. this._checkUniform(name);
  32428. this._matrices2x2[name] = value;
  32429. return this;
  32430. };
  32431. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  32432. var scene = this.getScene();
  32433. var engine = scene.getEngine();
  32434. if (!this.checkReadyOnEveryCall) {
  32435. if (this._renderId === scene.getRenderId()) {
  32436. return true;
  32437. }
  32438. }
  32439. // Instances
  32440. var defines = [];
  32441. var fallbacks = new BABYLON.EffectFallbacks();
  32442. if (useInstances) {
  32443. defines.push("#define INSTANCES");
  32444. }
  32445. for (var index = 0; index < this._options.defines.length; index++) {
  32446. defines.push(this._options.defines[index]);
  32447. }
  32448. // Bones
  32449. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  32450. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32451. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32452. fallbacks.addCPUSkinningFallback(0, mesh);
  32453. }
  32454. // Alpha test
  32455. if (engine.getAlphaTesting()) {
  32456. defines.push("#define ALPHATEST");
  32457. }
  32458. var previousEffect = this._effect;
  32459. var join = defines.join("\n");
  32460. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  32461. if (!this._effect.isReady()) {
  32462. return false;
  32463. }
  32464. if (previousEffect !== this._effect) {
  32465. scene.resetCachedMaterial();
  32466. }
  32467. this._renderId = scene.getRenderId();
  32468. return true;
  32469. };
  32470. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32471. var scene = this.getScene();
  32472. if (this._options.uniforms.indexOf("world") !== -1) {
  32473. this._effect.setMatrix("world", world);
  32474. }
  32475. if (this._options.uniforms.indexOf("worldView") !== -1) {
  32476. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  32477. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  32478. }
  32479. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  32480. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  32481. }
  32482. };
  32483. ShaderMaterial.prototype.bind = function (world, mesh) {
  32484. // Std values
  32485. this.bindOnlyWorldMatrix(world);
  32486. if (this.getScene().getCachedMaterial() !== this) {
  32487. if (this._options.uniforms.indexOf("view") !== -1) {
  32488. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  32489. }
  32490. if (this._options.uniforms.indexOf("projection") !== -1) {
  32491. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  32492. }
  32493. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  32494. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32495. }
  32496. // Bones
  32497. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  32498. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32499. }
  32500. // Texture
  32501. for (var name in this._textures) {
  32502. this._effect.setTexture(name, this._textures[name]);
  32503. }
  32504. // Float
  32505. for (name in this._floats) {
  32506. this._effect.setFloat(name, this._floats[name]);
  32507. }
  32508. // Float s
  32509. for (name in this._floatsArrays) {
  32510. this._effect.setArray(name, this._floatsArrays[name]);
  32511. }
  32512. // Color3
  32513. for (name in this._colors3) {
  32514. this._effect.setColor3(name, this._colors3[name]);
  32515. }
  32516. // Color4
  32517. for (name in this._colors4) {
  32518. var color = this._colors4[name];
  32519. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  32520. }
  32521. // Vector2
  32522. for (name in this._vectors2) {
  32523. this._effect.setVector2(name, this._vectors2[name]);
  32524. }
  32525. // Vector3
  32526. for (name in this._vectors3) {
  32527. this._effect.setVector3(name, this._vectors3[name]);
  32528. }
  32529. // Vector4
  32530. for (name in this._vectors4) {
  32531. this._effect.setVector4(name, this._vectors4[name]);
  32532. }
  32533. // Matrix
  32534. for (name in this._matrices) {
  32535. this._effect.setMatrix(name, this._matrices[name]);
  32536. }
  32537. // Matrix 3x3
  32538. for (name in this._matrices3x3) {
  32539. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  32540. }
  32541. // Matrix 2x2
  32542. for (name in this._matrices2x2) {
  32543. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  32544. }
  32545. }
  32546. _super.prototype.bind.call(this, world, mesh);
  32547. };
  32548. ShaderMaterial.prototype.clone = function (name) {
  32549. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  32550. return newShaderMaterial;
  32551. };
  32552. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  32553. for (var name in this._textures) {
  32554. this._textures[name].dispose();
  32555. }
  32556. this._textures = {};
  32557. _super.prototype.dispose.call(this, forceDisposeEffect);
  32558. };
  32559. ShaderMaterial.prototype.serialize = function () {
  32560. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32561. serializationObject.customType = "BABYLON.ShaderMaterial";
  32562. serializationObject.options = this._options;
  32563. serializationObject.shaderPath = this._shaderPath;
  32564. // Texture
  32565. serializationObject.textures = {};
  32566. for (var name in this._textures) {
  32567. serializationObject.textures[name] = this._textures[name].serialize();
  32568. }
  32569. // Float
  32570. serializationObject.floats = {};
  32571. for (name in this._floats) {
  32572. serializationObject.floats[name] = this._floats[name];
  32573. }
  32574. // Float s
  32575. serializationObject.floatArrays = {};
  32576. for (name in this._floatsArrays) {
  32577. serializationObject.floatArrays[name] = this._floatsArrays[name];
  32578. }
  32579. // Color3
  32580. serializationObject.colors3 = {};
  32581. for (name in this._colors3) {
  32582. serializationObject.colors3[name] = this._colors3[name].asArray();
  32583. }
  32584. // Color4
  32585. serializationObject.colors4 = {};
  32586. for (name in this._colors4) {
  32587. serializationObject.colors4[name] = this._colors4[name].asArray();
  32588. }
  32589. // Vector2
  32590. serializationObject.vectors2 = {};
  32591. for (name in this._vectors2) {
  32592. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  32593. }
  32594. // Vector3
  32595. serializationObject.vectors3 = {};
  32596. for (name in this._vectors3) {
  32597. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  32598. }
  32599. // Vector4
  32600. serializationObject.vectors4 = {};
  32601. for (name in this._vectors4) {
  32602. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  32603. }
  32604. // Matrix
  32605. serializationObject.matrices = {};
  32606. for (name in this._matrices) {
  32607. serializationObject.matrices[name] = this._matrices[name].asArray();
  32608. }
  32609. // Matrix 3x3
  32610. serializationObject.matrices3x3 = {};
  32611. for (name in this._matrices3x3) {
  32612. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  32613. }
  32614. // Matrix 2x2
  32615. serializationObject.matrices2x2 = {};
  32616. for (name in this._matrices2x2) {
  32617. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  32618. }
  32619. return serializationObject;
  32620. };
  32621. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  32622. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  32623. // Texture
  32624. for (var name in source.textures) {
  32625. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  32626. }
  32627. // Float
  32628. for (name in source.floats) {
  32629. material.setFloat(name, source.floats[name]);
  32630. }
  32631. // Float s
  32632. for (name in source.floatsArrays) {
  32633. material.setFloats(name, source.floatsArrays[name]);
  32634. }
  32635. // Color3
  32636. for (name in source.colors3) {
  32637. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  32638. }
  32639. // Color4
  32640. for (name in source.colors4) {
  32641. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  32642. }
  32643. // Vector2
  32644. for (name in source.vectors2) {
  32645. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  32646. }
  32647. // Vector3
  32648. for (name in source.vectors3) {
  32649. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  32650. }
  32651. // Vector4
  32652. for (name in source.vectors4) {
  32653. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  32654. }
  32655. // Matrix
  32656. for (name in source.matrices) {
  32657. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  32658. }
  32659. // Matrix 3x3
  32660. for (name in source.matrices3x3) {
  32661. material.setMatrix3x3(name, source.matrices3x3[name]);
  32662. }
  32663. // Matrix 2x2
  32664. for (name in source.matrices2x2) {
  32665. material.setMatrix2x2(name, source.matrices2x2[name]);
  32666. }
  32667. return material;
  32668. };
  32669. return ShaderMaterial;
  32670. })(BABYLON.Material);
  32671. BABYLON.ShaderMaterial = ShaderMaterial;
  32672. })(BABYLON || (BABYLON = {}));
  32673. var BABYLON;
  32674. (function (BABYLON) {
  32675. var Internals;
  32676. (function (Internals) {
  32677. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32678. // All values and structures referenced from:
  32679. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32680. var DDS_MAGIC = 0x20534444;
  32681. 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;
  32682. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32683. 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;
  32684. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32685. function FourCCToInt32(value) {
  32686. return value.charCodeAt(0) +
  32687. (value.charCodeAt(1) << 8) +
  32688. (value.charCodeAt(2) << 16) +
  32689. (value.charCodeAt(3) << 24);
  32690. }
  32691. function Int32ToFourCC(value) {
  32692. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32693. }
  32694. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32695. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32696. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32697. var headerLengthInt = 31; // The header length in 32 bit ints
  32698. // Offsets into the header array
  32699. var off_magic = 0;
  32700. var off_size = 1;
  32701. var off_flags = 2;
  32702. var off_height = 3;
  32703. var off_width = 4;
  32704. var off_mipmapCount = 7;
  32705. var off_pfFlags = 20;
  32706. var off_pfFourCC = 21;
  32707. var off_RGBbpp = 22;
  32708. var off_RMask = 23;
  32709. var off_GMask = 24;
  32710. var off_BMask = 25;
  32711. var off_AMask = 26;
  32712. var off_caps1 = 27;
  32713. var off_caps2 = 28;
  32714. ;
  32715. var DDSTools = (function () {
  32716. function DDSTools() {
  32717. }
  32718. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32719. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32720. var mipmapCount = 1;
  32721. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32722. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32723. }
  32724. return {
  32725. width: header[off_width],
  32726. height: header[off_height],
  32727. mipmapCount: mipmapCount,
  32728. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32729. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32730. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32731. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  32732. };
  32733. };
  32734. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32735. var byteArray = new Uint8Array(dataLength);
  32736. var srcData = new Uint8Array(arrayBuffer);
  32737. var index = 0;
  32738. for (var y = height - 1; y >= 0; y--) {
  32739. for (var x = 0; x < width; x++) {
  32740. var srcPos = dataOffset + (x + y * width) * 4;
  32741. byteArray[index + 2] = srcData[srcPos];
  32742. byteArray[index + 1] = srcData[srcPos + 1];
  32743. byteArray[index] = srcData[srcPos + 2];
  32744. byteArray[index + 3] = srcData[srcPos + 3];
  32745. index += 4;
  32746. }
  32747. }
  32748. return byteArray;
  32749. };
  32750. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32751. var byteArray = new Uint8Array(dataLength);
  32752. var srcData = new Uint8Array(arrayBuffer);
  32753. var index = 0;
  32754. for (var y = height - 1; y >= 0; y--) {
  32755. for (var x = 0; x < width; x++) {
  32756. var srcPos = dataOffset + (x + y * width) * 3;
  32757. byteArray[index + 2] = srcData[srcPos];
  32758. byteArray[index + 1] = srcData[srcPos + 1];
  32759. byteArray[index] = srcData[srcPos + 2];
  32760. index += 3;
  32761. }
  32762. }
  32763. return byteArray;
  32764. };
  32765. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32766. var byteArray = new Uint8Array(dataLength);
  32767. var srcData = new Uint8Array(arrayBuffer);
  32768. var index = 0;
  32769. for (var y = height - 1; y >= 0; y--) {
  32770. for (var x = 0; x < width; x++) {
  32771. var srcPos = dataOffset + (x + y * width);
  32772. byteArray[index] = srcData[srcPos];
  32773. index++;
  32774. }
  32775. }
  32776. return byteArray;
  32777. };
  32778. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  32779. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  32780. if (header[off_magic] != DDS_MAGIC) {
  32781. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32782. return;
  32783. }
  32784. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32785. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32786. return;
  32787. }
  32788. if (info.isFourCC) {
  32789. fourCC = header[off_pfFourCC];
  32790. switch (fourCC) {
  32791. case FOURCC_DXT1:
  32792. blockBytes = 8;
  32793. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32794. break;
  32795. case FOURCC_DXT3:
  32796. blockBytes = 16;
  32797. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32798. break;
  32799. case FOURCC_DXT5:
  32800. blockBytes = 16;
  32801. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32802. break;
  32803. default:
  32804. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  32805. return;
  32806. }
  32807. }
  32808. mipmapCount = 1;
  32809. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  32810. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32811. }
  32812. var bpp = header[off_RGBbpp];
  32813. for (var face = 0; face < faces; face++) {
  32814. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32815. width = header[off_width];
  32816. height = header[off_height];
  32817. dataOffset = header[off_size] + 4;
  32818. for (i = 0; i < mipmapCount; ++i) {
  32819. if (info.isRGB) {
  32820. if (bpp === 24) {
  32821. dataLength = width * height * 3;
  32822. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32823. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  32824. }
  32825. else {
  32826. dataLength = width * height * 4;
  32827. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32828. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  32829. }
  32830. }
  32831. else if (info.isLuminance) {
  32832. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  32833. var unpaddedRowSize = width;
  32834. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  32835. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  32836. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32837. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  32838. }
  32839. else {
  32840. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  32841. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  32842. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  32843. }
  32844. dataOffset += dataLength;
  32845. width *= 0.5;
  32846. height *= 0.5;
  32847. width = Math.max(1.0, width);
  32848. height = Math.max(1.0, height);
  32849. }
  32850. }
  32851. };
  32852. return DDSTools;
  32853. })();
  32854. Internals.DDSTools = DDSTools;
  32855. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32856. })(BABYLON || (BABYLON = {}));
  32857. var BABYLON;
  32858. (function (BABYLON) {
  32859. var CannonJSPlugin = (function () {
  32860. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  32861. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  32862. if (iterations === void 0) { iterations = 10; }
  32863. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  32864. this.name = "CannonJSPlugin";
  32865. this._physicsMaterials = [];
  32866. this._fixedTimeStep = 1 / 60;
  32867. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  32868. this._currentCollisionGroup = 2;
  32869. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  32870. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  32871. this._tmpPosition = BABYLON.Vector3.Zero();
  32872. this._tmpQuaternion = new BABYLON.Quaternion();
  32873. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  32874. this._tmpDeltaRotation = new BABYLON.Quaternion();
  32875. this._tmpUnityRotation = new BABYLON.Quaternion();
  32876. if (!this.isSupported()) {
  32877. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  32878. return;
  32879. }
  32880. this.world = new CANNON.World();
  32881. this.world.broadphase = new CANNON.NaiveBroadphase();
  32882. this.world.solver.iterations = iterations;
  32883. }
  32884. CannonJSPlugin.prototype.setGravity = function (gravity) {
  32885. this.world.gravity.copy(gravity);
  32886. };
  32887. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  32888. this._fixedTimeStep = timeStep;
  32889. };
  32890. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  32891. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  32892. };
  32893. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  32894. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  32895. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  32896. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  32897. };
  32898. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  32899. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  32900. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  32901. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  32902. };
  32903. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  32904. //parent-child relationship. Does this impostor has a parent impostor?
  32905. if (impostor.parent) {
  32906. if (impostor.physicsBody) {
  32907. this.removePhysicsBody(impostor);
  32908. //TODO is that needed?
  32909. impostor.forceUpdate();
  32910. }
  32911. return;
  32912. }
  32913. //should a new body be created for this impostor?
  32914. if (impostor.isBodyInitRequired()) {
  32915. if (!impostor.mesh.rotationQuaternion) {
  32916. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  32917. }
  32918. var shape = this._createShape(impostor);
  32919. //unregister events, if body is being changed
  32920. var oldBody = impostor.physicsBody;
  32921. if (oldBody) {
  32922. this.removePhysicsBody(impostor);
  32923. }
  32924. //create the body and material
  32925. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  32926. var bodyCreationObject = {
  32927. mass: impostor.getParam("mass"),
  32928. material: material
  32929. };
  32930. // A simple extend, in case native options were used.
  32931. var nativeOptions = impostor.getParam("nativeOptions");
  32932. for (var key in nativeOptions) {
  32933. if (nativeOptions.hasOwnProperty(key)) {
  32934. bodyCreationObject[key] = nativeOptions[key];
  32935. }
  32936. }
  32937. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  32938. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  32939. this.world.addEventListener("preStep", impostor.beforeStep);
  32940. this.world.addEventListener("postStep", impostor.afterStep);
  32941. impostor.physicsBody.addShape(shape);
  32942. this.world.add(impostor.physicsBody);
  32943. //try to keep the body moving in the right direction by taking old properties.
  32944. //Should be tested!
  32945. if (oldBody) {
  32946. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  32947. impostor.physicsBody[param].copy(oldBody[param]);
  32948. });
  32949. }
  32950. this._processChildMeshes(impostor);
  32951. }
  32952. //now update the body's transformation
  32953. this._updatePhysicsBodyTransformation(impostor);
  32954. };
  32955. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  32956. var _this = this;
  32957. var meshChildren = mainImpostor.mesh.getChildMeshes();
  32958. if (meshChildren.length) {
  32959. var processMesh = function (localPosition, mesh) {
  32960. var childImpostor = mesh.getPhysicsImpostor();
  32961. if (childImpostor) {
  32962. var parent = childImpostor.parent;
  32963. if (parent !== mainImpostor) {
  32964. var localPosition = mesh.position;
  32965. if (childImpostor.physicsBody) {
  32966. _this.removePhysicsBody(childImpostor);
  32967. childImpostor.physicsBody = null;
  32968. }
  32969. childImpostor.parent = mainImpostor;
  32970. childImpostor.resetUpdateFlags();
  32971. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  32972. //Add the mass of the children.
  32973. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  32974. }
  32975. }
  32976. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  32977. };
  32978. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  32979. }
  32980. };
  32981. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  32982. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  32983. this.world.removeEventListener("preStep", impostor.beforeStep);
  32984. this.world.removeEventListener("postStep", impostor.afterStep);
  32985. this.world.remove(impostor.physicsBody);
  32986. };
  32987. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  32988. var mainBody = impostorJoint.mainImpostor.physicsBody;
  32989. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  32990. if (!mainBody || !connectedBody) {
  32991. return;
  32992. }
  32993. var constraint;
  32994. var jointData = impostorJoint.joint.jointData;
  32995. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  32996. var constraintData = {
  32997. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  32998. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  32999. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  33000. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  33001. maxForce: jointData.nativeParams.maxForce,
  33002. collideConnected: !!jointData.collision
  33003. };
  33004. //Not needed, Cannon has a collideConnected flag
  33005. /*if (!jointData.collision) {
  33006. //add 1st body to a collision group of its own, if it is not in 1
  33007. if (mainBody.collisionFilterGroup === 1) {
  33008. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  33009. this._currentCollisionGroup <<= 1;
  33010. }
  33011. if (connectedBody.collisionFilterGroup === 1) {
  33012. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  33013. this._currentCollisionGroup <<= 1;
  33014. }
  33015. //add their mask to the collisionFilterMask of each other:
  33016. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  33017. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  33018. }*/
  33019. switch (impostorJoint.joint.type) {
  33020. case BABYLON.PhysicsJoint.HingeJoint:
  33021. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  33022. break;
  33023. case BABYLON.PhysicsJoint.DistanceJoint:
  33024. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  33025. break;
  33026. case BABYLON.PhysicsJoint.SpringJoint:
  33027. var springData = jointData;
  33028. constraint = new CANNON.Spring(mainBody, connectedBody, {
  33029. restLength: springData.length,
  33030. stiffness: springData.stiffness,
  33031. damping: springData.damping,
  33032. localAnchorA: constraintData.pivotA,
  33033. localAnchorB: constraintData.pivotB
  33034. });
  33035. break;
  33036. default:
  33037. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  33038. break;
  33039. }
  33040. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  33041. constraint.collideConnected = !!jointData.collision;
  33042. impostorJoint.joint.physicsJoint = constraint;
  33043. //don't add spring as constraint, as it is not one.
  33044. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  33045. this.world.addConstraint(constraint);
  33046. }
  33047. else {
  33048. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  33049. constraint.applyForce();
  33050. });
  33051. }
  33052. };
  33053. CannonJSPlugin.prototype.removeJoint = function (joint) {
  33054. //TODO
  33055. };
  33056. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  33057. var index;
  33058. var mat;
  33059. for (index = 0; index < this._physicsMaterials.length; index++) {
  33060. mat = this._physicsMaterials[index];
  33061. if (mat.friction === friction && mat.restitution === restitution) {
  33062. return mat;
  33063. }
  33064. }
  33065. var currentMat = new CANNON.Material("mat");
  33066. currentMat.friction = friction;
  33067. currentMat.restitution = restitution;
  33068. this._physicsMaterials.push(currentMat);
  33069. return currentMat;
  33070. };
  33071. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  33072. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  33073. };
  33074. CannonJSPlugin.prototype._createShape = function (impostor) {
  33075. var mesh = impostor.mesh;
  33076. //get the correct bounding box
  33077. var oldQuaternion = mesh.rotationQuaternion;
  33078. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  33079. mesh.computeWorldMatrix(true);
  33080. var returnValue;
  33081. switch (impostor.type) {
  33082. case BABYLON.PhysicsEngine.SphereImpostor:
  33083. var bbox = mesh.getBoundingInfo().boundingBox;
  33084. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  33085. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  33086. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  33087. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  33088. break;
  33089. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  33090. case BABYLON.PhysicsEngine.CylinderImpostor:
  33091. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  33092. case BABYLON.PhysicsEngine.BoxImpostor:
  33093. bbox = mesh.getBoundingInfo().boundingBox;
  33094. var min = bbox.minimumWorld;
  33095. var max = bbox.maximumWorld;
  33096. var box = max.subtract(min).scale(0.5);
  33097. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  33098. break;
  33099. case BABYLON.PhysicsEngine.PlaneImpostor:
  33100. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  33101. returnValue = new CANNON.Plane();
  33102. break;
  33103. case BABYLON.PhysicsEngine.MeshImpostor:
  33104. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33105. var rawFaces = mesh.getIndices();
  33106. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  33107. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  33108. break;
  33109. case BABYLON.PhysicsEngine.HeightmapImpostor:
  33110. returnValue = this._createHeightmap(mesh);
  33111. break;
  33112. }
  33113. mesh.rotationQuaternion = oldQuaternion;
  33114. return returnValue;
  33115. };
  33116. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  33117. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33118. var matrix = [];
  33119. //For now pointDepth will not be used and will be automatically calculated.
  33120. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  33121. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  33122. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  33123. var elementSize = dim * 2 / arraySize;
  33124. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  33125. for (var i = 0; i < pos.length; i = i + 3) {
  33126. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  33127. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  33128. var y = pos[i + 1] + minY;
  33129. if (!matrix[x]) {
  33130. matrix[x] = [];
  33131. }
  33132. if (!matrix[x][z]) {
  33133. matrix[x][z] = y;
  33134. }
  33135. matrix[x][z] = Math.max(y, matrix[x][z]);
  33136. }
  33137. for (var x = 0; x <= arraySize; ++x) {
  33138. if (!matrix[x]) {
  33139. var loc = 1;
  33140. while (!matrix[(x + loc) % arraySize]) {
  33141. loc++;
  33142. }
  33143. matrix[x] = matrix[(x + loc) % arraySize].slice();
  33144. }
  33145. for (var z = 0; z <= arraySize; ++z) {
  33146. if (!matrix[x][z]) {
  33147. var loc = 1;
  33148. var newValue;
  33149. while (newValue === undefined) {
  33150. newValue = matrix[x][(z + loc++) % arraySize];
  33151. }
  33152. matrix[x][z] = newValue;
  33153. }
  33154. }
  33155. }
  33156. var shape = new CANNON.Heightfield(matrix, {
  33157. elementSize: elementSize
  33158. });
  33159. //For future reference, needed for body transformation
  33160. shape.minY = minY;
  33161. return shape;
  33162. };
  33163. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  33164. var mesh = impostor.mesh;
  33165. //make sure it is updated...
  33166. impostor.mesh.computeWorldMatrix(true);
  33167. // The delta between the mesh position and the mesh bounding box center
  33168. var bbox = mesh.getBoundingInfo().boundingBox;
  33169. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  33170. var quaternion = mesh.rotationQuaternion;
  33171. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  33172. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  33173. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  33174. //-90 DEG in X, precalculated
  33175. quaternion = quaternion.multiply(this._minus90X);
  33176. //Invert! (Precalculated, 90 deg in X)
  33177. //No need to clone. this will never change.
  33178. impostor.setDeltaRotation(this._plus90X);
  33179. }
  33180. //If it is a heightfield, if should be centered.
  33181. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  33182. //calculate the correct body position:
  33183. var rotationQuaternion = mesh.rotationQuaternion;
  33184. mesh.rotationQuaternion = this._tmpUnityRotation;
  33185. mesh.computeWorldMatrix(true);
  33186. //get original center with no rotation
  33187. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  33188. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  33189. //rotation is back
  33190. mesh.rotationQuaternion = rotationQuaternion;
  33191. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  33192. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  33193. mesh.setPivotMatrix(p);
  33194. mesh.computeWorldMatrix(true);
  33195. //calculate the translation
  33196. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  33197. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  33198. //add it inverted to the delta
  33199. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  33200. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  33201. mesh.setPivotMatrix(oldPivot);
  33202. mesh.computeWorldMatrix(true);
  33203. }
  33204. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  33205. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  33206. this._tmpPosition.copyFrom(mesh.position);
  33207. }
  33208. impostor.setDeltaPosition(this._tmpDeltaPosition);
  33209. //Now update the impostor object
  33210. impostor.physicsBody.position.copy(this._tmpPosition);
  33211. impostor.physicsBody.quaternion.copy(quaternion);
  33212. };
  33213. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  33214. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  33215. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  33216. };
  33217. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  33218. impostor.physicsBody.position.copy(newPosition);
  33219. impostor.physicsBody.quaternion.copy(newRotation);
  33220. };
  33221. CannonJSPlugin.prototype.isSupported = function () {
  33222. return window.CANNON !== undefined;
  33223. };
  33224. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  33225. impostor.physicsBody.velocity.copy(velocity);
  33226. };
  33227. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  33228. impostor.physicsBody.angularVelocity.copy(velocity);
  33229. };
  33230. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  33231. impostor.physicsBody.mass = mass;
  33232. impostor.physicsBody.updateMassProperties();
  33233. };
  33234. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  33235. impostor.physicsBody.sleep();
  33236. };
  33237. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  33238. impostor.physicsBody.wakeUp();
  33239. };
  33240. CannonJSPlugin.prototype.dispose = function () {
  33241. //nothing to do, actually.
  33242. };
  33243. return CannonJSPlugin;
  33244. })();
  33245. BABYLON.CannonJSPlugin = CannonJSPlugin;
  33246. })(BABYLON || (BABYLON = {}));
  33247. var BABYLON;
  33248. (function (BABYLON) {
  33249. var OimoJSPlugin = (function () {
  33250. function OimoJSPlugin(iterations) {
  33251. this.name = "OimoJSPlugin";
  33252. this._tmpImpostorsArray = [];
  33253. this._tmpPositionVector = BABYLON.Vector3.Zero();
  33254. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  33255. this.world.clear();
  33256. //making sure no stats are calculated
  33257. this.world.isNoStat = true;
  33258. }
  33259. OimoJSPlugin.prototype.setGravity = function (gravity) {
  33260. this.world.gravity.copy(gravity);
  33261. };
  33262. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  33263. this.world.timeStep = timeStep;
  33264. };
  33265. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  33266. var _this = this;
  33267. impostors.forEach(function (impostor) {
  33268. impostor.beforeStep();
  33269. });
  33270. this.world.step();
  33271. impostors.forEach(function (impostor) {
  33272. impostor.afterStep();
  33273. //update the ordered impostors array
  33274. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  33275. });
  33276. //check for collisions
  33277. var contact = this.world.contacts;
  33278. while (contact !== null) {
  33279. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  33280. contact = contact.next;
  33281. continue;
  33282. }
  33283. //is this body colliding with any other? get the impostor
  33284. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  33285. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  33286. if (!mainImpostor || !collidingImpostor) {
  33287. contact = contact.next;
  33288. continue;
  33289. }
  33290. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  33291. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  33292. contact = contact.next;
  33293. }
  33294. };
  33295. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  33296. var mass = impostor.physicsBody.massInfo.mass;
  33297. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  33298. };
  33299. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  33300. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  33301. this.applyImpulse(impostor, force, contactPoint);
  33302. };
  33303. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  33304. var _this = this;
  33305. //parent-child relationship. Does this impostor has a parent impostor?
  33306. if (impostor.parent) {
  33307. if (impostor.physicsBody) {
  33308. this.removePhysicsBody(impostor);
  33309. //TODO is that needed?
  33310. impostor.forceUpdate();
  33311. }
  33312. return;
  33313. }
  33314. impostor.mesh.computeWorldMatrix(true);
  33315. if (impostor.isBodyInitRequired()) {
  33316. if (!impostor.mesh.rotationQuaternion) {
  33317. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  33318. }
  33319. var bodyConfig = {
  33320. name: impostor.mesh.uniqueId,
  33321. //Oimo must have mass, also for static objects.
  33322. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  33323. size: [],
  33324. type: [],
  33325. pos: [],
  33326. rot: [],
  33327. move: impostor.getParam("mass") !== 0,
  33328. //Supporting older versions of Oimo
  33329. world: this.world
  33330. };
  33331. var impostors = [impostor];
  33332. function addToArray(parent) {
  33333. parent.getChildMeshes().forEach(function (m) {
  33334. if (m.physicsImpostor) {
  33335. impostors.push(m.physicsImpostor);
  33336. m.physicsImpostor._init();
  33337. }
  33338. });
  33339. }
  33340. addToArray(impostor.mesh);
  33341. function checkWithEpsilon(value) {
  33342. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  33343. }
  33344. impostors.forEach(function (i) {
  33345. //get the correct bounding box
  33346. var oldQuaternion = i.mesh.rotationQuaternion;
  33347. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  33348. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  33349. i.mesh.computeWorldMatrix(true);
  33350. var bbox = i.mesh.getBoundingInfo().boundingBox;
  33351. if (i === impostor) {
  33352. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  33353. //Can also use Array.prototype.push.apply
  33354. bodyConfig.pos.push(bbox.center.x);
  33355. bodyConfig.pos.push(bbox.center.y);
  33356. bodyConfig.pos.push(bbox.center.z);
  33357. //tmp solution
  33358. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  33359. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  33360. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  33361. }
  33362. else {
  33363. bodyConfig.pos.push(i.mesh.position.x);
  33364. bodyConfig.pos.push(i.mesh.position.y);
  33365. bodyConfig.pos.push(i.mesh.position.z);
  33366. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  33367. bodyConfig.rot.push(0);
  33368. bodyConfig.rot.push(0);
  33369. bodyConfig.rot.push(0);
  33370. }
  33371. // register mesh
  33372. switch (i.type) {
  33373. case BABYLON.PhysicsEngine.SphereImpostor:
  33374. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  33375. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  33376. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  33377. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  33378. bodyConfig.type.push('sphere');
  33379. //due to the way oimo works with compounds, add 3 times
  33380. bodyConfig.size.push(size);
  33381. bodyConfig.size.push(size);
  33382. bodyConfig.size.push(size);
  33383. break;
  33384. case BABYLON.PhysicsEngine.PlaneImpostor:
  33385. //TODO Oimo now supports cylinder!
  33386. case BABYLON.PhysicsEngine.CylinderImpostor:
  33387. case BABYLON.PhysicsEngine.BoxImpostor:
  33388. default:
  33389. var min = bbox.minimumWorld;
  33390. var max = bbox.maximumWorld;
  33391. var box = max.subtract(min);
  33392. var sizeX = checkWithEpsilon(box.x);
  33393. var sizeY = checkWithEpsilon(box.y);
  33394. var sizeZ = checkWithEpsilon(box.z);
  33395. bodyConfig.type.push('box');
  33396. bodyConfig.size.push(sizeX);
  33397. bodyConfig.size.push(sizeY);
  33398. bodyConfig.size.push(sizeZ);
  33399. break;
  33400. }
  33401. //actually not needed, but hey...
  33402. i.mesh.rotationQuaternion = oldQuaternion;
  33403. });
  33404. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  33405. }
  33406. else {
  33407. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  33408. }
  33409. impostor.setDeltaPosition(this._tmpPositionVector);
  33410. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  33411. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  33412. };
  33413. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  33414. //impostor.physicsBody.dispose();
  33415. //Same as : (older oimo versions)
  33416. this.world.removeRigidBody(impostor.physicsBody);
  33417. };
  33418. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  33419. var mainBody = impostorJoint.mainImpostor.physicsBody;
  33420. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  33421. if (!mainBody || !connectedBody) {
  33422. return;
  33423. }
  33424. var jointData = impostorJoint.joint.jointData;
  33425. var options = jointData.nativeParams || {};
  33426. var type;
  33427. var nativeJointData = {
  33428. body1: mainBody,
  33429. body2: connectedBody,
  33430. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  33431. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  33432. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  33433. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  33434. min: options.min,
  33435. max: options.max,
  33436. collision: options.collision || jointData.collision,
  33437. spring: options.spring,
  33438. //supporting older version of Oimo
  33439. world: this.world
  33440. };
  33441. switch (impostorJoint.joint.type) {
  33442. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  33443. type = "jointBall";
  33444. break;
  33445. case BABYLON.PhysicsJoint.SpringJoint:
  33446. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  33447. var springData = jointData;
  33448. nativeJointData.min = springData.length || nativeJointData.min;
  33449. //Max should also be set, just make sure it is at least min
  33450. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  33451. case BABYLON.PhysicsJoint.DistanceJoint:
  33452. type = "jointDistance";
  33453. nativeJointData.max = jointData.maxDistance;
  33454. break;
  33455. case BABYLON.PhysicsJoint.PrismaticJoint:
  33456. type = "jointPrisme";
  33457. break;
  33458. case BABYLON.PhysicsJoint.SliderJoint:
  33459. type = "jointSlide";
  33460. break;
  33461. case BABYLON.PhysicsJoint.WheelJoint:
  33462. type = "jointWheel";
  33463. break;
  33464. case BABYLON.PhysicsJoint.HingeJoint:
  33465. default:
  33466. type = "jointHinge";
  33467. break;
  33468. }
  33469. nativeJointData.type = type;
  33470. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  33471. };
  33472. OimoJSPlugin.prototype.removeJoint = function (joint) {
  33473. joint.joint.physicsJoint.dispose();
  33474. };
  33475. OimoJSPlugin.prototype.isSupported = function () {
  33476. return OIMO !== undefined;
  33477. };
  33478. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  33479. if (!impostor.physicsBody.sleeping) {
  33480. //TODO check that
  33481. if (impostor.physicsBody.shapes.next) {
  33482. var parentShape = this._getLastShape(impostor.physicsBody);
  33483. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  33484. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  33485. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  33486. }
  33487. else {
  33488. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  33489. }
  33490. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  33491. }
  33492. };
  33493. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  33494. var body = impostor.physicsBody;
  33495. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  33496. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  33497. body.syncShapes();
  33498. body.awake();
  33499. };
  33500. OimoJSPlugin.prototype._getLastShape = function (body) {
  33501. var lastShape = body.shapes;
  33502. while (lastShape.next) {
  33503. lastShape = lastShape.next;
  33504. }
  33505. return lastShape;
  33506. };
  33507. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  33508. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  33509. };
  33510. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  33511. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  33512. };
  33513. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  33514. var staticBody = mass === 0;
  33515. //this will actually set the body's density and not its mass.
  33516. //But this is how oimo treats the mass variable.
  33517. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  33518. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  33519. };
  33520. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  33521. impostor.physicsBody.sleep();
  33522. };
  33523. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  33524. impostor.physicsBody.awake();
  33525. };
  33526. OimoJSPlugin.prototype.dispose = function () {
  33527. this.world.clear();
  33528. };
  33529. return OimoJSPlugin;
  33530. })();
  33531. BABYLON.OimoJSPlugin = OimoJSPlugin;
  33532. })(BABYLON || (BABYLON = {}));
  33533. var BABYLON;
  33534. (function (BABYLON) {
  33535. var DisplayPassPostProcess = (function (_super) {
  33536. __extends(DisplayPassPostProcess, _super);
  33537. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33538. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  33539. }
  33540. return DisplayPassPostProcess;
  33541. })(BABYLON.PostProcess);
  33542. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  33543. })(BABYLON || (BABYLON = {}));
  33544. var BABYLON;
  33545. (function (BABYLON) {
  33546. var SimplificationSettings = (function () {
  33547. function SimplificationSettings(quality, distance, optimizeMesh) {
  33548. this.quality = quality;
  33549. this.distance = distance;
  33550. this.optimizeMesh = optimizeMesh;
  33551. }
  33552. return SimplificationSettings;
  33553. })();
  33554. BABYLON.SimplificationSettings = SimplificationSettings;
  33555. var SimplificationQueue = (function () {
  33556. function SimplificationQueue() {
  33557. this.running = false;
  33558. this._simplificationArray = [];
  33559. }
  33560. SimplificationQueue.prototype.addTask = function (task) {
  33561. this._simplificationArray.push(task);
  33562. };
  33563. SimplificationQueue.prototype.executeNext = function () {
  33564. var task = this._simplificationArray.pop();
  33565. if (task) {
  33566. this.running = true;
  33567. this.runSimplification(task);
  33568. }
  33569. else {
  33570. this.running = false;
  33571. }
  33572. };
  33573. SimplificationQueue.prototype.runSimplification = function (task) {
  33574. var _this = this;
  33575. if (task.parallelProcessing) {
  33576. //parallel simplifier
  33577. task.settings.forEach(function (setting) {
  33578. var simplifier = _this.getSimplifier(task);
  33579. simplifier.simplify(setting, function (newMesh) {
  33580. task.mesh.addLODLevel(setting.distance, newMesh);
  33581. newMesh.isVisible = true;
  33582. //check if it is the last
  33583. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  33584. //all done, run the success callback.
  33585. task.successCallback();
  33586. }
  33587. _this.executeNext();
  33588. });
  33589. });
  33590. }
  33591. else {
  33592. //single simplifier.
  33593. var simplifier = this.getSimplifier(task);
  33594. var runDecimation = function (setting, callback) {
  33595. simplifier.simplify(setting, function (newMesh) {
  33596. task.mesh.addLODLevel(setting.distance, newMesh);
  33597. newMesh.isVisible = true;
  33598. //run the next quality level
  33599. callback();
  33600. });
  33601. };
  33602. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  33603. runDecimation(task.settings[loop.index], function () {
  33604. loop.executeNext();
  33605. });
  33606. }, function () {
  33607. //execution ended, run the success callback.
  33608. if (task.successCallback) {
  33609. task.successCallback();
  33610. }
  33611. _this.executeNext();
  33612. });
  33613. }
  33614. };
  33615. SimplificationQueue.prototype.getSimplifier = function (task) {
  33616. switch (task.simplificationType) {
  33617. case SimplificationType.QUADRATIC:
  33618. default:
  33619. return new QuadraticErrorSimplification(task.mesh);
  33620. }
  33621. };
  33622. return SimplificationQueue;
  33623. })();
  33624. BABYLON.SimplificationQueue = SimplificationQueue;
  33625. /**
  33626. * The implemented types of simplification.
  33627. * At the moment only Quadratic Error Decimation is implemented.
  33628. */
  33629. (function (SimplificationType) {
  33630. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  33631. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  33632. var SimplificationType = BABYLON.SimplificationType;
  33633. var DecimationTriangle = (function () {
  33634. function DecimationTriangle(vertices) {
  33635. this.vertices = vertices;
  33636. this.error = new Array(4);
  33637. this.deleted = false;
  33638. this.isDirty = false;
  33639. this.deletePending = false;
  33640. this.borderFactor = 0;
  33641. }
  33642. return DecimationTriangle;
  33643. })();
  33644. BABYLON.DecimationTriangle = DecimationTriangle;
  33645. var DecimationVertex = (function () {
  33646. function DecimationVertex(position, id) {
  33647. this.position = position;
  33648. this.id = id;
  33649. this.isBorder = true;
  33650. this.q = new QuadraticMatrix();
  33651. this.triangleCount = 0;
  33652. this.triangleStart = 0;
  33653. this.originalOffsets = [];
  33654. }
  33655. DecimationVertex.prototype.updatePosition = function (newPosition) {
  33656. this.position.copyFrom(newPosition);
  33657. };
  33658. return DecimationVertex;
  33659. })();
  33660. BABYLON.DecimationVertex = DecimationVertex;
  33661. var QuadraticMatrix = (function () {
  33662. function QuadraticMatrix(data) {
  33663. this.data = new Array(10);
  33664. for (var i = 0; i < 10; ++i) {
  33665. if (data && data[i]) {
  33666. this.data[i] = data[i];
  33667. }
  33668. else {
  33669. this.data[i] = 0;
  33670. }
  33671. }
  33672. }
  33673. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  33674. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  33675. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  33676. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  33677. return det;
  33678. };
  33679. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  33680. for (var i = 0; i < 10; ++i) {
  33681. this.data[i] += matrix.data[i];
  33682. }
  33683. };
  33684. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  33685. for (var i = 0; i < 10; ++i) {
  33686. this.data[i] += data[i];
  33687. }
  33688. };
  33689. QuadraticMatrix.prototype.add = function (matrix) {
  33690. var m = new QuadraticMatrix();
  33691. for (var i = 0; i < 10; ++i) {
  33692. m.data[i] = this.data[i] + matrix.data[i];
  33693. }
  33694. return m;
  33695. };
  33696. QuadraticMatrix.FromData = function (a, b, c, d) {
  33697. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  33698. };
  33699. //returning an array to avoid garbage collection
  33700. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  33701. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  33702. };
  33703. return QuadraticMatrix;
  33704. })();
  33705. BABYLON.QuadraticMatrix = QuadraticMatrix;
  33706. var Reference = (function () {
  33707. function Reference(vertexId, triangleId) {
  33708. this.vertexId = vertexId;
  33709. this.triangleId = triangleId;
  33710. }
  33711. return Reference;
  33712. })();
  33713. BABYLON.Reference = Reference;
  33714. /**
  33715. * An implementation of the Quadratic Error simplification algorithm.
  33716. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  33717. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  33718. * @author RaananW
  33719. */
  33720. var QuadraticErrorSimplification = (function () {
  33721. function QuadraticErrorSimplification(_mesh) {
  33722. this._mesh = _mesh;
  33723. this.initialized = false;
  33724. this.syncIterations = 5000;
  33725. this.aggressiveness = 7;
  33726. this.decimationIterations = 100;
  33727. this.boundingBoxEpsilon = BABYLON.Epsilon;
  33728. }
  33729. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  33730. var _this = this;
  33731. this.initDecimatedMesh();
  33732. //iterating through the submeshes array, one after the other.
  33733. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  33734. _this.initWithMesh(loop.index, function () {
  33735. _this.runDecimation(settings, loop.index, function () {
  33736. loop.executeNext();
  33737. });
  33738. }, settings.optimizeMesh);
  33739. }, function () {
  33740. setTimeout(function () {
  33741. successCallback(_this._reconstructedMesh);
  33742. }, 0);
  33743. });
  33744. };
  33745. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  33746. var _this = this;
  33747. var gCount = 0;
  33748. triangle.vertices.forEach(function (vertex) {
  33749. var count = 0;
  33750. var vPos = vertex.position;
  33751. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  33752. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  33753. ++count;
  33754. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  33755. ++count;
  33756. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  33757. ++count;
  33758. if (count > 1) {
  33759. ++gCount;
  33760. }
  33761. ;
  33762. });
  33763. if (gCount > 1) {
  33764. console.log(triangle, gCount);
  33765. }
  33766. return gCount > 1;
  33767. };
  33768. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  33769. var _this = this;
  33770. var targetCount = ~~(this.triangles.length * settings.quality);
  33771. var deletedTriangles = 0;
  33772. var triangleCount = this.triangles.length;
  33773. var iterationFunction = function (iteration, callback) {
  33774. setTimeout(function () {
  33775. if (iteration % 5 === 0) {
  33776. _this.updateMesh(iteration === 0);
  33777. }
  33778. for (var i = 0; i < _this.triangles.length; ++i) {
  33779. _this.triangles[i].isDirty = false;
  33780. }
  33781. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  33782. var trianglesIterator = function (i) {
  33783. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  33784. var t = _this.triangles[tIdx];
  33785. if (!t)
  33786. return;
  33787. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  33788. return;
  33789. }
  33790. for (var j = 0; j < 3; ++j) {
  33791. if (t.error[j] < threshold) {
  33792. var deleted0 = [];
  33793. var deleted1 = [];
  33794. var v0 = t.vertices[j];
  33795. var v1 = t.vertices[(j + 1) % 3];
  33796. if (v0.isBorder !== v1.isBorder)
  33797. continue;
  33798. var p = BABYLON.Vector3.Zero();
  33799. var n = BABYLON.Vector3.Zero();
  33800. var uv = BABYLON.Vector2.Zero();
  33801. var color = new BABYLON.Color4(0, 0, 0, 1);
  33802. _this.calculateError(v0, v1, p, n, uv, color);
  33803. var delTr = [];
  33804. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  33805. continue;
  33806. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  33807. continue;
  33808. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  33809. continue;
  33810. var uniqueArray = [];
  33811. delTr.forEach(function (deletedT) {
  33812. if (uniqueArray.indexOf(deletedT) === -1) {
  33813. deletedT.deletePending = true;
  33814. uniqueArray.push(deletedT);
  33815. }
  33816. });
  33817. if (uniqueArray.length % 2 !== 0) {
  33818. continue;
  33819. }
  33820. v0.q = v1.q.add(v0.q);
  33821. v0.updatePosition(p);
  33822. var tStart = _this.references.length;
  33823. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  33824. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  33825. var tCount = _this.references.length - tStart;
  33826. if (tCount <= v0.triangleCount) {
  33827. if (tCount) {
  33828. for (var c = 0; c < tCount; c++) {
  33829. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  33830. }
  33831. }
  33832. }
  33833. else {
  33834. v0.triangleStart = tStart;
  33835. }
  33836. v0.triangleCount = tCount;
  33837. break;
  33838. }
  33839. }
  33840. };
  33841. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  33842. }, 0);
  33843. };
  33844. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  33845. if (triangleCount - deletedTriangles <= targetCount)
  33846. loop.breakLoop();
  33847. else {
  33848. iterationFunction(loop.index, function () {
  33849. loop.executeNext();
  33850. });
  33851. }
  33852. }, function () {
  33853. setTimeout(function () {
  33854. //reconstruct this part of the mesh
  33855. _this.reconstructMesh(submeshIndex);
  33856. successCallback();
  33857. }, 0);
  33858. });
  33859. };
  33860. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  33861. var _this = this;
  33862. this.vertices = [];
  33863. this.triangles = [];
  33864. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33865. var indices = this._mesh.getIndices();
  33866. var submesh = this._mesh.subMeshes[submeshIndex];
  33867. var findInVertices = function (positionToSearch) {
  33868. if (optimizeMesh) {
  33869. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  33870. if (_this.vertices[ii].position.equals(positionToSearch)) {
  33871. return _this.vertices[ii];
  33872. }
  33873. }
  33874. }
  33875. return null;
  33876. };
  33877. var vertexReferences = [];
  33878. var vertexInit = function (i) {
  33879. var offset = i + submesh.verticesStart;
  33880. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  33881. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  33882. vertex.originalOffsets.push(offset);
  33883. if (vertex.id === _this.vertices.length) {
  33884. _this.vertices.push(vertex);
  33885. }
  33886. vertexReferences.push(vertex.id);
  33887. };
  33888. //var totalVertices = mesh.getTotalVertices();
  33889. var totalVertices = submesh.verticesCount;
  33890. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  33891. var indicesInit = function (i) {
  33892. var offset = (submesh.indexStart / 3) + i;
  33893. var pos = (offset * 3);
  33894. var i0 = indices[pos + 0];
  33895. var i1 = indices[pos + 1];
  33896. var i2 = indices[pos + 2];
  33897. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  33898. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  33899. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  33900. var triangle = new DecimationTriangle([v0, v1, v2]);
  33901. triangle.originalOffset = pos;
  33902. _this.triangles.push(triangle);
  33903. };
  33904. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  33905. _this.init(callback);
  33906. });
  33907. });
  33908. };
  33909. QuadraticErrorSimplification.prototype.init = function (callback) {
  33910. var _this = this;
  33911. var triangleInit1 = function (i) {
  33912. var t = _this.triangles[i];
  33913. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  33914. for (var j = 0; j < 3; j++) {
  33915. 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))));
  33916. }
  33917. };
  33918. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  33919. var triangleInit2 = function (i) {
  33920. var t = _this.triangles[i];
  33921. for (var j = 0; j < 3; ++j) {
  33922. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  33923. }
  33924. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  33925. };
  33926. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  33927. _this.initialized = true;
  33928. callback();
  33929. });
  33930. });
  33931. };
  33932. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  33933. var newTriangles = [];
  33934. var i;
  33935. for (i = 0; i < this.vertices.length; ++i) {
  33936. this.vertices[i].triangleCount = 0;
  33937. }
  33938. var t;
  33939. var j;
  33940. for (i = 0; i < this.triangles.length; ++i) {
  33941. if (!this.triangles[i].deleted) {
  33942. t = this.triangles[i];
  33943. for (j = 0; j < 3; ++j) {
  33944. t.vertices[j].triangleCount = 1;
  33945. }
  33946. newTriangles.push(t);
  33947. }
  33948. }
  33949. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  33950. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  33951. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  33952. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  33953. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33954. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33955. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  33956. var vertexCount = 0;
  33957. for (i = 0; i < this.vertices.length; ++i) {
  33958. var vertex = this.vertices[i];
  33959. vertex.id = vertexCount;
  33960. if (vertex.triangleCount) {
  33961. vertex.originalOffsets.forEach(function (originalOffset) {
  33962. newPositionData.push(vertex.position.x);
  33963. newPositionData.push(vertex.position.y);
  33964. newPositionData.push(vertex.position.z);
  33965. newNormalData.push(normalData[originalOffset * 3]);
  33966. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  33967. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  33968. if (uvs && uvs.length) {
  33969. newUVsData.push(uvs[(originalOffset * 2)]);
  33970. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  33971. }
  33972. else if (colorsData && colorsData.length) {
  33973. newColorsData.push(colorsData[(originalOffset * 4)]);
  33974. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  33975. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  33976. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  33977. }
  33978. ++vertexCount;
  33979. });
  33980. }
  33981. }
  33982. var startingIndex = this._reconstructedMesh.getTotalIndices();
  33983. var startingVertex = this._reconstructedMesh.getTotalVertices();
  33984. var submeshesArray = this._reconstructedMesh.subMeshes;
  33985. this._reconstructedMesh.subMeshes = [];
  33986. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  33987. var originalIndices = this._mesh.getIndices();
  33988. for (i = 0; i < newTriangles.length; ++i) {
  33989. t = newTriangles[i]; //now get the new referencing point for each vertex
  33990. [0, 1, 2].forEach(function (idx) {
  33991. var id = originalIndices[t.originalOffset + idx];
  33992. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  33993. if (offset < 0)
  33994. offset = 0;
  33995. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  33996. });
  33997. }
  33998. //overwriting the old vertex buffers and indices.
  33999. this._reconstructedMesh.setIndices(newIndicesArray);
  34000. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  34001. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  34002. if (newUVsData.length > 0)
  34003. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  34004. if (newColorsData.length > 0)
  34005. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  34006. //create submesh
  34007. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  34008. if (submeshIndex > 0) {
  34009. this._reconstructedMesh.subMeshes = [];
  34010. submeshesArray.forEach(function (submesh) {
  34011. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  34012. });
  34013. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  34014. }
  34015. };
  34016. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  34017. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  34018. this._reconstructedMesh.material = this._mesh.material;
  34019. this._reconstructedMesh.parent = this._mesh.parent;
  34020. this._reconstructedMesh.isVisible = false;
  34021. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  34022. };
  34023. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  34024. for (var i = 0; i < vertex1.triangleCount; ++i) {
  34025. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  34026. if (t.deleted)
  34027. continue;
  34028. var s = this.references[vertex1.triangleStart + i].vertexId;
  34029. var v1 = t.vertices[(s + 1) % 3];
  34030. var v2 = t.vertices[(s + 2) % 3];
  34031. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  34032. deletedArray[i] = true;
  34033. delTr.push(t);
  34034. continue;
  34035. }
  34036. var d1 = v1.position.subtract(point);
  34037. d1 = d1.normalize();
  34038. var d2 = v2.position.subtract(point);
  34039. d2 = d2.normalize();
  34040. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  34041. return true;
  34042. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  34043. deletedArray[i] = false;
  34044. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  34045. return true;
  34046. }
  34047. return false;
  34048. };
  34049. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  34050. var newDeleted = deletedTriangles;
  34051. for (var i = 0; i < vertex.triangleCount; ++i) {
  34052. var ref = this.references[vertex.triangleStart + i];
  34053. var t = this.triangles[ref.triangleId];
  34054. if (t.deleted)
  34055. continue;
  34056. if (deletedArray[i] && t.deletePending) {
  34057. t.deleted = true;
  34058. newDeleted++;
  34059. continue;
  34060. }
  34061. t.vertices[ref.vertexId] = origVertex;
  34062. t.isDirty = true;
  34063. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  34064. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  34065. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  34066. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  34067. this.references.push(ref);
  34068. }
  34069. return newDeleted;
  34070. };
  34071. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  34072. for (var i = 0; i < this.vertices.length; ++i) {
  34073. var vCount = [];
  34074. var vId = [];
  34075. var v = this.vertices[i];
  34076. var j;
  34077. for (j = 0; j < v.triangleCount; ++j) {
  34078. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  34079. for (var ii = 0; ii < 3; ii++) {
  34080. var ofs = 0;
  34081. var vv = triangle.vertices[ii];
  34082. while (ofs < vCount.length) {
  34083. if (vId[ofs] === vv.id)
  34084. break;
  34085. ++ofs;
  34086. }
  34087. if (ofs === vCount.length) {
  34088. vCount.push(1);
  34089. vId.push(vv.id);
  34090. }
  34091. else {
  34092. vCount[ofs]++;
  34093. }
  34094. }
  34095. }
  34096. for (j = 0; j < vCount.length; ++j) {
  34097. if (vCount[j] === 1) {
  34098. this.vertices[vId[j]].isBorder = true;
  34099. }
  34100. else {
  34101. this.vertices[vId[j]].isBorder = false;
  34102. }
  34103. }
  34104. }
  34105. };
  34106. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  34107. if (identifyBorders === void 0) { identifyBorders = false; }
  34108. var i;
  34109. if (!identifyBorders) {
  34110. var newTrianglesVector = [];
  34111. for (i = 0; i < this.triangles.length; ++i) {
  34112. if (!this.triangles[i].deleted) {
  34113. newTrianglesVector.push(this.triangles[i]);
  34114. }
  34115. }
  34116. this.triangles = newTrianglesVector;
  34117. }
  34118. for (i = 0; i < this.vertices.length; ++i) {
  34119. this.vertices[i].triangleCount = 0;
  34120. this.vertices[i].triangleStart = 0;
  34121. }
  34122. var t;
  34123. var j;
  34124. var v;
  34125. for (i = 0; i < this.triangles.length; ++i) {
  34126. t = this.triangles[i];
  34127. for (j = 0; j < 3; ++j) {
  34128. v = t.vertices[j];
  34129. v.triangleCount++;
  34130. }
  34131. }
  34132. var tStart = 0;
  34133. for (i = 0; i < this.vertices.length; ++i) {
  34134. this.vertices[i].triangleStart = tStart;
  34135. tStart += this.vertices[i].triangleCount;
  34136. this.vertices[i].triangleCount = 0;
  34137. }
  34138. var newReferences = new Array(this.triangles.length * 3);
  34139. for (i = 0; i < this.triangles.length; ++i) {
  34140. t = this.triangles[i];
  34141. for (j = 0; j < 3; ++j) {
  34142. v = t.vertices[j];
  34143. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  34144. v.triangleCount++;
  34145. }
  34146. }
  34147. this.references = newReferences;
  34148. if (identifyBorders) {
  34149. this.identifyBorder();
  34150. }
  34151. };
  34152. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  34153. var x = point.x;
  34154. var y = point.y;
  34155. var z = point.z;
  34156. 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
  34157. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  34158. };
  34159. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  34160. var q = vertex1.q.add(vertex2.q);
  34161. var border = vertex1.isBorder && vertex2.isBorder;
  34162. var error = 0;
  34163. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  34164. if (qDet !== 0 && !border) {
  34165. if (!pointResult) {
  34166. pointResult = BABYLON.Vector3.Zero();
  34167. }
  34168. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  34169. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  34170. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  34171. error = this.vertexError(q, pointResult);
  34172. }
  34173. else {
  34174. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  34175. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  34176. var error1 = this.vertexError(q, vertex1.position);
  34177. var error2 = this.vertexError(q, vertex2.position);
  34178. var error3 = this.vertexError(q, p3);
  34179. error = Math.min(error1, error2, error3);
  34180. if (error === error1) {
  34181. if (pointResult) {
  34182. pointResult.copyFrom(vertex1.position);
  34183. }
  34184. }
  34185. else if (error === error2) {
  34186. if (pointResult) {
  34187. pointResult.copyFrom(vertex2.position);
  34188. }
  34189. }
  34190. else {
  34191. if (pointResult) {
  34192. pointResult.copyFrom(p3);
  34193. }
  34194. }
  34195. }
  34196. return error;
  34197. };
  34198. return QuadraticErrorSimplification;
  34199. })();
  34200. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  34201. })(BABYLON || (BABYLON = {}));
  34202. var BABYLON;
  34203. (function (BABYLON) {
  34204. var serializedGeometries = [];
  34205. var serializeGeometry = function (geometry, serializationGeometries) {
  34206. if (serializedGeometries[geometry.id]) {
  34207. return;
  34208. }
  34209. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  34210. serializationGeometries.boxes.push(geometry.serialize());
  34211. }
  34212. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  34213. serializationGeometries.spheres.push(geometry.serialize());
  34214. }
  34215. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  34216. serializationGeometries.cylinders.push(geometry.serialize());
  34217. }
  34218. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  34219. serializationGeometries.toruses.push(geometry.serialize());
  34220. }
  34221. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  34222. serializationGeometries.grounds.push(geometry.serialize());
  34223. }
  34224. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  34225. serializationGeometries.planes.push(geometry.serialize());
  34226. }
  34227. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  34228. serializationGeometries.torusKnots.push(geometry.serialize());
  34229. }
  34230. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  34231. throw new Error("Unknown primitive type");
  34232. }
  34233. else {
  34234. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  34235. }
  34236. serializedGeometries[geometry.id] = true;
  34237. };
  34238. var serializeMesh = function (mesh, serializationScene) {
  34239. var serializationObject = {};
  34240. serializationObject.name = mesh.name;
  34241. serializationObject.id = mesh.id;
  34242. if (BABYLON.Tags.HasTags(mesh)) {
  34243. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  34244. }
  34245. serializationObject.position = mesh.position.asArray();
  34246. if (mesh.rotationQuaternion) {
  34247. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  34248. }
  34249. else if (mesh.rotation) {
  34250. serializationObject.rotation = mesh.rotation.asArray();
  34251. }
  34252. serializationObject.scaling = mesh.scaling.asArray();
  34253. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  34254. serializationObject.isEnabled = mesh.isEnabled();
  34255. serializationObject.isVisible = mesh.isVisible;
  34256. serializationObject.infiniteDistance = mesh.infiniteDistance;
  34257. serializationObject.pickable = mesh.isPickable;
  34258. serializationObject.receiveShadows = mesh.receiveShadows;
  34259. serializationObject.billboardMode = mesh.billboardMode;
  34260. serializationObject.visibility = mesh.visibility;
  34261. serializationObject.checkCollisions = mesh.checkCollisions;
  34262. // Parent
  34263. if (mesh.parent) {
  34264. serializationObject.parentId = mesh.parent.id;
  34265. }
  34266. // Geometry
  34267. var geometry = mesh._geometry;
  34268. if (geometry) {
  34269. var geometryId = geometry.id;
  34270. serializationObject.geometryId = geometryId;
  34271. if (!mesh.getScene().getGeometryByID(geometryId)) {
  34272. // 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
  34273. serializeGeometry(geometry, serializationScene.geometries);
  34274. }
  34275. // SubMeshes
  34276. serializationObject.subMeshes = [];
  34277. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34278. var subMesh = mesh.subMeshes[subIndex];
  34279. serializationObject.subMeshes.push({
  34280. materialIndex: subMesh.materialIndex,
  34281. verticesStart: subMesh.verticesStart,
  34282. verticesCount: subMesh.verticesCount,
  34283. indexStart: subMesh.indexStart,
  34284. indexCount: subMesh.indexCount
  34285. });
  34286. }
  34287. }
  34288. // Material
  34289. if (mesh.material) {
  34290. serializationObject.materialId = mesh.material.id;
  34291. }
  34292. else {
  34293. mesh.material = null;
  34294. }
  34295. // Skeleton
  34296. if (mesh.skeleton) {
  34297. serializationObject.skeletonId = mesh.skeleton.id;
  34298. }
  34299. // Physics
  34300. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  34301. serializationObject.physicsMass = mesh.getPhysicsMass();
  34302. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  34303. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  34304. switch (mesh.getPhysicsImpostor().type) {
  34305. case BABYLON.PhysicsEngine.BoxImpostor:
  34306. serializationObject.physicsImpostor = 1;
  34307. break;
  34308. case BABYLON.PhysicsEngine.SphereImpostor:
  34309. serializationObject.physicsImpostor = 2;
  34310. break;
  34311. }
  34312. }
  34313. // Instances
  34314. serializationObject.instances = [];
  34315. for (var index = 0; index < mesh.instances.length; index++) {
  34316. var instance = mesh.instances[index];
  34317. var serializationInstance = {
  34318. name: instance.name,
  34319. position: instance.position.asArray(),
  34320. scaling: instance.scaling.asArray()
  34321. };
  34322. if (instance.rotationQuaternion) {
  34323. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34324. }
  34325. else if (instance.rotation) {
  34326. serializationInstance.rotation = instance.rotation.asArray();
  34327. }
  34328. serializationObject.instances.push(serializationInstance);
  34329. // Animations
  34330. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34331. serializationInstance.ranges = instance.serializeAnimationRanges();
  34332. }
  34333. // Animations
  34334. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  34335. serializationObject.ranges = mesh.serializeAnimationRanges();
  34336. // Layer mask
  34337. serializationObject.layerMask = mesh.layerMask;
  34338. return serializationObject;
  34339. };
  34340. var finalizeSingleMesh = function (mesh, serializationObject) {
  34341. //only works if the mesh is already loaded
  34342. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  34343. //serialize material
  34344. if (mesh.material) {
  34345. if (mesh.material instanceof BABYLON.StandardMaterial) {
  34346. serializationObject.materials = serializationObject.materials || [];
  34347. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  34348. serializationObject.materials.push(mesh.material.serialize());
  34349. }
  34350. }
  34351. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  34352. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  34353. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  34354. serializationObject.multiMaterials.push(mesh.material.serialize());
  34355. }
  34356. }
  34357. }
  34358. //serialize geometry
  34359. var geometry = mesh._geometry;
  34360. if (geometry) {
  34361. if (!serializationObject.geometries) {
  34362. serializationObject.geometries = {};
  34363. serializationObject.geometries.boxes = [];
  34364. serializationObject.geometries.spheres = [];
  34365. serializationObject.geometries.cylinders = [];
  34366. serializationObject.geometries.toruses = [];
  34367. serializationObject.geometries.grounds = [];
  34368. serializationObject.geometries.planes = [];
  34369. serializationObject.geometries.torusKnots = [];
  34370. serializationObject.geometries.vertexData = [];
  34371. }
  34372. serializeGeometry(geometry, serializationObject.geometries);
  34373. }
  34374. // Skeletons
  34375. if (mesh.skeleton) {
  34376. serializationObject.skeletons = serializationObject.skeletons || [];
  34377. serializationObject.skeletons.push(mesh.skeleton.serialize());
  34378. }
  34379. //serialize the actual mesh
  34380. serializationObject.meshes = serializationObject.meshes || [];
  34381. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  34382. }
  34383. };
  34384. var SceneSerializer = (function () {
  34385. function SceneSerializer() {
  34386. }
  34387. SceneSerializer.ClearCache = function () {
  34388. serializedGeometries = [];
  34389. };
  34390. SceneSerializer.Serialize = function (scene) {
  34391. var serializationObject = {};
  34392. // Scene
  34393. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  34394. serializationObject.autoClear = scene.autoClear;
  34395. serializationObject.clearColor = scene.clearColor.asArray();
  34396. serializationObject.ambientColor = scene.ambientColor.asArray();
  34397. serializationObject.gravity = scene.gravity.asArray();
  34398. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  34399. serializationObject.workerCollisions = scene.workerCollisions;
  34400. // Fog
  34401. if (scene.fogMode && scene.fogMode !== 0) {
  34402. serializationObject.fogMode = scene.fogMode;
  34403. serializationObject.fogColor = scene.fogColor.asArray();
  34404. serializationObject.fogStart = scene.fogStart;
  34405. serializationObject.fogEnd = scene.fogEnd;
  34406. serializationObject.fogDensity = scene.fogDensity;
  34407. }
  34408. //Physics
  34409. if (scene.isPhysicsEnabled()) {
  34410. serializationObject.physicsEnabled = true;
  34411. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  34412. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  34413. }
  34414. // Lights
  34415. serializationObject.lights = [];
  34416. var index;
  34417. var light;
  34418. for (index = 0; index < scene.lights.length; index++) {
  34419. light = scene.lights[index];
  34420. serializationObject.lights.push(light.serialize());
  34421. }
  34422. // Cameras
  34423. serializationObject.cameras = [];
  34424. for (index = 0; index < scene.cameras.length; index++) {
  34425. var camera = scene.cameras[index];
  34426. serializationObject.cameras.push(camera.serialize());
  34427. }
  34428. if (scene.activeCamera) {
  34429. serializationObject.activeCameraID = scene.activeCamera.id;
  34430. }
  34431. // Animations
  34432. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  34433. // Materials
  34434. serializationObject.materials = [];
  34435. serializationObject.multiMaterials = [];
  34436. var material;
  34437. for (index = 0; index < scene.materials.length; index++) {
  34438. material = scene.materials[index];
  34439. serializationObject.materials.push(material.serialize());
  34440. }
  34441. // MultiMaterials
  34442. serializationObject.multiMaterials = [];
  34443. for (index = 0; index < scene.multiMaterials.length; index++) {
  34444. var multiMaterial = scene.multiMaterials[index];
  34445. serializationObject.multiMaterials.push(multiMaterial.serialize());
  34446. }
  34447. // Skeletons
  34448. serializationObject.skeletons = [];
  34449. for (index = 0; index < scene.skeletons.length; index++) {
  34450. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  34451. }
  34452. // Geometries
  34453. serializationObject.geometries = {};
  34454. serializationObject.geometries.boxes = [];
  34455. serializationObject.geometries.spheres = [];
  34456. serializationObject.geometries.cylinders = [];
  34457. serializationObject.geometries.toruses = [];
  34458. serializationObject.geometries.grounds = [];
  34459. serializationObject.geometries.planes = [];
  34460. serializationObject.geometries.torusKnots = [];
  34461. serializationObject.geometries.vertexData = [];
  34462. serializedGeometries = [];
  34463. var geometries = scene.getGeometries();
  34464. for (index = 0; index < geometries.length; index++) {
  34465. var geometry = geometries[index];
  34466. if (geometry.isReady()) {
  34467. serializeGeometry(geometry, serializationObject.geometries);
  34468. }
  34469. }
  34470. // Meshes
  34471. serializationObject.meshes = [];
  34472. for (index = 0; index < scene.meshes.length; index++) {
  34473. var abstractMesh = scene.meshes[index];
  34474. if (abstractMesh instanceof BABYLON.Mesh) {
  34475. var mesh = abstractMesh;
  34476. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  34477. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  34478. }
  34479. }
  34480. }
  34481. // Particles Systems
  34482. serializationObject.particleSystems = [];
  34483. for (index = 0; index < scene.particleSystems.length; index++) {
  34484. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  34485. }
  34486. // Lens flares
  34487. serializationObject.lensFlareSystems = [];
  34488. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  34489. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  34490. }
  34491. // Shadows
  34492. serializationObject.shadowGenerators = [];
  34493. for (index = 0; index < scene.lights.length; index++) {
  34494. light = scene.lights[index];
  34495. if (light.getShadowGenerator()) {
  34496. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  34497. }
  34498. }
  34499. return serializationObject;
  34500. };
  34501. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  34502. if (withParents === void 0) { withParents = false; }
  34503. if (withChildren === void 0) { withChildren = false; }
  34504. var serializationObject = {};
  34505. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  34506. if (withParents || withChildren) {
  34507. //deliberate for loop! not for each, appended should be processed as well.
  34508. for (var i = 0; i < toSerialize.length; ++i) {
  34509. if (withChildren) {
  34510. toSerialize[i].getDescendants().forEach(function (node) {
  34511. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  34512. toSerialize.push(node);
  34513. }
  34514. });
  34515. }
  34516. //make sure the array doesn't contain the object already
  34517. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  34518. toSerialize.push(toSerialize[i].parent);
  34519. }
  34520. }
  34521. }
  34522. toSerialize.forEach(function (mesh) {
  34523. finalizeSingleMesh(mesh, serializationObject);
  34524. });
  34525. return serializationObject;
  34526. };
  34527. return SceneSerializer;
  34528. })();
  34529. BABYLON.SceneSerializer = SceneSerializer;
  34530. })(BABYLON || (BABYLON = {}));
  34531. var BABYLON;
  34532. (function (BABYLON) {
  34533. // Unique ID when we import meshes from Babylon to CSG
  34534. var currentCSGMeshId = 0;
  34535. // # class Vertex
  34536. // Represents a vertex of a polygon. Use your own vertex class instead of this
  34537. // one to provide additional features like texture coordinates and vertex
  34538. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  34539. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  34540. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  34541. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  34542. // is not used anywhere else.
  34543. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  34544. var Vertex = (function () {
  34545. function Vertex(pos, normal, uv) {
  34546. this.pos = pos;
  34547. this.normal = normal;
  34548. this.uv = uv;
  34549. }
  34550. Vertex.prototype.clone = function () {
  34551. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  34552. };
  34553. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  34554. // orientation of a polygon is flipped.
  34555. Vertex.prototype.flip = function () {
  34556. this.normal = this.normal.scale(-1);
  34557. };
  34558. // Create a new vertex between this vertex and `other` by linearly
  34559. // interpolating all properties using a parameter of `t`. Subclasses should
  34560. // override this to interpolate additional properties.
  34561. Vertex.prototype.interpolate = function (other, t) {
  34562. 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));
  34563. };
  34564. return Vertex;
  34565. })();
  34566. // # class Plane
  34567. // Represents a plane in 3D space.
  34568. var Plane = (function () {
  34569. function Plane(normal, w) {
  34570. this.normal = normal;
  34571. this.w = w;
  34572. }
  34573. Plane.FromPoints = function (a, b, c) {
  34574. var v0 = c.subtract(a);
  34575. var v1 = b.subtract(a);
  34576. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  34577. return null;
  34578. }
  34579. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  34580. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  34581. };
  34582. Plane.prototype.clone = function () {
  34583. return new Plane(this.normal.clone(), this.w);
  34584. };
  34585. Plane.prototype.flip = function () {
  34586. this.normal.scaleInPlace(-1);
  34587. this.w = -this.w;
  34588. };
  34589. // Split `polygon` by this plane if needed, then put the polygon or polygon
  34590. // fragments in the appropriate lists. Coplanar polygons go into either
  34591. // `coplanarFront` or `coplanarBack` depending on their orientation with
  34592. // respect to this plane. Polygons in front or in back of this plane go into
  34593. // either `front` or `back`.
  34594. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  34595. var COPLANAR = 0;
  34596. var FRONT = 1;
  34597. var BACK = 2;
  34598. var SPANNING = 3;
  34599. // Classify each point as well as the entire polygon into one of the above
  34600. // four classes.
  34601. var polygonType = 0;
  34602. var types = [];
  34603. var i;
  34604. var t;
  34605. for (i = 0; i < polygon.vertices.length; i++) {
  34606. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  34607. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  34608. polygonType |= type;
  34609. types.push(type);
  34610. }
  34611. // Put the polygon in the correct list, splitting it when necessary.
  34612. switch (polygonType) {
  34613. case COPLANAR:
  34614. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  34615. break;
  34616. case FRONT:
  34617. front.push(polygon);
  34618. break;
  34619. case BACK:
  34620. back.push(polygon);
  34621. break;
  34622. case SPANNING:
  34623. var f = [], b = [];
  34624. for (i = 0; i < polygon.vertices.length; i++) {
  34625. var j = (i + 1) % polygon.vertices.length;
  34626. var ti = types[i], tj = types[j];
  34627. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  34628. if (ti !== BACK)
  34629. f.push(vi);
  34630. if (ti !== FRONT)
  34631. b.push(ti !== BACK ? vi.clone() : vi);
  34632. if ((ti | tj) === SPANNING) {
  34633. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  34634. var v = vi.interpolate(vj, t);
  34635. f.push(v);
  34636. b.push(v.clone());
  34637. }
  34638. }
  34639. var poly;
  34640. if (f.length >= 3) {
  34641. poly = new Polygon(f, polygon.shared);
  34642. if (poly.plane)
  34643. front.push(poly);
  34644. }
  34645. if (b.length >= 3) {
  34646. poly = new Polygon(b, polygon.shared);
  34647. if (poly.plane)
  34648. back.push(poly);
  34649. }
  34650. break;
  34651. }
  34652. };
  34653. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  34654. // point is on the plane.
  34655. Plane.EPSILON = 1e-5;
  34656. return Plane;
  34657. })();
  34658. // # class Polygon
  34659. // Represents a convex polygon. The vertices used to initialize a polygon must
  34660. // be coplanar and form a convex loop.
  34661. //
  34662. // Each convex polygon has a `shared` property, which is shared between all
  34663. // polygons that are clones of each other or were split from the same polygon.
  34664. // This can be used to define per-polygon properties (such as surface color).
  34665. var Polygon = (function () {
  34666. function Polygon(vertices, shared) {
  34667. this.vertices = vertices;
  34668. this.shared = shared;
  34669. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  34670. }
  34671. Polygon.prototype.clone = function () {
  34672. var vertices = this.vertices.map(function (v) { return v.clone(); });
  34673. return new Polygon(vertices, this.shared);
  34674. };
  34675. Polygon.prototype.flip = function () {
  34676. this.vertices.reverse().map(function (v) { v.flip(); });
  34677. this.plane.flip();
  34678. };
  34679. return Polygon;
  34680. })();
  34681. // # class Node
  34682. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  34683. // by picking a polygon to split along. That polygon (and all other coplanar
  34684. // polygons) are added directly to that node and the other polygons are added to
  34685. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  34686. // no distinction between internal and leaf nodes.
  34687. var Node = (function () {
  34688. function Node(polygons) {
  34689. this.plane = null;
  34690. this.front = null;
  34691. this.back = null;
  34692. this.polygons = [];
  34693. if (polygons) {
  34694. this.build(polygons);
  34695. }
  34696. }
  34697. Node.prototype.clone = function () {
  34698. var node = new Node();
  34699. node.plane = this.plane && this.plane.clone();
  34700. node.front = this.front && this.front.clone();
  34701. node.back = this.back && this.back.clone();
  34702. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  34703. return node;
  34704. };
  34705. // Convert solid space to empty space and empty space to solid space.
  34706. Node.prototype.invert = function () {
  34707. for (var i = 0; i < this.polygons.length; i++) {
  34708. this.polygons[i].flip();
  34709. }
  34710. if (this.plane) {
  34711. this.plane.flip();
  34712. }
  34713. if (this.front) {
  34714. this.front.invert();
  34715. }
  34716. if (this.back) {
  34717. this.back.invert();
  34718. }
  34719. var temp = this.front;
  34720. this.front = this.back;
  34721. this.back = temp;
  34722. };
  34723. // Recursively remove all polygons in `polygons` that are inside this BSP
  34724. // tree.
  34725. Node.prototype.clipPolygons = function (polygons) {
  34726. if (!this.plane)
  34727. return polygons.slice();
  34728. var front = [], back = [];
  34729. for (var i = 0; i < polygons.length; i++) {
  34730. this.plane.splitPolygon(polygons[i], front, back, front, back);
  34731. }
  34732. if (this.front) {
  34733. front = this.front.clipPolygons(front);
  34734. }
  34735. if (this.back) {
  34736. back = this.back.clipPolygons(back);
  34737. }
  34738. else {
  34739. back = [];
  34740. }
  34741. return front.concat(back);
  34742. };
  34743. // Remove all polygons in this BSP tree that are inside the other BSP tree
  34744. // `bsp`.
  34745. Node.prototype.clipTo = function (bsp) {
  34746. this.polygons = bsp.clipPolygons(this.polygons);
  34747. if (this.front)
  34748. this.front.clipTo(bsp);
  34749. if (this.back)
  34750. this.back.clipTo(bsp);
  34751. };
  34752. // Return a list of all polygons in this BSP tree.
  34753. Node.prototype.allPolygons = function () {
  34754. var polygons = this.polygons.slice();
  34755. if (this.front)
  34756. polygons = polygons.concat(this.front.allPolygons());
  34757. if (this.back)
  34758. polygons = polygons.concat(this.back.allPolygons());
  34759. return polygons;
  34760. };
  34761. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  34762. // new polygons are filtered down to the bottom of the tree and become new
  34763. // nodes there. Each set of polygons is partitioned using the first polygon
  34764. // (no heuristic is used to pick a good split).
  34765. Node.prototype.build = function (polygons) {
  34766. if (!polygons.length)
  34767. return;
  34768. if (!this.plane)
  34769. this.plane = polygons[0].plane.clone();
  34770. var front = [], back = [];
  34771. for (var i = 0; i < polygons.length; i++) {
  34772. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  34773. }
  34774. if (front.length) {
  34775. if (!this.front)
  34776. this.front = new Node();
  34777. this.front.build(front);
  34778. }
  34779. if (back.length) {
  34780. if (!this.back)
  34781. this.back = new Node();
  34782. this.back.build(back);
  34783. }
  34784. };
  34785. return Node;
  34786. })();
  34787. var CSG = (function () {
  34788. function CSG() {
  34789. this.polygons = new Array();
  34790. }
  34791. // Convert BABYLON.Mesh to BABYLON.CSG
  34792. CSG.FromMesh = function (mesh) {
  34793. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  34794. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  34795. if (mesh instanceof BABYLON.Mesh) {
  34796. mesh.computeWorldMatrix(true);
  34797. matrix = mesh.getWorldMatrix();
  34798. meshPosition = mesh.position.clone();
  34799. meshRotation = mesh.rotation.clone();
  34800. if (mesh.rotationQuaternion) {
  34801. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  34802. }
  34803. meshScaling = mesh.scaling.clone();
  34804. }
  34805. else {
  34806. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  34807. }
  34808. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34809. var subMeshes = mesh.subMeshes;
  34810. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  34811. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  34812. vertices = [];
  34813. for (var j = 0; j < 3; j++) {
  34814. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  34815. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  34816. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  34817. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  34818. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  34819. vertex = new Vertex(position, normal, uv);
  34820. vertices.push(vertex);
  34821. }
  34822. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  34823. // To handle the case of degenerated triangle
  34824. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  34825. if (polygon.plane)
  34826. polygons.push(polygon);
  34827. }
  34828. }
  34829. var csg = CSG.FromPolygons(polygons);
  34830. csg.matrix = matrix;
  34831. csg.position = meshPosition;
  34832. csg.rotation = meshRotation;
  34833. csg.scaling = meshScaling;
  34834. csg.rotationQuaternion = meshRotationQuaternion;
  34835. currentCSGMeshId++;
  34836. return csg;
  34837. };
  34838. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  34839. CSG.FromPolygons = function (polygons) {
  34840. var csg = new CSG();
  34841. csg.polygons = polygons;
  34842. return csg;
  34843. };
  34844. CSG.prototype.clone = function () {
  34845. var csg = new CSG();
  34846. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  34847. csg.copyTransformAttributes(this);
  34848. return csg;
  34849. };
  34850. CSG.prototype.toPolygons = function () {
  34851. return this.polygons;
  34852. };
  34853. CSG.prototype.union = function (csg) {
  34854. var a = new Node(this.clone().polygons);
  34855. var b = new Node(csg.clone().polygons);
  34856. a.clipTo(b);
  34857. b.clipTo(a);
  34858. b.invert();
  34859. b.clipTo(a);
  34860. b.invert();
  34861. a.build(b.allPolygons());
  34862. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  34863. };
  34864. CSG.prototype.unionInPlace = function (csg) {
  34865. var a = new Node(this.polygons);
  34866. var b = new Node(csg.polygons);
  34867. a.clipTo(b);
  34868. b.clipTo(a);
  34869. b.invert();
  34870. b.clipTo(a);
  34871. b.invert();
  34872. a.build(b.allPolygons());
  34873. this.polygons = a.allPolygons();
  34874. };
  34875. CSG.prototype.subtract = function (csg) {
  34876. var a = new Node(this.clone().polygons);
  34877. var b = new Node(csg.clone().polygons);
  34878. a.invert();
  34879. a.clipTo(b);
  34880. b.clipTo(a);
  34881. b.invert();
  34882. b.clipTo(a);
  34883. b.invert();
  34884. a.build(b.allPolygons());
  34885. a.invert();
  34886. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  34887. };
  34888. CSG.prototype.subtractInPlace = function (csg) {
  34889. var a = new Node(this.polygons);
  34890. var b = new Node(csg.polygons);
  34891. a.invert();
  34892. a.clipTo(b);
  34893. b.clipTo(a);
  34894. b.invert();
  34895. b.clipTo(a);
  34896. b.invert();
  34897. a.build(b.allPolygons());
  34898. a.invert();
  34899. this.polygons = a.allPolygons();
  34900. };
  34901. CSG.prototype.intersect = function (csg) {
  34902. var a = new Node(this.clone().polygons);
  34903. var b = new Node(csg.clone().polygons);
  34904. a.invert();
  34905. b.clipTo(a);
  34906. b.invert();
  34907. a.clipTo(b);
  34908. b.clipTo(a);
  34909. a.build(b.allPolygons());
  34910. a.invert();
  34911. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  34912. };
  34913. CSG.prototype.intersectInPlace = function (csg) {
  34914. var a = new Node(this.polygons);
  34915. var b = new Node(csg.polygons);
  34916. a.invert();
  34917. b.clipTo(a);
  34918. b.invert();
  34919. a.clipTo(b);
  34920. b.clipTo(a);
  34921. a.build(b.allPolygons());
  34922. a.invert();
  34923. this.polygons = a.allPolygons();
  34924. };
  34925. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  34926. // not modified.
  34927. CSG.prototype.inverse = function () {
  34928. var csg = this.clone();
  34929. csg.inverseInPlace();
  34930. return csg;
  34931. };
  34932. CSG.prototype.inverseInPlace = function () {
  34933. this.polygons.map(function (p) { p.flip(); });
  34934. };
  34935. // This is used to keep meshes transformations so they can be restored
  34936. // when we build back a Babylon Mesh
  34937. // NB : All CSG operations are performed in world coordinates
  34938. CSG.prototype.copyTransformAttributes = function (csg) {
  34939. this.matrix = csg.matrix;
  34940. this.position = csg.position;
  34941. this.rotation = csg.rotation;
  34942. this.scaling = csg.scaling;
  34943. this.rotationQuaternion = csg.rotationQuaternion;
  34944. return this;
  34945. };
  34946. // Build Raw mesh from CSG
  34947. // Coordinates here are in world space
  34948. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  34949. var matrix = this.matrix.clone();
  34950. matrix.invert();
  34951. 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;
  34952. if (keepSubMeshes) {
  34953. // Sort Polygons, since subMeshes are indices range
  34954. polygons.sort(function (a, b) {
  34955. if (a.shared.meshId === b.shared.meshId) {
  34956. return a.shared.subMeshId - b.shared.subMeshId;
  34957. }
  34958. else {
  34959. return a.shared.meshId - b.shared.meshId;
  34960. }
  34961. });
  34962. }
  34963. for (var i = 0, il = polygons.length; i < il; i++) {
  34964. polygon = polygons[i];
  34965. // Building SubMeshes
  34966. if (!subMesh_dict[polygon.shared.meshId]) {
  34967. subMesh_dict[polygon.shared.meshId] = {};
  34968. }
  34969. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  34970. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  34971. indexStart: +Infinity,
  34972. indexEnd: -Infinity,
  34973. materialIndex: polygon.shared.materialIndex
  34974. };
  34975. }
  34976. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  34977. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  34978. polygonIndices[0] = 0;
  34979. polygonIndices[1] = j - 1;
  34980. polygonIndices[2] = j;
  34981. for (var k = 0; k < 3; k++) {
  34982. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  34983. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  34984. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  34985. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  34986. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  34987. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  34988. // Check if 2 points can be merged
  34989. if (!(typeof vertex_idx !== 'undefined' &&
  34990. normals[vertex_idx * 3] === localNormal.x &&
  34991. normals[vertex_idx * 3 + 1] === localNormal.y &&
  34992. normals[vertex_idx * 3 + 2] === localNormal.z &&
  34993. uvs[vertex_idx * 2] === uv.x &&
  34994. uvs[vertex_idx * 2 + 1] === uv.y)) {
  34995. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  34996. uvs.push(uv.x, uv.y);
  34997. normals.push(normal.x, normal.y, normal.z);
  34998. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  34999. }
  35000. indices.push(vertex_idx);
  35001. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  35002. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  35003. currentIndex++;
  35004. }
  35005. }
  35006. }
  35007. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  35008. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  35009. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  35010. mesh.setIndices(indices);
  35011. if (keepSubMeshes) {
  35012. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  35013. var materialIndexOffset = 0, materialMaxIndex;
  35014. mesh.subMeshes = new Array();
  35015. for (var m in subMesh_dict) {
  35016. materialMaxIndex = -1;
  35017. for (var sm in subMesh_dict[m]) {
  35018. subMesh_obj = subMesh_dict[m][sm];
  35019. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  35020. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  35021. }
  35022. materialIndexOffset += ++materialMaxIndex;
  35023. }
  35024. }
  35025. return mesh;
  35026. };
  35027. // Build Mesh from CSG taking material and transforms into account
  35028. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  35029. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  35030. mesh.material = material;
  35031. mesh.position.copyFrom(this.position);
  35032. mesh.rotation.copyFrom(this.rotation);
  35033. if (this.rotationQuaternion) {
  35034. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  35035. }
  35036. mesh.scaling.copyFrom(this.scaling);
  35037. mesh.computeWorldMatrix(true);
  35038. return mesh;
  35039. };
  35040. return CSG;
  35041. })();
  35042. BABYLON.CSG = CSG;
  35043. })(BABYLON || (BABYLON = {}));
  35044. var BABYLON;
  35045. (function (BABYLON) {
  35046. var VRDistortionCorrectionPostProcess = (function (_super) {
  35047. __extends(VRDistortionCorrectionPostProcess, _super);
  35048. //ANY
  35049. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  35050. var _this = this;
  35051. _super.call(this, name, "vrDistortionCorrection", [
  35052. 'LensCenter',
  35053. 'Scale',
  35054. 'ScaleIn',
  35055. 'HmdWarpParam'
  35056. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  35057. this._isRightEye = isRightEye;
  35058. this._distortionFactors = vrMetrics.distortionK;
  35059. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  35060. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  35061. this.onSizeChanged = function () {
  35062. _this.aspectRatio = _this.width * .5 / _this.height;
  35063. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  35064. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  35065. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  35066. };
  35067. this.onApply = function (effect) {
  35068. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  35069. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  35070. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  35071. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  35072. };
  35073. }
  35074. return VRDistortionCorrectionPostProcess;
  35075. })(BABYLON.PostProcess);
  35076. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  35077. })(BABYLON || (BABYLON = {}));
  35078. // Mainly based on these 2 articles :
  35079. // 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
  35080. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  35081. var BABYLON;
  35082. (function (BABYLON) {
  35083. (function (JoystickAxis) {
  35084. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  35085. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  35086. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  35087. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  35088. var JoystickAxis = BABYLON.JoystickAxis;
  35089. var VirtualJoystick = (function () {
  35090. function VirtualJoystick(leftJoystick) {
  35091. var _this = this;
  35092. if (leftJoystick) {
  35093. this._leftJoystick = true;
  35094. }
  35095. else {
  35096. this._leftJoystick = false;
  35097. }
  35098. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  35099. VirtualJoystick._globalJoystickIndex++;
  35100. // By default left & right arrow keys are moving the X
  35101. // and up & down keys are moving the Y
  35102. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  35103. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  35104. this.reverseLeftRight = false;
  35105. this.reverseUpDown = false;
  35106. // collections of pointers
  35107. this._touches = new BABYLON.SmartCollection();
  35108. this.deltaPosition = BABYLON.Vector3.Zero();
  35109. this._joystickSensibility = 25;
  35110. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  35111. this._rotationSpeed = 25;
  35112. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  35113. this._rotateOnAxisRelativeToMesh = false;
  35114. this._onResize = function (evt) {
  35115. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  35116. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  35117. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  35118. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  35119. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  35120. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  35121. };
  35122. // injecting a canvas element on top of the canvas 3D game
  35123. if (!VirtualJoystick.vjCanvas) {
  35124. window.addEventListener("resize", this._onResize, false);
  35125. VirtualJoystick.vjCanvas = document.createElement("canvas");
  35126. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  35127. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  35128. VirtualJoystick.vjCanvas.width = window.innerWidth;
  35129. VirtualJoystick.vjCanvas.height = window.innerHeight;
  35130. VirtualJoystick.vjCanvas.style.width = "100%";
  35131. VirtualJoystick.vjCanvas.style.height = "100%";
  35132. VirtualJoystick.vjCanvas.style.position = "absolute";
  35133. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  35134. VirtualJoystick.vjCanvas.style.top = "0px";
  35135. VirtualJoystick.vjCanvas.style.left = "0px";
  35136. VirtualJoystick.vjCanvas.style.zIndex = "5";
  35137. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  35138. // Support for jQuery PEP polyfill
  35139. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  35140. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  35141. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  35142. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  35143. document.body.appendChild(VirtualJoystick.vjCanvas);
  35144. }
  35145. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  35146. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  35147. this.pressed = false;
  35148. // default joystick color
  35149. this._joystickColor = "cyan";
  35150. this._joystickPointerID = -1;
  35151. // current joystick position
  35152. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  35153. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  35154. // origin joystick position
  35155. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  35156. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  35157. this._onPointerDownHandlerRef = function (evt) {
  35158. _this._onPointerDown(evt);
  35159. };
  35160. this._onPointerMoveHandlerRef = function (evt) {
  35161. _this._onPointerMove(evt);
  35162. };
  35163. this._onPointerOutHandlerRef = function (evt) {
  35164. _this._onPointerUp(evt);
  35165. };
  35166. this._onPointerUpHandlerRef = function (evt) {
  35167. _this._onPointerUp(evt);
  35168. };
  35169. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  35170. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  35171. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  35172. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  35173. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  35174. evt.preventDefault(); // Disables system menu
  35175. }, false);
  35176. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  35177. }
  35178. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  35179. this._joystickSensibility = newJoystickSensibility;
  35180. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  35181. };
  35182. VirtualJoystick.prototype._onPointerDown = function (e) {
  35183. var positionOnScreenCondition;
  35184. e.preventDefault();
  35185. if (this._leftJoystick === true) {
  35186. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  35187. }
  35188. else {
  35189. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  35190. }
  35191. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  35192. // First contact will be dedicated to the virtual joystick
  35193. this._joystickPointerID = e.pointerId;
  35194. this._joystickPointerStartPos.x = e.clientX;
  35195. this._joystickPointerStartPos.y = e.clientY;
  35196. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  35197. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  35198. this._deltaJoystickVector.x = 0;
  35199. this._deltaJoystickVector.y = 0;
  35200. this.pressed = true;
  35201. this._touches.add(e.pointerId.toString(), e);
  35202. }
  35203. else {
  35204. // You can only trigger the action buttons with a joystick declared
  35205. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  35206. this._action();
  35207. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  35208. }
  35209. }
  35210. };
  35211. VirtualJoystick.prototype._onPointerMove = function (e) {
  35212. // If the current pointer is the one associated to the joystick (first touch contact)
  35213. if (this._joystickPointerID == e.pointerId) {
  35214. this._joystickPointerPos.x = e.clientX;
  35215. this._joystickPointerPos.y = e.clientY;
  35216. this._deltaJoystickVector = this._joystickPointerPos.clone();
  35217. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  35218. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  35219. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  35220. switch (this._axisTargetedByLeftAndRight) {
  35221. case JoystickAxis.X:
  35222. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  35223. break;
  35224. case JoystickAxis.Y:
  35225. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  35226. break;
  35227. case JoystickAxis.Z:
  35228. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  35229. break;
  35230. }
  35231. var directionUpDown = this.reverseUpDown ? 1 : -1;
  35232. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  35233. switch (this._axisTargetedByUpAndDown) {
  35234. case JoystickAxis.X:
  35235. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  35236. break;
  35237. case JoystickAxis.Y:
  35238. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  35239. break;
  35240. case JoystickAxis.Z:
  35241. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  35242. break;
  35243. }
  35244. }
  35245. else {
  35246. if (this._touches.item(e.pointerId.toString())) {
  35247. this._touches.item(e.pointerId.toString()).x = e.clientX;
  35248. this._touches.item(e.pointerId.toString()).y = e.clientY;
  35249. }
  35250. }
  35251. };
  35252. VirtualJoystick.prototype._onPointerUp = function (e) {
  35253. if (this._joystickPointerID == e.pointerId) {
  35254. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  35255. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  35256. this._joystickPointerID = -1;
  35257. this.pressed = false;
  35258. }
  35259. else {
  35260. var touch = this._touches.item(e.pointerId.toString());
  35261. if (touch) {
  35262. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  35263. }
  35264. }
  35265. this._deltaJoystickVector.x = 0;
  35266. this._deltaJoystickVector.y = 0;
  35267. this._touches.remove(e.pointerId.toString());
  35268. };
  35269. /**
  35270. * Change the color of the virtual joystick
  35271. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  35272. */
  35273. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  35274. this._joystickColor = newColor;
  35275. };
  35276. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  35277. this._action = action;
  35278. };
  35279. // Define which axis you'd like to control for left & right
  35280. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  35281. switch (axis) {
  35282. case JoystickAxis.X:
  35283. case JoystickAxis.Y:
  35284. case JoystickAxis.Z:
  35285. this._axisTargetedByLeftAndRight = axis;
  35286. break;
  35287. default:
  35288. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  35289. break;
  35290. }
  35291. };
  35292. // Define which axis you'd like to control for up & down
  35293. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  35294. switch (axis) {
  35295. case JoystickAxis.X:
  35296. case JoystickAxis.Y:
  35297. case JoystickAxis.Z:
  35298. this._axisTargetedByUpAndDown = axis;
  35299. break;
  35300. default:
  35301. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  35302. break;
  35303. }
  35304. };
  35305. VirtualJoystick.prototype._clearCanvas = function () {
  35306. if (this._leftJoystick) {
  35307. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  35308. }
  35309. else {
  35310. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  35311. }
  35312. };
  35313. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  35314. var _this = this;
  35315. if (this.pressed) {
  35316. this._touches.forEach(function (touch) {
  35317. if (touch.pointerId === _this._joystickPointerID) {
  35318. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  35319. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  35320. VirtualJoystick.vjCanvasContext.beginPath();
  35321. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  35322. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35323. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  35324. VirtualJoystick.vjCanvasContext.stroke();
  35325. VirtualJoystick.vjCanvasContext.closePath();
  35326. VirtualJoystick.vjCanvasContext.beginPath();
  35327. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35328. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  35329. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  35330. VirtualJoystick.vjCanvasContext.stroke();
  35331. VirtualJoystick.vjCanvasContext.closePath();
  35332. VirtualJoystick.vjCanvasContext.beginPath();
  35333. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35334. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  35335. VirtualJoystick.vjCanvasContext.stroke();
  35336. VirtualJoystick.vjCanvasContext.closePath();
  35337. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  35338. }
  35339. else {
  35340. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  35341. VirtualJoystick.vjCanvasContext.beginPath();
  35342. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  35343. VirtualJoystick.vjCanvasContext.beginPath();
  35344. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  35345. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  35346. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  35347. VirtualJoystick.vjCanvasContext.stroke();
  35348. VirtualJoystick.vjCanvasContext.closePath();
  35349. touch.prevX = touch.x;
  35350. touch.prevY = touch.y;
  35351. }
  35352. ;
  35353. });
  35354. }
  35355. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  35356. };
  35357. VirtualJoystick.prototype.releaseCanvas = function () {
  35358. if (VirtualJoystick.vjCanvas) {
  35359. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  35360. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  35361. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  35362. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  35363. window.removeEventListener("resize", this._onResize);
  35364. document.body.removeChild(VirtualJoystick.vjCanvas);
  35365. VirtualJoystick.vjCanvas = null;
  35366. }
  35367. };
  35368. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  35369. VirtualJoystick._globalJoystickIndex = 0;
  35370. return VirtualJoystick;
  35371. })();
  35372. BABYLON.VirtualJoystick = VirtualJoystick;
  35373. })(BABYLON || (BABYLON = {}));
  35374. var BABYLON;
  35375. (function (BABYLON) {
  35376. // We're mainly based on the logic defined into the FreeCamera code
  35377. var VirtualJoysticksCamera = (function (_super) {
  35378. __extends(VirtualJoysticksCamera, _super);
  35379. function VirtualJoysticksCamera(name, position, scene) {
  35380. _super.call(this, name, position, scene);
  35381. this.inputs.addVirtualJoystick();
  35382. }
  35383. return VirtualJoysticksCamera;
  35384. })(BABYLON.FreeCamera);
  35385. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  35386. })(BABYLON || (BABYLON = {}));
  35387. var BABYLON;
  35388. (function (BABYLON) {
  35389. var AnaglyphPostProcess = (function (_super) {
  35390. __extends(AnaglyphPostProcess, _super);
  35391. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35392. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  35393. }
  35394. return AnaglyphPostProcess;
  35395. })(BABYLON.PostProcess);
  35396. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  35397. })(BABYLON || (BABYLON = {}));
  35398. var BABYLON;
  35399. (function (BABYLON) {
  35400. var OutlineRenderer = (function () {
  35401. function OutlineRenderer(scene) {
  35402. this._scene = scene;
  35403. }
  35404. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  35405. var _this = this;
  35406. if (useOverlay === void 0) { useOverlay = false; }
  35407. var scene = this._scene;
  35408. var engine = this._scene.getEngine();
  35409. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35410. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  35411. return;
  35412. }
  35413. var mesh = subMesh.getRenderingMesh();
  35414. var material = subMesh.getMaterial();
  35415. engine.enableEffect(this._effect);
  35416. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  35417. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  35418. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35419. // Bones
  35420. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35421. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35422. }
  35423. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35424. // Alpha test
  35425. if (material && material.needAlphaTesting()) {
  35426. var alphaTexture = material.getAlphaTestTexture();
  35427. this._effect.setTexture("diffuseSampler", alphaTexture);
  35428. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35429. }
  35430. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  35431. };
  35432. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  35433. var defines = [];
  35434. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  35435. var mesh = subMesh.getMesh();
  35436. var material = subMesh.getMaterial();
  35437. // Alpha test
  35438. if (material && material.needAlphaTesting()) {
  35439. defines.push("#define ALPHATEST");
  35440. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35441. attribs.push(BABYLON.VertexBuffer.UVKind);
  35442. defines.push("#define UV1");
  35443. }
  35444. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35445. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35446. defines.push("#define UV2");
  35447. }
  35448. }
  35449. // Bones
  35450. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35451. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35452. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35453. if (mesh.numBoneInfluencers > 4) {
  35454. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35455. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35456. }
  35457. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35458. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35459. }
  35460. else {
  35461. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35462. }
  35463. // Instances
  35464. if (useInstances) {
  35465. defines.push("#define INSTANCES");
  35466. attribs.push("world0");
  35467. attribs.push("world1");
  35468. attribs.push("world2");
  35469. attribs.push("world3");
  35470. }
  35471. // Get correct effect
  35472. var join = defines.join("\n");
  35473. if (this._cachedDefines !== join) {
  35474. this._cachedDefines = join;
  35475. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  35476. }
  35477. return this._effect.isReady();
  35478. };
  35479. return OutlineRenderer;
  35480. })();
  35481. BABYLON.OutlineRenderer = OutlineRenderer;
  35482. })(BABYLON || (BABYLON = {}));
  35483. var BABYLON;
  35484. (function (BABYLON) {
  35485. var MeshAssetTask = (function () {
  35486. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  35487. this.name = name;
  35488. this.meshesNames = meshesNames;
  35489. this.rootUrl = rootUrl;
  35490. this.sceneFilename = sceneFilename;
  35491. this.isCompleted = false;
  35492. }
  35493. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35494. var _this = this;
  35495. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  35496. _this.loadedMeshes = meshes;
  35497. _this.loadedParticleSystems = particleSystems;
  35498. _this.loadedSkeletons = skeletons;
  35499. _this.isCompleted = true;
  35500. if (_this.onSuccess) {
  35501. _this.onSuccess(_this);
  35502. }
  35503. onSuccess();
  35504. }, null, function () {
  35505. if (_this.onError) {
  35506. _this.onError(_this);
  35507. }
  35508. onError();
  35509. });
  35510. };
  35511. return MeshAssetTask;
  35512. })();
  35513. BABYLON.MeshAssetTask = MeshAssetTask;
  35514. var TextFileAssetTask = (function () {
  35515. function TextFileAssetTask(name, url) {
  35516. this.name = name;
  35517. this.url = url;
  35518. this.isCompleted = false;
  35519. }
  35520. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35521. var _this = this;
  35522. BABYLON.Tools.LoadFile(this.url, function (data) {
  35523. _this.text = data;
  35524. _this.isCompleted = true;
  35525. if (_this.onSuccess) {
  35526. _this.onSuccess(_this);
  35527. }
  35528. onSuccess();
  35529. }, null, scene.database, false, function () {
  35530. if (_this.onError) {
  35531. _this.onError(_this);
  35532. }
  35533. onError();
  35534. });
  35535. };
  35536. return TextFileAssetTask;
  35537. })();
  35538. BABYLON.TextFileAssetTask = TextFileAssetTask;
  35539. var BinaryFileAssetTask = (function () {
  35540. function BinaryFileAssetTask(name, url) {
  35541. this.name = name;
  35542. this.url = url;
  35543. this.isCompleted = false;
  35544. }
  35545. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35546. var _this = this;
  35547. BABYLON.Tools.LoadFile(this.url, function (data) {
  35548. _this.data = data;
  35549. _this.isCompleted = true;
  35550. if (_this.onSuccess) {
  35551. _this.onSuccess(_this);
  35552. }
  35553. onSuccess();
  35554. }, null, scene.database, true, function () {
  35555. if (_this.onError) {
  35556. _this.onError(_this);
  35557. }
  35558. onError();
  35559. });
  35560. };
  35561. return BinaryFileAssetTask;
  35562. })();
  35563. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  35564. var ImageAssetTask = (function () {
  35565. function ImageAssetTask(name, url) {
  35566. this.name = name;
  35567. this.url = url;
  35568. this.isCompleted = false;
  35569. }
  35570. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35571. var _this = this;
  35572. var img = new Image();
  35573. img.onload = function () {
  35574. _this.image = img;
  35575. _this.isCompleted = true;
  35576. if (_this.onSuccess) {
  35577. _this.onSuccess(_this);
  35578. }
  35579. onSuccess();
  35580. };
  35581. img.onerror = function () {
  35582. if (_this.onError) {
  35583. _this.onError(_this);
  35584. }
  35585. onError();
  35586. };
  35587. img.src = this.url;
  35588. };
  35589. return ImageAssetTask;
  35590. })();
  35591. BABYLON.ImageAssetTask = ImageAssetTask;
  35592. var TextureAssetTask = (function () {
  35593. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  35594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35595. this.name = name;
  35596. this.url = url;
  35597. this.noMipmap = noMipmap;
  35598. this.invertY = invertY;
  35599. this.samplingMode = samplingMode;
  35600. this.isCompleted = false;
  35601. }
  35602. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35603. var _this = this;
  35604. var onload = function () {
  35605. _this.isCompleted = true;
  35606. if (_this.onSuccess) {
  35607. _this.onSuccess(_this);
  35608. }
  35609. onSuccess();
  35610. };
  35611. var onerror = function () {
  35612. if (_this.onError) {
  35613. _this.onError(_this);
  35614. }
  35615. onError();
  35616. };
  35617. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  35618. };
  35619. return TextureAssetTask;
  35620. })();
  35621. BABYLON.TextureAssetTask = TextureAssetTask;
  35622. var AssetsManager = (function () {
  35623. function AssetsManager(scene) {
  35624. this._tasks = new Array();
  35625. this._waitingTasksCount = 0;
  35626. this.useDefaultLoadingScreen = true;
  35627. this._scene = scene;
  35628. }
  35629. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  35630. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  35631. this._tasks.push(task);
  35632. return task;
  35633. };
  35634. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  35635. var task = new TextFileAssetTask(taskName, url);
  35636. this._tasks.push(task);
  35637. return task;
  35638. };
  35639. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  35640. var task = new BinaryFileAssetTask(taskName, url);
  35641. this._tasks.push(task);
  35642. return task;
  35643. };
  35644. AssetsManager.prototype.addImageTask = function (taskName, url) {
  35645. var task = new ImageAssetTask(taskName, url);
  35646. this._tasks.push(task);
  35647. return task;
  35648. };
  35649. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  35650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35651. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  35652. this._tasks.push(task);
  35653. return task;
  35654. };
  35655. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  35656. this._waitingTasksCount--;
  35657. if (this._waitingTasksCount === 0) {
  35658. if (this.onFinish) {
  35659. this.onFinish(this._tasks);
  35660. }
  35661. this._scene.getEngine().hideLoadingUI();
  35662. }
  35663. };
  35664. AssetsManager.prototype._runTask = function (task) {
  35665. var _this = this;
  35666. task.run(this._scene, function () {
  35667. if (_this.onTaskSuccess) {
  35668. _this.onTaskSuccess(task);
  35669. }
  35670. _this._decreaseWaitingTasksCount();
  35671. }, function () {
  35672. if (_this.onTaskError) {
  35673. _this.onTaskError(task);
  35674. }
  35675. _this._decreaseWaitingTasksCount();
  35676. });
  35677. };
  35678. AssetsManager.prototype.reset = function () {
  35679. this._tasks = new Array();
  35680. return this;
  35681. };
  35682. AssetsManager.prototype.load = function () {
  35683. this._waitingTasksCount = this._tasks.length;
  35684. if (this._waitingTasksCount === 0) {
  35685. if (this.onFinish) {
  35686. this.onFinish(this._tasks);
  35687. }
  35688. return this;
  35689. }
  35690. if (this.useDefaultLoadingScreen) {
  35691. this._scene.getEngine().displayLoadingUI();
  35692. }
  35693. for (var index = 0; index < this._tasks.length; index++) {
  35694. var task = this._tasks[index];
  35695. this._runTask(task);
  35696. }
  35697. return this;
  35698. };
  35699. return AssetsManager;
  35700. })();
  35701. BABYLON.AssetsManager = AssetsManager;
  35702. })(BABYLON || (BABYLON = {}));
  35703. var BABYLON;
  35704. (function (BABYLON) {
  35705. var VRCameraMetrics = (function () {
  35706. function VRCameraMetrics() {
  35707. this.compensateDistortion = true;
  35708. }
  35709. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  35710. get: function () {
  35711. return this.hResolution / (2 * this.vResolution);
  35712. },
  35713. enumerable: true,
  35714. configurable: true
  35715. });
  35716. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  35717. get: function () {
  35718. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  35719. },
  35720. enumerable: true,
  35721. configurable: true
  35722. });
  35723. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  35724. get: function () {
  35725. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  35726. var h = (4 * meters) / this.hScreenSize;
  35727. return BABYLON.Matrix.Translation(h, 0, 0);
  35728. },
  35729. enumerable: true,
  35730. configurable: true
  35731. });
  35732. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  35733. get: function () {
  35734. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  35735. var h = (4 * meters) / this.hScreenSize;
  35736. return BABYLON.Matrix.Translation(-h, 0, 0);
  35737. },
  35738. enumerable: true,
  35739. configurable: true
  35740. });
  35741. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  35742. get: function () {
  35743. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  35744. },
  35745. enumerable: true,
  35746. configurable: true
  35747. });
  35748. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  35749. get: function () {
  35750. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  35751. },
  35752. enumerable: true,
  35753. configurable: true
  35754. });
  35755. VRCameraMetrics.GetDefault = function () {
  35756. var result = new VRCameraMetrics();
  35757. result.hResolution = 1280;
  35758. result.vResolution = 800;
  35759. result.hScreenSize = 0.149759993;
  35760. result.vScreenSize = 0.0935999975;
  35761. result.vScreenCenter = 0.0467999987,
  35762. result.eyeToScreenDistance = 0.0410000011;
  35763. result.lensSeparationDistance = 0.0635000020;
  35764. result.interpupillaryDistance = 0.0640000030;
  35765. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  35766. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  35767. result.postProcessScaleFactor = 1.714605507808412;
  35768. result.lensCenterOffset = 0.151976421;
  35769. return result;
  35770. };
  35771. return VRCameraMetrics;
  35772. })();
  35773. BABYLON.VRCameraMetrics = VRCameraMetrics;
  35774. })(BABYLON || (BABYLON = {}));
  35775. var BABYLON;
  35776. (function (BABYLON) {
  35777. var VRDeviceOrientationFreeCamera = (function (_super) {
  35778. __extends(VRDeviceOrientationFreeCamera, _super);
  35779. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  35780. if (compensateDistortion === void 0) { compensateDistortion = true; }
  35781. _super.call(this, name, position, scene);
  35782. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  35783. metrics.compensateDistortion = compensateDistortion;
  35784. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  35785. this.inputs.addVRDeviceOrientation();
  35786. }
  35787. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  35788. return "VRDeviceOrientationFreeCamera";
  35789. };
  35790. return VRDeviceOrientationFreeCamera;
  35791. })(BABYLON.FreeCamera);
  35792. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  35793. })(BABYLON || (BABYLON = {}));
  35794. var BABYLON;
  35795. (function (BABYLON) {
  35796. var WebVRFreeCamera = (function (_super) {
  35797. __extends(WebVRFreeCamera, _super);
  35798. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  35799. if (compensateDistortion === void 0) { compensateDistortion = true; }
  35800. _super.call(this, name, position, scene);
  35801. this._hmdDevice = null;
  35802. this._sensorDevice = null;
  35803. this._cacheState = null;
  35804. this._cacheQuaternion = new BABYLON.Quaternion();
  35805. this._cacheRotation = BABYLON.Vector3.Zero();
  35806. this._vrEnabled = false;
  35807. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  35808. metrics.compensateDistortion = compensateDistortion;
  35809. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  35810. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  35811. }
  35812. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  35813. var size = devices.length;
  35814. var i = 0;
  35815. // Reset devices.
  35816. this._sensorDevice = null;
  35817. this._hmdDevice = null;
  35818. // Search for a HmdDevice.
  35819. while (i < size && this._hmdDevice === null) {
  35820. if (devices[i] instanceof HMDVRDevice) {
  35821. this._hmdDevice = devices[i];
  35822. }
  35823. i++;
  35824. }
  35825. i = 0;
  35826. while (i < size && this._sensorDevice === null) {
  35827. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  35828. this._sensorDevice = devices[i];
  35829. }
  35830. i++;
  35831. }
  35832. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  35833. };
  35834. WebVRFreeCamera.prototype._checkInputs = function () {
  35835. if (this._vrEnabled) {
  35836. this._cacheState = this._sensorDevice.getState();
  35837. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  35838. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  35839. this.rotation.x = -this._cacheRotation.x;
  35840. this.rotation.y = -this._cacheRotation.y;
  35841. this.rotation.z = this._cacheRotation.z;
  35842. }
  35843. _super.prototype._checkInputs.call(this);
  35844. };
  35845. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  35846. _super.prototype.attachControl.call(this, element, noPreventDefault);
  35847. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  35848. if (navigator.getVRDevices) {
  35849. navigator.getVRDevices().then(this._getWebVRDevices);
  35850. }
  35851. else if (navigator.mozGetVRDevices) {
  35852. navigator.mozGetVRDevices(this._getWebVRDevices);
  35853. }
  35854. };
  35855. WebVRFreeCamera.prototype.detachControl = function (element) {
  35856. _super.prototype.detachControl.call(this, element);
  35857. this._vrEnabled = false;
  35858. };
  35859. WebVRFreeCamera.prototype.getTypeName = function () {
  35860. return "WebVRFreeCamera";
  35861. };
  35862. return WebVRFreeCamera;
  35863. })(BABYLON.FreeCamera);
  35864. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  35865. })(BABYLON || (BABYLON = {}));
  35866. var BABYLON;
  35867. (function (BABYLON) {
  35868. // Standard optimizations
  35869. var SceneOptimization = (function () {
  35870. function SceneOptimization(priority) {
  35871. if (priority === void 0) { priority = 0; }
  35872. this.priority = priority;
  35873. this.apply = function (scene) {
  35874. return true; // Return true if everything that can be done was applied
  35875. };
  35876. }
  35877. return SceneOptimization;
  35878. })();
  35879. BABYLON.SceneOptimization = SceneOptimization;
  35880. var TextureOptimization = (function (_super) {
  35881. __extends(TextureOptimization, _super);
  35882. function TextureOptimization(priority, maximumSize) {
  35883. var _this = this;
  35884. if (priority === void 0) { priority = 0; }
  35885. if (maximumSize === void 0) { maximumSize = 1024; }
  35886. _super.call(this, priority);
  35887. this.priority = priority;
  35888. this.maximumSize = maximumSize;
  35889. this.apply = function (scene) {
  35890. var allDone = true;
  35891. for (var index = 0; index < scene.textures.length; index++) {
  35892. var texture = scene.textures[index];
  35893. if (!texture.canRescale) {
  35894. continue;
  35895. }
  35896. var currentSize = texture.getSize();
  35897. var maxDimension = Math.max(currentSize.width, currentSize.height);
  35898. if (maxDimension > _this.maximumSize) {
  35899. texture.scale(0.5);
  35900. allDone = false;
  35901. }
  35902. }
  35903. return allDone;
  35904. };
  35905. }
  35906. return TextureOptimization;
  35907. })(SceneOptimization);
  35908. BABYLON.TextureOptimization = TextureOptimization;
  35909. var HardwareScalingOptimization = (function (_super) {
  35910. __extends(HardwareScalingOptimization, _super);
  35911. function HardwareScalingOptimization(priority, maximumScale) {
  35912. var _this = this;
  35913. if (priority === void 0) { priority = 0; }
  35914. if (maximumScale === void 0) { maximumScale = 2; }
  35915. _super.call(this, priority);
  35916. this.priority = priority;
  35917. this.maximumScale = maximumScale;
  35918. this._currentScale = 1;
  35919. this.apply = function (scene) {
  35920. _this._currentScale++;
  35921. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  35922. return _this._currentScale >= _this.maximumScale;
  35923. };
  35924. }
  35925. return HardwareScalingOptimization;
  35926. })(SceneOptimization);
  35927. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  35928. var ShadowsOptimization = (function (_super) {
  35929. __extends(ShadowsOptimization, _super);
  35930. function ShadowsOptimization() {
  35931. _super.apply(this, arguments);
  35932. this.apply = function (scene) {
  35933. scene.shadowsEnabled = false;
  35934. return true;
  35935. };
  35936. }
  35937. return ShadowsOptimization;
  35938. })(SceneOptimization);
  35939. BABYLON.ShadowsOptimization = ShadowsOptimization;
  35940. var PostProcessesOptimization = (function (_super) {
  35941. __extends(PostProcessesOptimization, _super);
  35942. function PostProcessesOptimization() {
  35943. _super.apply(this, arguments);
  35944. this.apply = function (scene) {
  35945. scene.postProcessesEnabled = false;
  35946. return true;
  35947. };
  35948. }
  35949. return PostProcessesOptimization;
  35950. })(SceneOptimization);
  35951. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  35952. var LensFlaresOptimization = (function (_super) {
  35953. __extends(LensFlaresOptimization, _super);
  35954. function LensFlaresOptimization() {
  35955. _super.apply(this, arguments);
  35956. this.apply = function (scene) {
  35957. scene.lensFlaresEnabled = false;
  35958. return true;
  35959. };
  35960. }
  35961. return LensFlaresOptimization;
  35962. })(SceneOptimization);
  35963. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  35964. var ParticlesOptimization = (function (_super) {
  35965. __extends(ParticlesOptimization, _super);
  35966. function ParticlesOptimization() {
  35967. _super.apply(this, arguments);
  35968. this.apply = function (scene) {
  35969. scene.particlesEnabled = false;
  35970. return true;
  35971. };
  35972. }
  35973. return ParticlesOptimization;
  35974. })(SceneOptimization);
  35975. BABYLON.ParticlesOptimization = ParticlesOptimization;
  35976. var RenderTargetsOptimization = (function (_super) {
  35977. __extends(RenderTargetsOptimization, _super);
  35978. function RenderTargetsOptimization() {
  35979. _super.apply(this, arguments);
  35980. this.apply = function (scene) {
  35981. scene.renderTargetsEnabled = false;
  35982. return true;
  35983. };
  35984. }
  35985. return RenderTargetsOptimization;
  35986. })(SceneOptimization);
  35987. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  35988. var MergeMeshesOptimization = (function (_super) {
  35989. __extends(MergeMeshesOptimization, _super);
  35990. function MergeMeshesOptimization() {
  35991. var _this = this;
  35992. _super.apply(this, arguments);
  35993. this._canBeMerged = function (abstractMesh) {
  35994. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  35995. return false;
  35996. }
  35997. var mesh = abstractMesh;
  35998. if (!mesh.isVisible || !mesh.isEnabled()) {
  35999. return false;
  36000. }
  36001. if (mesh.instances.length > 0) {
  36002. return false;
  36003. }
  36004. if (mesh.skeleton || mesh.hasLODLevels) {
  36005. return false;
  36006. }
  36007. if (mesh.parent) {
  36008. return false;
  36009. }
  36010. return true;
  36011. };
  36012. this.apply = function (scene, updateSelectionTree) {
  36013. var globalPool = scene.meshes.slice(0);
  36014. var globalLength = globalPool.length;
  36015. for (var index = 0; index < globalLength; index++) {
  36016. var currentPool = new Array();
  36017. var current = globalPool[index];
  36018. // Checks
  36019. if (!_this._canBeMerged(current)) {
  36020. continue;
  36021. }
  36022. currentPool.push(current);
  36023. // Find compatible meshes
  36024. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  36025. var otherMesh = globalPool[subIndex];
  36026. if (!_this._canBeMerged(otherMesh)) {
  36027. continue;
  36028. }
  36029. if (otherMesh.material !== current.material) {
  36030. continue;
  36031. }
  36032. if (otherMesh.checkCollisions !== current.checkCollisions) {
  36033. continue;
  36034. }
  36035. currentPool.push(otherMesh);
  36036. globalLength--;
  36037. globalPool.splice(subIndex, 1);
  36038. subIndex--;
  36039. }
  36040. if (currentPool.length < 2) {
  36041. continue;
  36042. }
  36043. // Merge meshes
  36044. BABYLON.Mesh.MergeMeshes(currentPool);
  36045. }
  36046. if (updateSelectionTree != undefined) {
  36047. if (updateSelectionTree) {
  36048. scene.createOrUpdateSelectionOctree();
  36049. }
  36050. }
  36051. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  36052. scene.createOrUpdateSelectionOctree();
  36053. }
  36054. return true;
  36055. };
  36056. }
  36057. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  36058. get: function () {
  36059. return MergeMeshesOptimization._UpdateSelectionTree;
  36060. },
  36061. set: function (value) {
  36062. MergeMeshesOptimization._UpdateSelectionTree = value;
  36063. },
  36064. enumerable: true,
  36065. configurable: true
  36066. });
  36067. MergeMeshesOptimization._UpdateSelectionTree = false;
  36068. return MergeMeshesOptimization;
  36069. })(SceneOptimization);
  36070. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  36071. // Options
  36072. var SceneOptimizerOptions = (function () {
  36073. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  36074. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  36075. if (trackerDuration === void 0) { trackerDuration = 2000; }
  36076. this.targetFrameRate = targetFrameRate;
  36077. this.trackerDuration = trackerDuration;
  36078. this.optimizations = new Array();
  36079. }
  36080. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  36081. var result = new SceneOptimizerOptions(targetFrameRate);
  36082. var priority = 0;
  36083. result.optimizations.push(new MergeMeshesOptimization(priority));
  36084. result.optimizations.push(new ShadowsOptimization(priority));
  36085. result.optimizations.push(new LensFlaresOptimization(priority));
  36086. // Next priority
  36087. priority++;
  36088. result.optimizations.push(new PostProcessesOptimization(priority));
  36089. result.optimizations.push(new ParticlesOptimization(priority));
  36090. // Next priority
  36091. priority++;
  36092. result.optimizations.push(new TextureOptimization(priority, 1024));
  36093. return result;
  36094. };
  36095. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  36096. var result = new SceneOptimizerOptions(targetFrameRate);
  36097. var priority = 0;
  36098. result.optimizations.push(new MergeMeshesOptimization(priority));
  36099. result.optimizations.push(new ShadowsOptimization(priority));
  36100. result.optimizations.push(new LensFlaresOptimization(priority));
  36101. // Next priority
  36102. priority++;
  36103. result.optimizations.push(new PostProcessesOptimization(priority));
  36104. result.optimizations.push(new ParticlesOptimization(priority));
  36105. // Next priority
  36106. priority++;
  36107. result.optimizations.push(new TextureOptimization(priority, 512));
  36108. // Next priority
  36109. priority++;
  36110. result.optimizations.push(new RenderTargetsOptimization(priority));
  36111. // Next priority
  36112. priority++;
  36113. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  36114. return result;
  36115. };
  36116. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  36117. var result = new SceneOptimizerOptions(targetFrameRate);
  36118. var priority = 0;
  36119. result.optimizations.push(new MergeMeshesOptimization(priority));
  36120. result.optimizations.push(new ShadowsOptimization(priority));
  36121. result.optimizations.push(new LensFlaresOptimization(priority));
  36122. // Next priority
  36123. priority++;
  36124. result.optimizations.push(new PostProcessesOptimization(priority));
  36125. result.optimizations.push(new ParticlesOptimization(priority));
  36126. // Next priority
  36127. priority++;
  36128. result.optimizations.push(new TextureOptimization(priority, 256));
  36129. // Next priority
  36130. priority++;
  36131. result.optimizations.push(new RenderTargetsOptimization(priority));
  36132. // Next priority
  36133. priority++;
  36134. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  36135. return result;
  36136. };
  36137. return SceneOptimizerOptions;
  36138. })();
  36139. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  36140. // Scene optimizer tool
  36141. var SceneOptimizer = (function () {
  36142. function SceneOptimizer() {
  36143. }
  36144. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  36145. // TODO: add an epsilon
  36146. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  36147. if (onSuccess) {
  36148. onSuccess();
  36149. }
  36150. return;
  36151. }
  36152. // Apply current level of optimizations
  36153. var allDone = true;
  36154. var noOptimizationApplied = true;
  36155. for (var index = 0; index < options.optimizations.length; index++) {
  36156. var optimization = options.optimizations[index];
  36157. if (optimization.priority === currentPriorityLevel) {
  36158. noOptimizationApplied = false;
  36159. allDone = allDone && optimization.apply(scene);
  36160. }
  36161. }
  36162. // If no optimization was applied, this is a failure :(
  36163. if (noOptimizationApplied) {
  36164. if (onFailure) {
  36165. onFailure();
  36166. }
  36167. return;
  36168. }
  36169. // If all optimizations were done, move to next level
  36170. if (allDone) {
  36171. currentPriorityLevel++;
  36172. }
  36173. // Let's the system running for a specific amount of time before checking FPS
  36174. scene.executeWhenReady(function () {
  36175. setTimeout(function () {
  36176. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  36177. }, options.trackerDuration);
  36178. });
  36179. };
  36180. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  36181. if (!options) {
  36182. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  36183. }
  36184. // Let's the system running for a specific amount of time before checking FPS
  36185. scene.executeWhenReady(function () {
  36186. setTimeout(function () {
  36187. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  36188. }, options.trackerDuration);
  36189. });
  36190. };
  36191. return SceneOptimizer;
  36192. })();
  36193. BABYLON.SceneOptimizer = SceneOptimizer;
  36194. })(BABYLON || (BABYLON = {}));
  36195. var BABYLON;
  36196. (function (BABYLON) {
  36197. var Internals;
  36198. (function (Internals) {
  36199. var MeshLODLevel = (function () {
  36200. function MeshLODLevel(distance, mesh) {
  36201. this.distance = distance;
  36202. this.mesh = mesh;
  36203. }
  36204. return MeshLODLevel;
  36205. })();
  36206. Internals.MeshLODLevel = MeshLODLevel;
  36207. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36208. })(BABYLON || (BABYLON = {}));
  36209. var BABYLON;
  36210. (function (BABYLON) {
  36211. var RawTexture = (function (_super) {
  36212. __extends(RawTexture, _super);
  36213. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  36214. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36215. if (invertY === void 0) { invertY = false; }
  36216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36217. _super.call(this, null, scene, !generateMipMaps, invertY);
  36218. this.format = format;
  36219. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  36220. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36221. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36222. }
  36223. RawTexture.prototype.update = function (data) {
  36224. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  36225. };
  36226. // Statics
  36227. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36228. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36229. if (invertY === void 0) { invertY = false; }
  36230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36231. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  36232. };
  36233. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36234. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36235. if (invertY === void 0) { invertY = false; }
  36236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36237. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  36238. };
  36239. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36240. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36241. if (invertY === void 0) { invertY = false; }
  36242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36243. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  36244. };
  36245. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36246. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36247. if (invertY === void 0) { invertY = false; }
  36248. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36249. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  36250. };
  36251. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36252. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36253. if (invertY === void 0) { invertY = false; }
  36254. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36255. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  36256. };
  36257. return RawTexture;
  36258. })(BABYLON.Texture);
  36259. BABYLON.RawTexture = RawTexture;
  36260. })(BABYLON || (BABYLON = {}));
  36261. var BABYLON;
  36262. (function (BABYLON) {
  36263. var IndexedVector2 = (function (_super) {
  36264. __extends(IndexedVector2, _super);
  36265. function IndexedVector2(original, index) {
  36266. _super.call(this, original.x, original.y);
  36267. this.index = index;
  36268. }
  36269. return IndexedVector2;
  36270. })(BABYLON.Vector2);
  36271. var PolygonPoints = (function () {
  36272. function PolygonPoints() {
  36273. this.elements = new Array();
  36274. }
  36275. PolygonPoints.prototype.add = function (originalPoints) {
  36276. var _this = this;
  36277. var result = new Array();
  36278. originalPoints.forEach(function (point) {
  36279. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  36280. var newPoint = new IndexedVector2(point, _this.elements.length);
  36281. result.push(newPoint);
  36282. _this.elements.push(newPoint);
  36283. }
  36284. });
  36285. return result;
  36286. };
  36287. PolygonPoints.prototype.computeBounds = function () {
  36288. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  36289. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  36290. this.elements.forEach(function (point) {
  36291. // x
  36292. if (point.x < lmin.x) {
  36293. lmin.x = point.x;
  36294. }
  36295. else if (point.x > lmax.x) {
  36296. lmax.x = point.x;
  36297. }
  36298. // y
  36299. if (point.y < lmin.y) {
  36300. lmin.y = point.y;
  36301. }
  36302. else if (point.y > lmax.y) {
  36303. lmax.y = point.y;
  36304. }
  36305. });
  36306. return {
  36307. min: lmin,
  36308. max: lmax,
  36309. width: lmax.x - lmin.x,
  36310. height: lmax.y - lmin.y
  36311. };
  36312. };
  36313. return PolygonPoints;
  36314. })();
  36315. var Polygon = (function () {
  36316. function Polygon() {
  36317. }
  36318. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  36319. return [
  36320. new BABYLON.Vector2(xmin, ymin),
  36321. new BABYLON.Vector2(xmax, ymin),
  36322. new BABYLON.Vector2(xmax, ymax),
  36323. new BABYLON.Vector2(xmin, ymax)
  36324. ];
  36325. };
  36326. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  36327. if (cx === void 0) { cx = 0; }
  36328. if (cy === void 0) { cy = 0; }
  36329. if (numberOfSides === void 0) { numberOfSides = 32; }
  36330. var result = new Array();
  36331. var angle = 0;
  36332. var increment = (Math.PI * 2) / numberOfSides;
  36333. for (var i = 0; i < numberOfSides; i++) {
  36334. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  36335. angle -= increment;
  36336. }
  36337. return result;
  36338. };
  36339. Polygon.Parse = function (input) {
  36340. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  36341. var i, result = [];
  36342. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  36343. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  36344. }
  36345. return result;
  36346. };
  36347. Polygon.StartingAt = function (x, y) {
  36348. return BABYLON.Path2.StartingAt(x, y);
  36349. };
  36350. return Polygon;
  36351. })();
  36352. BABYLON.Polygon = Polygon;
  36353. var PolygonMeshBuilder = (function () {
  36354. function PolygonMeshBuilder(name, contours, scene) {
  36355. this._points = new PolygonPoints();
  36356. this._outlinepoints = new PolygonPoints();
  36357. this._holes = [];
  36358. if (!("poly2tri" in window)) {
  36359. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  36360. }
  36361. this._name = name;
  36362. this._scene = scene;
  36363. var points;
  36364. if (contours instanceof BABYLON.Path2) {
  36365. points = contours.getPoints();
  36366. }
  36367. else {
  36368. points = contours;
  36369. }
  36370. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  36371. this._outlinepoints.add(points);
  36372. }
  36373. PolygonMeshBuilder.prototype.addHole = function (hole) {
  36374. this._swctx.addHole(this._points.add(hole));
  36375. var holepoints = new PolygonPoints();
  36376. holepoints.add(hole);
  36377. this._holes.push(holepoints);
  36378. return this;
  36379. };
  36380. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  36381. var _this = this;
  36382. if (updatable === void 0) { updatable = false; }
  36383. var result = new BABYLON.Mesh(this._name, this._scene);
  36384. var normals = [];
  36385. var positions = [];
  36386. var uvs = [];
  36387. var bounds = this._points.computeBounds();
  36388. this._points.elements.forEach(function (p) {
  36389. normals.push(0, 1.0, 0);
  36390. positions.push(p.x, 0, p.y);
  36391. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  36392. });
  36393. var indices = [];
  36394. this._swctx.triangulate();
  36395. this._swctx.getTriangles().forEach(function (triangle) {
  36396. triangle.getPoints().forEach(function (point) {
  36397. indices.push(point.index);
  36398. });
  36399. });
  36400. if (depth > 0) {
  36401. var positionscount = (positions.length / 3); //get the current pointcount
  36402. this._points.elements.forEach(function (p) {
  36403. normals.push(0, -1.0, 0);
  36404. positions.push(p.x, -depth, p.y);
  36405. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  36406. });
  36407. var p1; //we need to change order of point so the triangles are made in the rigth way.
  36408. var p2;
  36409. var poscounter = 0;
  36410. this._swctx.getTriangles().forEach(function (triangle) {
  36411. triangle.getPoints().forEach(function (point) {
  36412. switch (poscounter) {
  36413. case 0:
  36414. p1 = point;
  36415. break;
  36416. case 1:
  36417. p2 = point;
  36418. break;
  36419. case 2:
  36420. indices.push(point.index + positionscount);
  36421. indices.push(p2.index + positionscount);
  36422. indices.push(p1.index + positionscount);
  36423. poscounter = -1;
  36424. break;
  36425. }
  36426. poscounter++;
  36427. //indices.push((<IndexedVector2>point).index + positionscount);
  36428. });
  36429. });
  36430. //Add the sides
  36431. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  36432. this._holes.forEach(function (hole) {
  36433. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  36434. });
  36435. }
  36436. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  36437. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  36438. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  36439. result.setIndices(indices);
  36440. return result;
  36441. };
  36442. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  36443. var StartIndex = positions.length / 3;
  36444. var ulength = 0;
  36445. for (var i = 0; i < points.elements.length; i++) {
  36446. var p = points.elements[i];
  36447. var p1;
  36448. if ((i + 1) > points.elements.length - 1) {
  36449. p1 = points.elements[0];
  36450. }
  36451. else {
  36452. p1 = points.elements[i + 1];
  36453. }
  36454. positions.push(p.x, 0, p.y);
  36455. positions.push(p.x, -depth, p.y);
  36456. positions.push(p1.x, 0, p1.y);
  36457. positions.push(p1.x, -depth, p1.y);
  36458. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  36459. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  36460. var v3 = v2.subtract(v1);
  36461. var v4 = new BABYLON.Vector3(0, 1, 0);
  36462. var vn = BABYLON.Vector3.Cross(v3, v4);
  36463. vn = vn.normalize();
  36464. uvs.push(ulength / bounds.width, 0);
  36465. uvs.push(ulength / bounds.width, 1);
  36466. ulength += v3.length();
  36467. uvs.push((ulength / bounds.width), 0);
  36468. uvs.push((ulength / bounds.width), 1);
  36469. if (!flip) {
  36470. normals.push(-vn.x, -vn.y, -vn.z);
  36471. normals.push(-vn.x, -vn.y, -vn.z);
  36472. normals.push(-vn.x, -vn.y, -vn.z);
  36473. normals.push(-vn.x, -vn.y, -vn.z);
  36474. indices.push(StartIndex);
  36475. indices.push(StartIndex + 1);
  36476. indices.push(StartIndex + 2);
  36477. indices.push(StartIndex + 1);
  36478. indices.push(StartIndex + 3);
  36479. indices.push(StartIndex + 2);
  36480. }
  36481. else {
  36482. normals.push(vn.x, vn.y, vn.z);
  36483. normals.push(vn.x, vn.y, vn.z);
  36484. normals.push(vn.x, vn.y, vn.z);
  36485. normals.push(vn.x, vn.y, vn.z);
  36486. indices.push(StartIndex);
  36487. indices.push(StartIndex + 2);
  36488. indices.push(StartIndex + 1);
  36489. indices.push(StartIndex + 1);
  36490. indices.push(StartIndex + 2);
  36491. indices.push(StartIndex + 3);
  36492. }
  36493. StartIndex += 4;
  36494. }
  36495. ;
  36496. };
  36497. return PolygonMeshBuilder;
  36498. })();
  36499. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  36500. })(BABYLON || (BABYLON = {}));
  36501. var BABYLON;
  36502. (function (BABYLON) {
  36503. var Octree = (function () {
  36504. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  36505. if (maxDepth === void 0) { maxDepth = 2; }
  36506. this.maxDepth = maxDepth;
  36507. this.dynamicContent = new Array();
  36508. this._maxBlockCapacity = maxBlockCapacity || 64;
  36509. this._selectionContent = new BABYLON.SmartArray(1024);
  36510. this._creationFunc = creationFunc;
  36511. }
  36512. // Methods
  36513. Octree.prototype.update = function (worldMin, worldMax, entries) {
  36514. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  36515. };
  36516. Octree.prototype.addMesh = function (entry) {
  36517. for (var index = 0; index < this.blocks.length; index++) {
  36518. var block = this.blocks[index];
  36519. block.addEntry(entry);
  36520. }
  36521. };
  36522. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  36523. this._selectionContent.reset();
  36524. for (var index = 0; index < this.blocks.length; index++) {
  36525. var block = this.blocks[index];
  36526. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  36527. }
  36528. if (allowDuplicate) {
  36529. this._selectionContent.concat(this.dynamicContent);
  36530. }
  36531. else {
  36532. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36533. }
  36534. return this._selectionContent;
  36535. };
  36536. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  36537. this._selectionContent.reset();
  36538. for (var index = 0; index < this.blocks.length; index++) {
  36539. var block = this.blocks[index];
  36540. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  36541. }
  36542. if (allowDuplicate) {
  36543. this._selectionContent.concat(this.dynamicContent);
  36544. }
  36545. else {
  36546. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36547. }
  36548. return this._selectionContent;
  36549. };
  36550. Octree.prototype.intersectsRay = function (ray) {
  36551. this._selectionContent.reset();
  36552. for (var index = 0; index < this.blocks.length; index++) {
  36553. var block = this.blocks[index];
  36554. block.intersectsRay(ray, this._selectionContent);
  36555. }
  36556. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36557. return this._selectionContent;
  36558. };
  36559. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  36560. target.blocks = new Array();
  36561. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  36562. // Segmenting space
  36563. for (var x = 0; x < 2; x++) {
  36564. for (var y = 0; y < 2; y++) {
  36565. for (var z = 0; z < 2; z++) {
  36566. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  36567. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  36568. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  36569. block.addEntries(entries);
  36570. target.blocks.push(block);
  36571. }
  36572. }
  36573. }
  36574. };
  36575. Octree.CreationFuncForMeshes = function (entry, block) {
  36576. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  36577. block.entries.push(entry);
  36578. }
  36579. };
  36580. Octree.CreationFuncForSubMeshes = function (entry, block) {
  36581. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  36582. block.entries.push(entry);
  36583. }
  36584. };
  36585. return Octree;
  36586. })();
  36587. BABYLON.Octree = Octree;
  36588. })(BABYLON || (BABYLON = {}));
  36589. var BABYLON;
  36590. (function (BABYLON) {
  36591. var OctreeBlock = (function () {
  36592. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  36593. this.entries = new Array();
  36594. this._boundingVectors = new Array();
  36595. this._capacity = capacity;
  36596. this._depth = depth;
  36597. this._maxDepth = maxDepth;
  36598. this._creationFunc = creationFunc;
  36599. this._minPoint = minPoint;
  36600. this._maxPoint = maxPoint;
  36601. this._boundingVectors.push(minPoint.clone());
  36602. this._boundingVectors.push(maxPoint.clone());
  36603. this._boundingVectors.push(minPoint.clone());
  36604. this._boundingVectors[2].x = maxPoint.x;
  36605. this._boundingVectors.push(minPoint.clone());
  36606. this._boundingVectors[3].y = maxPoint.y;
  36607. this._boundingVectors.push(minPoint.clone());
  36608. this._boundingVectors[4].z = maxPoint.z;
  36609. this._boundingVectors.push(maxPoint.clone());
  36610. this._boundingVectors[5].z = minPoint.z;
  36611. this._boundingVectors.push(maxPoint.clone());
  36612. this._boundingVectors[6].x = minPoint.x;
  36613. this._boundingVectors.push(maxPoint.clone());
  36614. this._boundingVectors[7].y = minPoint.y;
  36615. }
  36616. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  36617. // Property
  36618. get: function () {
  36619. return this._capacity;
  36620. },
  36621. enumerable: true,
  36622. configurable: true
  36623. });
  36624. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  36625. get: function () {
  36626. return this._minPoint;
  36627. },
  36628. enumerable: true,
  36629. configurable: true
  36630. });
  36631. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  36632. get: function () {
  36633. return this._maxPoint;
  36634. },
  36635. enumerable: true,
  36636. configurable: true
  36637. });
  36638. // Methods
  36639. OctreeBlock.prototype.addEntry = function (entry) {
  36640. if (this.blocks) {
  36641. for (var index = 0; index < this.blocks.length; index++) {
  36642. var block = this.blocks[index];
  36643. block.addEntry(entry);
  36644. }
  36645. return;
  36646. }
  36647. this._creationFunc(entry, this);
  36648. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  36649. this.createInnerBlocks();
  36650. }
  36651. };
  36652. OctreeBlock.prototype.addEntries = function (entries) {
  36653. for (var index = 0; index < entries.length; index++) {
  36654. var mesh = entries[index];
  36655. this.addEntry(mesh);
  36656. }
  36657. };
  36658. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  36659. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  36660. if (this.blocks) {
  36661. for (var index = 0; index < this.blocks.length; index++) {
  36662. var block = this.blocks[index];
  36663. block.select(frustumPlanes, selection, allowDuplicate);
  36664. }
  36665. return;
  36666. }
  36667. if (allowDuplicate) {
  36668. selection.concat(this.entries);
  36669. }
  36670. else {
  36671. selection.concatWithNoDuplicate(this.entries);
  36672. }
  36673. }
  36674. };
  36675. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  36676. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  36677. if (this.blocks) {
  36678. for (var index = 0; index < this.blocks.length; index++) {
  36679. var block = this.blocks[index];
  36680. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  36681. }
  36682. return;
  36683. }
  36684. if (allowDuplicate) {
  36685. selection.concat(this.entries);
  36686. }
  36687. else {
  36688. selection.concatWithNoDuplicate(this.entries);
  36689. }
  36690. }
  36691. };
  36692. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  36693. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  36694. if (this.blocks) {
  36695. for (var index = 0; index < this.blocks.length; index++) {
  36696. var block = this.blocks[index];
  36697. block.intersectsRay(ray, selection);
  36698. }
  36699. return;
  36700. }
  36701. selection.concatWithNoDuplicate(this.entries);
  36702. }
  36703. };
  36704. OctreeBlock.prototype.createInnerBlocks = function () {
  36705. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  36706. };
  36707. return OctreeBlock;
  36708. })();
  36709. BABYLON.OctreeBlock = OctreeBlock;
  36710. })(BABYLON || (BABYLON = {}));
  36711. var BABYLON;
  36712. (function (BABYLON) {
  36713. var BlurPostProcess = (function (_super) {
  36714. __extends(BlurPostProcess, _super);
  36715. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  36716. var _this = this;
  36717. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36718. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  36719. this.direction = direction;
  36720. this.blurWidth = blurWidth;
  36721. this.onApply = function (effect) {
  36722. effect.setFloat2("screenSize", _this.width, _this.height);
  36723. effect.setVector2("direction", _this.direction);
  36724. effect.setFloat("blurWidth", _this.blurWidth);
  36725. };
  36726. }
  36727. return BlurPostProcess;
  36728. })(BABYLON.PostProcess);
  36729. BABYLON.BlurPostProcess = BlurPostProcess;
  36730. })(BABYLON || (BABYLON = {}));
  36731. var BABYLON;
  36732. (function (BABYLON) {
  36733. var RefractionPostProcess = (function (_super) {
  36734. __extends(RefractionPostProcess, _super);
  36735. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  36736. var _this = this;
  36737. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  36738. this.color = color;
  36739. this.depth = depth;
  36740. this.colorLevel = colorLevel;
  36741. this.onActivate = function (cam) {
  36742. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  36743. };
  36744. this.onApply = function (effect) {
  36745. effect.setColor3("baseColor", _this.color);
  36746. effect.setFloat("depth", _this.depth);
  36747. effect.setFloat("colorLevel", _this.colorLevel);
  36748. effect.setTexture("refractionSampler", _this._refRexture);
  36749. };
  36750. }
  36751. // Methods
  36752. RefractionPostProcess.prototype.dispose = function (camera) {
  36753. if (this._refRexture) {
  36754. this._refRexture.dispose();
  36755. }
  36756. _super.prototype.dispose.call(this, camera);
  36757. };
  36758. return RefractionPostProcess;
  36759. })(BABYLON.PostProcess);
  36760. BABYLON.RefractionPostProcess = RefractionPostProcess;
  36761. })(BABYLON || (BABYLON = {}));
  36762. var BABYLON;
  36763. (function (BABYLON) {
  36764. var BlackAndWhitePostProcess = (function (_super) {
  36765. __extends(BlackAndWhitePostProcess, _super);
  36766. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  36767. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  36768. }
  36769. return BlackAndWhitePostProcess;
  36770. })(BABYLON.PostProcess);
  36771. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  36772. })(BABYLON || (BABYLON = {}));
  36773. var BABYLON;
  36774. (function (BABYLON) {
  36775. var ConvolutionPostProcess = (function (_super) {
  36776. __extends(ConvolutionPostProcess, _super);
  36777. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  36778. var _this = this;
  36779. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  36780. this.kernel = kernel;
  36781. this.onApply = function (effect) {
  36782. effect.setFloat2("screenSize", _this.width, _this.height);
  36783. effect.setArray("kernel", _this.kernel);
  36784. };
  36785. }
  36786. // Statics
  36787. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  36788. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  36789. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  36790. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  36791. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  36792. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  36793. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  36794. return ConvolutionPostProcess;
  36795. })(BABYLON.PostProcess);
  36796. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  36797. })(BABYLON || (BABYLON = {}));
  36798. var BABYLON;
  36799. (function (BABYLON) {
  36800. var FilterPostProcess = (function (_super) {
  36801. __extends(FilterPostProcess, _super);
  36802. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  36803. var _this = this;
  36804. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  36805. this.kernelMatrix = kernelMatrix;
  36806. this.onApply = function (effect) {
  36807. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  36808. };
  36809. }
  36810. return FilterPostProcess;
  36811. })(BABYLON.PostProcess);
  36812. BABYLON.FilterPostProcess = FilterPostProcess;
  36813. })(BABYLON || (BABYLON = {}));
  36814. var BABYLON;
  36815. (function (BABYLON) {
  36816. var FxaaPostProcess = (function (_super) {
  36817. __extends(FxaaPostProcess, _super);
  36818. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  36819. var _this = this;
  36820. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  36821. this.onSizeChanged = function () {
  36822. _this.texelWidth = 1.0 / _this.width;
  36823. _this.texelHeight = 1.0 / _this.height;
  36824. };
  36825. this.onApply = function (effect) {
  36826. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  36827. };
  36828. }
  36829. return FxaaPostProcess;
  36830. })(BABYLON.PostProcess);
  36831. BABYLON.FxaaPostProcess = FxaaPostProcess;
  36832. })(BABYLON || (BABYLON = {}));
  36833. var BABYLON;
  36834. (function (BABYLON) {
  36835. var StereoscopicInterlacePostProcess = (function (_super) {
  36836. __extends(StereoscopicInterlacePostProcess, _super);
  36837. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  36838. var _this = this;
  36839. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  36840. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  36841. this.onSizeChanged = function () {
  36842. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  36843. };
  36844. this.onApply = function (effect) {
  36845. effect.setTextureFromPostProcess("camASampler", postProcessA);
  36846. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  36847. };
  36848. }
  36849. return StereoscopicInterlacePostProcess;
  36850. })(BABYLON.PostProcess);
  36851. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  36852. })(BABYLON || (BABYLON = {}));
  36853. var BABYLON;
  36854. (function (BABYLON) {
  36855. var LensFlare = (function () {
  36856. function LensFlare(size, position, color, imgUrl, system) {
  36857. this.size = size;
  36858. this.position = position;
  36859. this.dispose = function () {
  36860. if (this.texture) {
  36861. this.texture.dispose();
  36862. }
  36863. // Remove from scene
  36864. var index = this._system.lensFlares.indexOf(this);
  36865. this._system.lensFlares.splice(index, 1);
  36866. };
  36867. this.color = color || new BABYLON.Color3(1, 1, 1);
  36868. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  36869. this._system = system;
  36870. system.lensFlares.push(this);
  36871. }
  36872. return LensFlare;
  36873. })();
  36874. BABYLON.LensFlare = LensFlare;
  36875. })(BABYLON || (BABYLON = {}));
  36876. var BABYLON;
  36877. (function (BABYLON) {
  36878. var LensFlareSystem = (function () {
  36879. function LensFlareSystem(name, emitter, scene) {
  36880. this.name = name;
  36881. this.lensFlares = new Array();
  36882. this.borderLimit = 300;
  36883. this.layerMask = 0x0FFFFFFF;
  36884. this._vertexDeclaration = [2];
  36885. this._vertexStrideSize = 2 * 4;
  36886. this._isEnabled = true;
  36887. this._scene = scene;
  36888. this._emitter = emitter;
  36889. scene.lensFlareSystems.push(this);
  36890. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  36891. // VBO
  36892. var vertices = [];
  36893. vertices.push(1, 1);
  36894. vertices.push(-1, 1);
  36895. vertices.push(-1, -1);
  36896. vertices.push(1, -1);
  36897. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  36898. // Indices
  36899. var indices = [];
  36900. indices.push(0);
  36901. indices.push(1);
  36902. indices.push(2);
  36903. indices.push(0);
  36904. indices.push(2);
  36905. indices.push(3);
  36906. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36907. // Effects
  36908. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  36909. }
  36910. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  36911. get: function () {
  36912. return this._isEnabled;
  36913. },
  36914. set: function (value) {
  36915. this._isEnabled = value;
  36916. },
  36917. enumerable: true,
  36918. configurable: true
  36919. });
  36920. LensFlareSystem.prototype.getScene = function () {
  36921. return this._scene;
  36922. };
  36923. LensFlareSystem.prototype.getEmitter = function () {
  36924. return this._emitter;
  36925. };
  36926. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  36927. this._emitter = newEmitter;
  36928. };
  36929. LensFlareSystem.prototype.getEmitterPosition = function () {
  36930. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  36931. };
  36932. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  36933. var position = this.getEmitterPosition();
  36934. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  36935. this._positionX = position.x;
  36936. this._positionY = position.y;
  36937. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  36938. if (position.z > 0) {
  36939. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  36940. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  36941. return true;
  36942. }
  36943. }
  36944. return false;
  36945. };
  36946. LensFlareSystem.prototype._isVisible = function () {
  36947. if (!this._isEnabled) {
  36948. return false;
  36949. }
  36950. var emitterPosition = this.getEmitterPosition();
  36951. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  36952. var distance = direction.length();
  36953. direction.normalize();
  36954. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  36955. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  36956. return !pickInfo.hit || pickInfo.distance > distance;
  36957. };
  36958. LensFlareSystem.prototype.render = function () {
  36959. if (!this._effect.isReady())
  36960. return false;
  36961. var engine = this._scene.getEngine();
  36962. var viewport = this._scene.activeCamera.viewport;
  36963. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  36964. // Position
  36965. if (!this.computeEffectivePosition(globalViewport)) {
  36966. return false;
  36967. }
  36968. // Visibility
  36969. if (!this._isVisible()) {
  36970. return false;
  36971. }
  36972. // Intensity
  36973. var awayX;
  36974. var awayY;
  36975. if (this._positionX < this.borderLimit + globalViewport.x) {
  36976. awayX = this.borderLimit + globalViewport.x - this._positionX;
  36977. }
  36978. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  36979. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  36980. }
  36981. else {
  36982. awayX = 0;
  36983. }
  36984. if (this._positionY < this.borderLimit + globalViewport.y) {
  36985. awayY = this.borderLimit + globalViewport.y - this._positionY;
  36986. }
  36987. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  36988. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  36989. }
  36990. else {
  36991. awayY = 0;
  36992. }
  36993. var away = (awayX > awayY) ? awayX : awayY;
  36994. if (away > this.borderLimit) {
  36995. away = this.borderLimit;
  36996. }
  36997. var intensity = 1.0 - (away / this.borderLimit);
  36998. if (intensity < 0) {
  36999. return false;
  37000. }
  37001. if (intensity > 1.0) {
  37002. intensity = 1.0;
  37003. }
  37004. // Position
  37005. var centerX = globalViewport.x + globalViewport.width / 2;
  37006. var centerY = globalViewport.y + globalViewport.height / 2;
  37007. var distX = centerX - this._positionX;
  37008. var distY = centerY - this._positionY;
  37009. // Effects
  37010. engine.enableEffect(this._effect);
  37011. engine.setState(false);
  37012. engine.setDepthBuffer(false);
  37013. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  37014. // VBOs
  37015. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  37016. // Flares
  37017. for (var index = 0; index < this.lensFlares.length; index++) {
  37018. var flare = this.lensFlares[index];
  37019. var x = centerX - (distX * flare.position);
  37020. var y = centerY - (distY * flare.position);
  37021. var cw = flare.size;
  37022. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  37023. var cx = 2 * (x / globalViewport.width) - 1.0;
  37024. var cy = 1.0 - 2 * (y / globalViewport.height);
  37025. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  37026. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  37027. // Texture
  37028. this._effect.setTexture("textureSampler", flare.texture);
  37029. // Color
  37030. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  37031. // Draw order
  37032. engine.draw(true, 0, 6);
  37033. }
  37034. engine.setDepthBuffer(true);
  37035. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37036. return true;
  37037. };
  37038. LensFlareSystem.prototype.dispose = function () {
  37039. if (this._vertexBuffer) {
  37040. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  37041. this._vertexBuffer = null;
  37042. }
  37043. if (this._indexBuffer) {
  37044. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37045. this._indexBuffer = null;
  37046. }
  37047. while (this.lensFlares.length) {
  37048. this.lensFlares[0].dispose();
  37049. }
  37050. // Remove from scene
  37051. var index = this._scene.lensFlareSystems.indexOf(this);
  37052. this._scene.lensFlareSystems.splice(index, 1);
  37053. };
  37054. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  37055. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  37056. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  37057. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  37058. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  37059. var parsedFlare = parsedLensFlareSystem.flares[index];
  37060. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  37061. }
  37062. return lensFlareSystem;
  37063. };
  37064. LensFlareSystem.prototype.serialize = function () {
  37065. var serializationObject = {};
  37066. serializationObject.emitterId = this.getEmitter().id;
  37067. serializationObject.borderLimit = this.borderLimit;
  37068. serializationObject.flares = [];
  37069. for (var index = 0; index < this.lensFlares.length; index++) {
  37070. var flare = this.lensFlares[index];
  37071. serializationObject.flares.push({
  37072. size: flare.size,
  37073. position: flare.position,
  37074. color: flare.color.asArray(),
  37075. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  37076. });
  37077. }
  37078. return serializationObject;
  37079. };
  37080. return LensFlareSystem;
  37081. })();
  37082. BABYLON.LensFlareSystem = LensFlareSystem;
  37083. })(BABYLON || (BABYLON = {}));
  37084. var BABYLON;
  37085. (function (BABYLON) {
  37086. // We're mainly based on the logic defined into the FreeCamera code
  37087. var DeviceOrientationCamera = (function (_super) {
  37088. __extends(DeviceOrientationCamera, _super);
  37089. //-- end properties for backward compatibility for inputs
  37090. function DeviceOrientationCamera(name, position, scene) {
  37091. _super.call(this, name, position, scene);
  37092. this.inputs.addDeviceOrientation();
  37093. }
  37094. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  37095. //-- Begin properties for backward compatibility for inputs
  37096. get: function () {
  37097. var gamepad = this.inputs.attached["deviceOrientation"];
  37098. if (gamepad)
  37099. return gamepad.angularSensibility;
  37100. },
  37101. set: function (value) {
  37102. var gamepad = this.inputs.attached["deviceOrientation"];
  37103. if (gamepad)
  37104. gamepad.angularSensibility = value;
  37105. },
  37106. enumerable: true,
  37107. configurable: true
  37108. });
  37109. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  37110. get: function () {
  37111. var gamepad = this.inputs.attached["deviceOrientation"];
  37112. if (gamepad)
  37113. return gamepad.moveSensibility;
  37114. },
  37115. set: function (value) {
  37116. var gamepad = this.inputs.attached["deviceOrientation"];
  37117. if (gamepad)
  37118. gamepad.moveSensibility = value;
  37119. },
  37120. enumerable: true,
  37121. configurable: true
  37122. });
  37123. DeviceOrientationCamera.prototype.getTypeName = function () {
  37124. return "DeviceOrientationCamera";
  37125. };
  37126. return DeviceOrientationCamera;
  37127. })(BABYLON.FreeCamera);
  37128. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  37129. })(BABYLON || (BABYLON = {}));
  37130. var BABYLON;
  37131. (function (BABYLON) {
  37132. // We're mainly based on the logic defined into the FreeCamera code
  37133. var UniversalCamera = (function (_super) {
  37134. __extends(UniversalCamera, _super);
  37135. //-- end properties for backward compatibility for inputs
  37136. function UniversalCamera(name, position, scene) {
  37137. _super.call(this, name, position, scene);
  37138. this.inputs.addGamepad();
  37139. }
  37140. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  37141. //-- Begin properties for backward compatibility for inputs
  37142. get: function () {
  37143. var gamepad = this.inputs.attached["gamepad"];
  37144. if (gamepad)
  37145. return gamepad.gamepadAngularSensibility;
  37146. },
  37147. set: function (value) {
  37148. var gamepad = this.inputs.attached["gamepad"];
  37149. if (gamepad)
  37150. gamepad.gamepadAngularSensibility = value;
  37151. },
  37152. enumerable: true,
  37153. configurable: true
  37154. });
  37155. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  37156. get: function () {
  37157. var gamepad = this.inputs.attached["gamepad"];
  37158. if (gamepad)
  37159. return gamepad.gamepadMoveSensibility;
  37160. },
  37161. set: function (value) {
  37162. var gamepad = this.inputs.attached["gamepad"];
  37163. if (gamepad)
  37164. gamepad.gamepadMoveSensibility = value;
  37165. },
  37166. enumerable: true,
  37167. configurable: true
  37168. });
  37169. UniversalCamera.prototype.getTypeName = function () {
  37170. return "UniversalCamera";
  37171. };
  37172. return UniversalCamera;
  37173. })(BABYLON.TouchCamera);
  37174. BABYLON.UniversalCamera = UniversalCamera;
  37175. })(BABYLON || (BABYLON = {}));
  37176. var BABYLON;
  37177. (function (BABYLON) {
  37178. var Gamepads = (function () {
  37179. function Gamepads(ongamedpadconnected) {
  37180. var _this = this;
  37181. this.babylonGamepads = [];
  37182. this.oneGamepadConnected = false;
  37183. this.isMonitoring = false;
  37184. this.gamepadEventSupported = 'GamepadEvent' in window;
  37185. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37186. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37187. this._callbackGamepadConnected = ongamedpadconnected;
  37188. if (this.gamepadSupportAvailable) {
  37189. // Checking if the gamepad connected event is supported (like in Firefox)
  37190. if (this.gamepadEventSupported) {
  37191. this._onGamepadConnectedEvent = function (evt) {
  37192. _this._onGamepadConnected(evt);
  37193. };
  37194. this._onGamepadDisonnectedEvent = function (evt) {
  37195. _this._onGamepadDisconnected(evt);
  37196. };
  37197. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  37198. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  37199. }
  37200. else {
  37201. this._startMonitoringGamepads();
  37202. }
  37203. }
  37204. }
  37205. Gamepads.prototype.dispose = function () {
  37206. if (Gamepads.gamepadDOMInfo) {
  37207. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37208. }
  37209. if (this._onGamepadConnectedEvent) {
  37210. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  37211. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  37212. this._onGamepadConnectedEvent = null;
  37213. this._onGamepadDisonnectedEvent = null;
  37214. }
  37215. };
  37216. Gamepads.prototype._onGamepadConnected = function (evt) {
  37217. var newGamepad = this._addNewGamepad(evt.gamepad);
  37218. if (this._callbackGamepadConnected)
  37219. this._callbackGamepadConnected(newGamepad);
  37220. this._startMonitoringGamepads();
  37221. };
  37222. Gamepads.prototype._addNewGamepad = function (gamepad) {
  37223. if (!this.oneGamepadConnected) {
  37224. this.oneGamepadConnected = true;
  37225. if (Gamepads.gamepadDOMInfo) {
  37226. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37227. Gamepads.gamepadDOMInfo = null;
  37228. }
  37229. }
  37230. var newGamepad;
  37231. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  37232. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  37233. }
  37234. else {
  37235. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  37236. }
  37237. this.babylonGamepads.push(newGamepad);
  37238. return newGamepad;
  37239. };
  37240. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  37241. // Remove the gamepad from the list of gamepads to monitor.
  37242. for (var i in this.babylonGamepads) {
  37243. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  37244. this.babylonGamepads.splice(+i, 1);
  37245. break;
  37246. }
  37247. }
  37248. // If no gamepads are left, stop the polling loop.
  37249. if (this.babylonGamepads.length == 0) {
  37250. this._stopMonitoringGamepads();
  37251. }
  37252. };
  37253. Gamepads.prototype._startMonitoringGamepads = function () {
  37254. if (!this.isMonitoring) {
  37255. this.isMonitoring = true;
  37256. this._checkGamepadsStatus();
  37257. }
  37258. };
  37259. Gamepads.prototype._stopMonitoringGamepads = function () {
  37260. this.isMonitoring = false;
  37261. };
  37262. Gamepads.prototype._checkGamepadsStatus = function () {
  37263. var _this = this;
  37264. // updating gamepad objects
  37265. this._updateGamepadObjects();
  37266. for (var i in this.babylonGamepads) {
  37267. this.babylonGamepads[i].update();
  37268. }
  37269. if (this.isMonitoring) {
  37270. if (window.requestAnimationFrame) {
  37271. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37272. }
  37273. else if (window.mozRequestAnimationFrame) {
  37274. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37275. }
  37276. else if (window.webkitRequestAnimationFrame) {
  37277. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37278. }
  37279. }
  37280. };
  37281. // This function is called only on Chrome, which does not yet support
  37282. // connection/disconnection events, but requires you to monitor
  37283. // an array for changes.
  37284. Gamepads.prototype._updateGamepadObjects = function () {
  37285. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  37286. for (var i = 0; i < gamepads.length; i++) {
  37287. if (gamepads[i]) {
  37288. if (!(gamepads[i].index in this.babylonGamepads)) {
  37289. var newGamepad = this._addNewGamepad(gamepads[i]);
  37290. if (this._callbackGamepadConnected) {
  37291. this._callbackGamepadConnected(newGamepad);
  37292. }
  37293. }
  37294. else {
  37295. this.babylonGamepads[i].browserGamepad = gamepads[i];
  37296. }
  37297. }
  37298. }
  37299. };
  37300. return Gamepads;
  37301. })();
  37302. BABYLON.Gamepads = Gamepads;
  37303. var StickValues = (function () {
  37304. function StickValues(x, y) {
  37305. this.x = x;
  37306. this.y = y;
  37307. }
  37308. return StickValues;
  37309. })();
  37310. BABYLON.StickValues = StickValues;
  37311. var Gamepad = (function () {
  37312. function Gamepad(id, index, browserGamepad) {
  37313. this.id = id;
  37314. this.index = index;
  37315. this.browserGamepad = browserGamepad;
  37316. if (this.browserGamepad.axes.length >= 2) {
  37317. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37318. }
  37319. if (this.browserGamepad.axes.length >= 4) {
  37320. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37321. }
  37322. }
  37323. Gamepad.prototype.onleftstickchanged = function (callback) {
  37324. this._onleftstickchanged = callback;
  37325. };
  37326. Gamepad.prototype.onrightstickchanged = function (callback) {
  37327. this._onrightstickchanged = callback;
  37328. };
  37329. Object.defineProperty(Gamepad.prototype, "leftStick", {
  37330. get: function () {
  37331. return this._leftStick;
  37332. },
  37333. set: function (newValues) {
  37334. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  37335. this._onleftstickchanged(newValues);
  37336. }
  37337. this._leftStick = newValues;
  37338. },
  37339. enumerable: true,
  37340. configurable: true
  37341. });
  37342. Object.defineProperty(Gamepad.prototype, "rightStick", {
  37343. get: function () {
  37344. return this._rightStick;
  37345. },
  37346. set: function (newValues) {
  37347. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  37348. this._onrightstickchanged(newValues);
  37349. }
  37350. this._rightStick = newValues;
  37351. },
  37352. enumerable: true,
  37353. configurable: true
  37354. });
  37355. Gamepad.prototype.update = function () {
  37356. if (this._leftStick) {
  37357. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37358. }
  37359. if (this._rightStick) {
  37360. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37361. }
  37362. };
  37363. return Gamepad;
  37364. })();
  37365. BABYLON.Gamepad = Gamepad;
  37366. var GenericPad = (function (_super) {
  37367. __extends(GenericPad, _super);
  37368. function GenericPad(id, index, gamepad) {
  37369. _super.call(this, id, index, gamepad);
  37370. this.id = id;
  37371. this.index = index;
  37372. this.gamepad = gamepad;
  37373. this._buttons = new Array(gamepad.buttons.length);
  37374. }
  37375. GenericPad.prototype.onbuttondown = function (callback) {
  37376. this._onbuttondown = callback;
  37377. };
  37378. GenericPad.prototype.onbuttonup = function (callback) {
  37379. this._onbuttonup = callback;
  37380. };
  37381. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  37382. if (newValue !== currentValue) {
  37383. if (this._onbuttondown && newValue === 1) {
  37384. this._onbuttondown(buttonIndex);
  37385. }
  37386. if (this._onbuttonup && newValue === 0) {
  37387. this._onbuttonup(buttonIndex);
  37388. }
  37389. }
  37390. return newValue;
  37391. };
  37392. GenericPad.prototype.update = function () {
  37393. _super.prototype.update.call(this);
  37394. for (var index = 0; index < this._buttons.length; index++) {
  37395. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  37396. }
  37397. };
  37398. return GenericPad;
  37399. })(Gamepad);
  37400. BABYLON.GenericPad = GenericPad;
  37401. (function (Xbox360Button) {
  37402. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  37403. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  37404. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  37405. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  37406. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  37407. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  37408. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  37409. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  37410. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  37411. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  37412. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  37413. var Xbox360Button = BABYLON.Xbox360Button;
  37414. (function (Xbox360Dpad) {
  37415. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  37416. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  37417. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  37418. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  37419. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  37420. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  37421. var Xbox360Pad = (function (_super) {
  37422. __extends(Xbox360Pad, _super);
  37423. function Xbox360Pad() {
  37424. _super.apply(this, arguments);
  37425. this._leftTrigger = 0;
  37426. this._rightTrigger = 0;
  37427. this._buttonA = 0;
  37428. this._buttonB = 0;
  37429. this._buttonX = 0;
  37430. this._buttonY = 0;
  37431. this._buttonBack = 0;
  37432. this._buttonStart = 0;
  37433. this._buttonLB = 0;
  37434. this._buttonRB = 0;
  37435. this._buttonLeftStick = 0;
  37436. this._buttonRightStick = 0;
  37437. this._dPadUp = 0;
  37438. this._dPadDown = 0;
  37439. this._dPadLeft = 0;
  37440. this._dPadRight = 0;
  37441. }
  37442. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  37443. this._onlefttriggerchanged = callback;
  37444. };
  37445. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  37446. this._onrighttriggerchanged = callback;
  37447. };
  37448. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  37449. get: function () {
  37450. return this._leftTrigger;
  37451. },
  37452. set: function (newValue) {
  37453. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  37454. this._onlefttriggerchanged(newValue);
  37455. }
  37456. this._leftTrigger = newValue;
  37457. },
  37458. enumerable: true,
  37459. configurable: true
  37460. });
  37461. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  37462. get: function () {
  37463. return this._rightTrigger;
  37464. },
  37465. set: function (newValue) {
  37466. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  37467. this._onrighttriggerchanged(newValue);
  37468. }
  37469. this._rightTrigger = newValue;
  37470. },
  37471. enumerable: true,
  37472. configurable: true
  37473. });
  37474. Xbox360Pad.prototype.onbuttondown = function (callback) {
  37475. this._onbuttondown = callback;
  37476. };
  37477. Xbox360Pad.prototype.onbuttonup = function (callback) {
  37478. this._onbuttonup = callback;
  37479. };
  37480. Xbox360Pad.prototype.ondpaddown = function (callback) {
  37481. this._ondpaddown = callback;
  37482. };
  37483. Xbox360Pad.prototype.ondpadup = function (callback) {
  37484. this._ondpadup = callback;
  37485. };
  37486. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  37487. if (newValue !== currentValue) {
  37488. if (this._onbuttondown && newValue === 1) {
  37489. this._onbuttondown(buttonType);
  37490. }
  37491. if (this._onbuttonup && newValue === 0) {
  37492. this._onbuttonup(buttonType);
  37493. }
  37494. }
  37495. return newValue;
  37496. };
  37497. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  37498. if (newValue !== currentValue) {
  37499. if (this._ondpaddown && newValue === 1) {
  37500. this._ondpaddown(buttonType);
  37501. }
  37502. if (this._ondpadup && newValue === 0) {
  37503. this._ondpadup(buttonType);
  37504. }
  37505. }
  37506. return newValue;
  37507. };
  37508. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  37509. get: function () {
  37510. return this._buttonA;
  37511. },
  37512. set: function (value) {
  37513. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  37514. },
  37515. enumerable: true,
  37516. configurable: true
  37517. });
  37518. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  37519. get: function () {
  37520. return this._buttonB;
  37521. },
  37522. set: function (value) {
  37523. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  37524. },
  37525. enumerable: true,
  37526. configurable: true
  37527. });
  37528. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  37529. get: function () {
  37530. return this._buttonX;
  37531. },
  37532. set: function (value) {
  37533. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  37534. },
  37535. enumerable: true,
  37536. configurable: true
  37537. });
  37538. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  37539. get: function () {
  37540. return this._buttonY;
  37541. },
  37542. set: function (value) {
  37543. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  37544. },
  37545. enumerable: true,
  37546. configurable: true
  37547. });
  37548. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  37549. get: function () {
  37550. return this._buttonStart;
  37551. },
  37552. set: function (value) {
  37553. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  37554. },
  37555. enumerable: true,
  37556. configurable: true
  37557. });
  37558. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  37559. get: function () {
  37560. return this._buttonBack;
  37561. },
  37562. set: function (value) {
  37563. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  37564. },
  37565. enumerable: true,
  37566. configurable: true
  37567. });
  37568. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  37569. get: function () {
  37570. return this._buttonLB;
  37571. },
  37572. set: function (value) {
  37573. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  37574. },
  37575. enumerable: true,
  37576. configurable: true
  37577. });
  37578. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  37579. get: function () {
  37580. return this._buttonRB;
  37581. },
  37582. set: function (value) {
  37583. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  37584. },
  37585. enumerable: true,
  37586. configurable: true
  37587. });
  37588. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  37589. get: function () {
  37590. return this._buttonLeftStick;
  37591. },
  37592. set: function (value) {
  37593. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  37594. },
  37595. enumerable: true,
  37596. configurable: true
  37597. });
  37598. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  37599. get: function () {
  37600. return this._buttonRightStick;
  37601. },
  37602. set: function (value) {
  37603. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  37604. },
  37605. enumerable: true,
  37606. configurable: true
  37607. });
  37608. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  37609. get: function () {
  37610. return this._dPadUp;
  37611. },
  37612. set: function (value) {
  37613. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  37614. },
  37615. enumerable: true,
  37616. configurable: true
  37617. });
  37618. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  37619. get: function () {
  37620. return this._dPadDown;
  37621. },
  37622. set: function (value) {
  37623. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  37624. },
  37625. enumerable: true,
  37626. configurable: true
  37627. });
  37628. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  37629. get: function () {
  37630. return this._dPadLeft;
  37631. },
  37632. set: function (value) {
  37633. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  37634. },
  37635. enumerable: true,
  37636. configurable: true
  37637. });
  37638. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  37639. get: function () {
  37640. return this._dPadRight;
  37641. },
  37642. set: function (value) {
  37643. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  37644. },
  37645. enumerable: true,
  37646. configurable: true
  37647. });
  37648. Xbox360Pad.prototype.update = function () {
  37649. _super.prototype.update.call(this);
  37650. this.buttonA = this.browserGamepad.buttons[0].value;
  37651. this.buttonB = this.browserGamepad.buttons[1].value;
  37652. this.buttonX = this.browserGamepad.buttons[2].value;
  37653. this.buttonY = this.browserGamepad.buttons[3].value;
  37654. this.buttonLB = this.browserGamepad.buttons[4].value;
  37655. this.buttonRB = this.browserGamepad.buttons[5].value;
  37656. this.leftTrigger = this.browserGamepad.buttons[6].value;
  37657. this.rightTrigger = this.browserGamepad.buttons[7].value;
  37658. this.buttonBack = this.browserGamepad.buttons[8].value;
  37659. this.buttonStart = this.browserGamepad.buttons[9].value;
  37660. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  37661. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  37662. this.dPadUp = this.browserGamepad.buttons[12].value;
  37663. this.dPadDown = this.browserGamepad.buttons[13].value;
  37664. this.dPadLeft = this.browserGamepad.buttons[14].value;
  37665. this.dPadRight = this.browserGamepad.buttons[15].value;
  37666. };
  37667. return Xbox360Pad;
  37668. })(Gamepad);
  37669. BABYLON.Xbox360Pad = Xbox360Pad;
  37670. })(BABYLON || (BABYLON = {}));
  37671. var BABYLON;
  37672. (function (BABYLON) {
  37673. // We're mainly based on the logic defined into the FreeCamera code
  37674. var GamepadCamera = (function (_super) {
  37675. __extends(GamepadCamera, _super);
  37676. //-- end properties for backward compatibility for inputs
  37677. function GamepadCamera(name, position, scene) {
  37678. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  37679. _super.call(this, name, position, scene);
  37680. }
  37681. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  37682. //-- Begin properties for backward compatibility for inputs
  37683. get: function () {
  37684. var gamepad = this.inputs.attached["gamepad"];
  37685. if (gamepad)
  37686. return gamepad.gamepadAngularSensibility;
  37687. },
  37688. set: function (value) {
  37689. var gamepad = this.inputs.attached["gamepad"];
  37690. if (gamepad)
  37691. gamepad.gamepadAngularSensibility = value;
  37692. },
  37693. enumerable: true,
  37694. configurable: true
  37695. });
  37696. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  37697. get: function () {
  37698. var gamepad = this.inputs.attached["gamepad"];
  37699. if (gamepad)
  37700. return gamepad.gamepadMoveSensibility;
  37701. },
  37702. set: function (value) {
  37703. var gamepad = this.inputs.attached["gamepad"];
  37704. if (gamepad)
  37705. gamepad.gamepadMoveSensibility = value;
  37706. },
  37707. enumerable: true,
  37708. configurable: true
  37709. });
  37710. GamepadCamera.prototype.getTypeName = function () {
  37711. return "GamepadCamera";
  37712. };
  37713. return GamepadCamera;
  37714. })(BABYLON.UniversalCamera);
  37715. BABYLON.GamepadCamera = GamepadCamera;
  37716. })(BABYLON || (BABYLON = {}));
  37717. var BABYLON;
  37718. (function (BABYLON) {
  37719. var Analyser = (function () {
  37720. function Analyser(scene) {
  37721. this.SMOOTHING = 0.75;
  37722. this.FFT_SIZE = 512;
  37723. this.BARGRAPHAMPLITUDE = 256;
  37724. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  37725. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  37726. this._scene = scene;
  37727. this._audioEngine = BABYLON.Engine.audioEngine;
  37728. if (this._audioEngine.canUseWebAudio) {
  37729. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  37730. this._webAudioAnalyser.minDecibels = -140;
  37731. this._webAudioAnalyser.maxDecibels = 0;
  37732. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  37733. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  37734. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  37735. }
  37736. }
  37737. Analyser.prototype.getFrequencyBinCount = function () {
  37738. if (this._audioEngine.canUseWebAudio) {
  37739. return this._webAudioAnalyser.frequencyBinCount;
  37740. }
  37741. else {
  37742. return 0;
  37743. }
  37744. };
  37745. Analyser.prototype.getByteFrequencyData = function () {
  37746. if (this._audioEngine.canUseWebAudio) {
  37747. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  37748. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  37749. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  37750. }
  37751. return this._byteFreqs;
  37752. };
  37753. Analyser.prototype.getByteTimeDomainData = function () {
  37754. if (this._audioEngine.canUseWebAudio) {
  37755. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  37756. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  37757. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  37758. }
  37759. return this._byteTime;
  37760. };
  37761. Analyser.prototype.getFloatFrequencyData = function () {
  37762. if (this._audioEngine.canUseWebAudio) {
  37763. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  37764. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  37765. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  37766. }
  37767. return this._floatFreqs;
  37768. };
  37769. Analyser.prototype.drawDebugCanvas = function () {
  37770. var _this = this;
  37771. if (this._audioEngine.canUseWebAudio) {
  37772. if (!this._debugCanvas) {
  37773. this._debugCanvas = document.createElement("canvas");
  37774. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  37775. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  37776. this._debugCanvas.style.position = "absolute";
  37777. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  37778. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  37779. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  37780. document.body.appendChild(this._debugCanvas);
  37781. this._registerFunc = function () {
  37782. _this.drawDebugCanvas();
  37783. };
  37784. this._scene.registerBeforeRender(this._registerFunc);
  37785. }
  37786. if (this._registerFunc) {
  37787. var workingArray = this.getByteFrequencyData();
  37788. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  37789. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  37790. // Draw the frequency domain chart.
  37791. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  37792. var value = workingArray[i];
  37793. var percent = value / this.BARGRAPHAMPLITUDE;
  37794. var height = this.DEBUGCANVASSIZE.height * percent;
  37795. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  37796. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  37797. var hue = i / this.getFrequencyBinCount() * 360;
  37798. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  37799. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  37800. }
  37801. }
  37802. }
  37803. };
  37804. Analyser.prototype.stopDebugCanvas = function () {
  37805. if (this._debugCanvas) {
  37806. this._scene.unregisterBeforeRender(this._registerFunc);
  37807. this._registerFunc = null;
  37808. document.body.removeChild(this._debugCanvas);
  37809. this._debugCanvas = null;
  37810. this._debugCanvasContext = null;
  37811. }
  37812. };
  37813. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  37814. if (this._audioEngine.canUseWebAudio) {
  37815. inputAudioNode.connect(this._webAudioAnalyser);
  37816. this._webAudioAnalyser.connect(outputAudioNode);
  37817. }
  37818. };
  37819. Analyser.prototype.dispose = function () {
  37820. if (this._audioEngine.canUseWebAudio) {
  37821. this._webAudioAnalyser.disconnect();
  37822. }
  37823. };
  37824. return Analyser;
  37825. })();
  37826. BABYLON.Analyser = Analyser;
  37827. })(BABYLON || (BABYLON = {}));
  37828. var BABYLON;
  37829. (function (BABYLON) {
  37830. var DepthRenderer = (function () {
  37831. function DepthRenderer(scene, type) {
  37832. var _this = this;
  37833. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  37834. this._viewMatrix = BABYLON.Matrix.Zero();
  37835. this._projectionMatrix = BABYLON.Matrix.Zero();
  37836. this._transformMatrix = BABYLON.Matrix.Zero();
  37837. this._worldViewProjection = BABYLON.Matrix.Zero();
  37838. this._scene = scene;
  37839. var engine = scene.getEngine();
  37840. // Render target
  37841. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  37842. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37843. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37844. this._depthMap.refreshRate = 1;
  37845. this._depthMap.renderParticles = false;
  37846. this._depthMap.renderList = null;
  37847. // set default depth value to 1.0 (far away)
  37848. this._depthMap.onClear = function (engine) {
  37849. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  37850. };
  37851. // Custom render function
  37852. var renderSubMesh = function (subMesh) {
  37853. var mesh = subMesh.getRenderingMesh();
  37854. var scene = _this._scene;
  37855. var engine = scene.getEngine();
  37856. // Culling
  37857. engine.setState(subMesh.getMaterial().backFaceCulling);
  37858. // Managing instances
  37859. var batch = mesh._getInstancesRenderList(subMesh._id);
  37860. if (batch.mustReturn) {
  37861. return;
  37862. }
  37863. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  37864. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  37865. engine.enableEffect(_this._effect);
  37866. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  37867. var material = subMesh.getMaterial();
  37868. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  37869. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  37870. // Alpha test
  37871. if (material && material.needAlphaTesting()) {
  37872. var alphaTexture = material.getAlphaTestTexture();
  37873. _this._effect.setTexture("diffuseSampler", alphaTexture);
  37874. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37875. }
  37876. // Bones
  37877. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37878. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37879. }
  37880. // Draw
  37881. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  37882. }
  37883. };
  37884. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  37885. var index;
  37886. for (index = 0; index < opaqueSubMeshes.length; index++) {
  37887. renderSubMesh(opaqueSubMeshes.data[index]);
  37888. }
  37889. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  37890. renderSubMesh(alphaTestSubMeshes.data[index]);
  37891. }
  37892. };
  37893. }
  37894. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  37895. var defines = [];
  37896. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37897. var mesh = subMesh.getMesh();
  37898. var scene = mesh.getScene();
  37899. var material = subMesh.getMaterial();
  37900. // Alpha test
  37901. if (material && material.needAlphaTesting()) {
  37902. defines.push("#define ALPHATEST");
  37903. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37904. attribs.push(BABYLON.VertexBuffer.UVKind);
  37905. defines.push("#define UV1");
  37906. }
  37907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37908. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37909. defines.push("#define UV2");
  37910. }
  37911. }
  37912. // Bones
  37913. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37916. if (mesh.numBoneInfluencers > 4) {
  37917. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37918. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37919. }
  37920. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37921. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37922. }
  37923. else {
  37924. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37925. }
  37926. // Instances
  37927. if (useInstances) {
  37928. defines.push("#define INSTANCES");
  37929. attribs.push("world0");
  37930. attribs.push("world1");
  37931. attribs.push("world2");
  37932. attribs.push("world3");
  37933. }
  37934. // Get correct effect
  37935. var join = defines.join("\n");
  37936. if (this._cachedDefines !== join) {
  37937. this._cachedDefines = join;
  37938. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  37939. }
  37940. return this._effect.isReady();
  37941. };
  37942. DepthRenderer.prototype.getDepthMap = function () {
  37943. return this._depthMap;
  37944. };
  37945. // Methods
  37946. DepthRenderer.prototype.dispose = function () {
  37947. this._depthMap.dispose();
  37948. };
  37949. return DepthRenderer;
  37950. })();
  37951. BABYLON.DepthRenderer = DepthRenderer;
  37952. })(BABYLON || (BABYLON = {}));
  37953. var BABYLON;
  37954. (function (BABYLON) {
  37955. var SSAORenderingPipeline = (function (_super) {
  37956. __extends(SSAORenderingPipeline, _super);
  37957. /**
  37958. * @constructor
  37959. * @param {string} name - The rendering pipeline name
  37960. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  37961. * @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 }
  37962. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  37963. */
  37964. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  37965. var _this = this;
  37966. _super.call(this, scene.getEngine(), name);
  37967. // Members
  37968. /**
  37969. * The PassPostProcess id in the pipeline that contains the original scene color
  37970. * @type {string}
  37971. */
  37972. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  37973. /**
  37974. * The SSAO PostProcess id in the pipeline
  37975. * @type {string}
  37976. */
  37977. this.SSAORenderEffect = "SSAORenderEffect";
  37978. /**
  37979. * The horizontal blur PostProcess id in the pipeline
  37980. * @type {string}
  37981. */
  37982. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  37983. /**
  37984. * The vertical blur PostProcess id in the pipeline
  37985. * @type {string}
  37986. */
  37987. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  37988. /**
  37989. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  37990. * @type {string}
  37991. */
  37992. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  37993. /**
  37994. * The output strength of the SSAO post-process. Default value is 1.0.
  37995. * @type {number}
  37996. */
  37997. this.totalStrength = 1.0;
  37998. /**
  37999. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  38000. * @type {number}
  38001. */
  38002. this.radius = 0.0001;
  38003. /**
  38004. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  38005. * Must not be equal to fallOff and superior to fallOff.
  38006. * Default value is 0.975
  38007. * @type {number}
  38008. */
  38009. this.area = 0.0075;
  38010. /**
  38011. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  38012. * Must not be equal to area and inferior to area.
  38013. * Default value is 0.0
  38014. * @type {number}
  38015. */
  38016. this.fallOff = 0.000001;
  38017. /**
  38018. * The base color of the SSAO post-process
  38019. * The final result is "base + ssao" between [0, 1]
  38020. * @type {number}
  38021. */
  38022. this.base = 0.5;
  38023. this._firstUpdate = true;
  38024. this._scene = scene;
  38025. // Set up assets
  38026. this._createRandomTexture();
  38027. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  38028. var ssaoRatio = ratio.ssaoRatio || ratio;
  38029. var combineRatio = ratio.combineRatio || ratio;
  38030. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38031. this._createSSAOPostProcess(ssaoRatio);
  38032. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38033. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38034. this._createSSAOCombinePostProcess(combineRatio);
  38035. // Set up pipeline
  38036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  38037. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  38038. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  38039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  38040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  38041. // Finish
  38042. scene.postProcessRenderPipelineManager.addPipeline(this);
  38043. if (cameras)
  38044. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38045. }
  38046. // Public Methods
  38047. /**
  38048. * Returns the horizontal blur PostProcess
  38049. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  38050. */
  38051. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  38052. return this._blurHPostProcess;
  38053. };
  38054. /**
  38055. * Returns the vertical blur PostProcess
  38056. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  38057. */
  38058. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  38059. return this._blurVPostProcess;
  38060. };
  38061. /**
  38062. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  38063. */
  38064. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  38065. if (disableDepthRender === void 0) { disableDepthRender = false; }
  38066. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38067. this._originalColorPostProcess = undefined;
  38068. this._ssaoPostProcess = undefined;
  38069. this._blurHPostProcess = undefined;
  38070. this._blurVPostProcess = undefined;
  38071. this._ssaoCombinePostProcess = undefined;
  38072. this._randomTexture.dispose();
  38073. if (disableDepthRender)
  38074. this._scene.disableDepthRenderer();
  38075. };
  38076. // Private Methods
  38077. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  38078. var _this = this;
  38079. var numSamples = 16;
  38080. var sampleSphere = [
  38081. 0.5381, 0.1856, -0.4319,
  38082. 0.1379, 0.2486, 0.4430,
  38083. 0.3371, 0.5679, -0.0057,
  38084. -0.6999, -0.0451, -0.0019,
  38085. 0.0689, -0.1598, -0.8547,
  38086. 0.0560, 0.0069, -0.1843,
  38087. -0.0146, 0.1402, 0.0762,
  38088. 0.0100, -0.1924, -0.0344,
  38089. -0.3577, -0.5301, -0.4358,
  38090. -0.3169, 0.1063, 0.0158,
  38091. 0.0103, -0.5869, 0.0046,
  38092. -0.0897, -0.4940, 0.3287,
  38093. 0.7119, -0.0154, -0.0918,
  38094. -0.0533, 0.0596, -0.5411,
  38095. 0.0352, -0.0631, 0.5460,
  38096. -0.4776, 0.2847, -0.0271
  38097. ];
  38098. var samplesFactor = 1.0 / numSamples;
  38099. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  38100. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  38101. "area", "fallOff", "base"
  38102. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  38103. this._ssaoPostProcess.onApply = function (effect) {
  38104. if (_this._firstUpdate) {
  38105. effect.setArray3("sampleSphere", sampleSphere);
  38106. effect.setFloat("samplesFactor", samplesFactor);
  38107. effect.setFloat("randTextureTiles", 4.0);
  38108. _this._firstUpdate = false;
  38109. }
  38110. effect.setFloat("totalStrength", _this.totalStrength);
  38111. effect.setFloat("radius", _this.radius);
  38112. effect.setFloat("area", _this.area);
  38113. effect.setFloat("fallOff", _this.fallOff);
  38114. effect.setFloat("base", _this.base);
  38115. effect.setTexture("textureSampler", _this._depthTexture);
  38116. effect.setTexture("randomSampler", _this._randomTexture);
  38117. };
  38118. };
  38119. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  38120. var _this = this;
  38121. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38122. this._ssaoCombinePostProcess.onApply = function (effect) {
  38123. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  38124. };
  38125. };
  38126. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  38127. var size = 512;
  38128. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38129. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  38130. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  38131. var context = this._randomTexture.getContext();
  38132. var rand = function (min, max) {
  38133. return Math.random() * (max - min) + min;
  38134. };
  38135. var randVector = BABYLON.Vector3.Zero();
  38136. for (var x = 0; x < size; x++) {
  38137. for (var y = 0; y < size; y++) {
  38138. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  38139. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  38140. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  38141. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  38142. context.fillRect(x, y, 1, 1);
  38143. }
  38144. }
  38145. this._randomTexture.update(false);
  38146. };
  38147. return SSAORenderingPipeline;
  38148. })(BABYLON.PostProcessRenderPipeline);
  38149. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  38150. })(BABYLON || (BABYLON = {}));
  38151. var BABYLON;
  38152. (function (BABYLON) {
  38153. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  38154. var VolumetricLightScatteringPostProcess = (function (_super) {
  38155. __extends(VolumetricLightScatteringPostProcess, _super);
  38156. /**
  38157. * @constructor
  38158. * @param {string} name - The post-process name
  38159. * @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)
  38160. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  38161. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  38162. * @param {number} samples - The post-process quality, default 100
  38163. * @param {number} samplingMode - The post-process filtering mode
  38164. * @param {BABYLON.Engine} engine - The babylon engine
  38165. * @param {boolean} reusable - If the post-process is reusable
  38166. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  38167. */
  38168. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  38169. var _this = this;
  38170. if (samples === void 0) { samples = 100; }
  38171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38172. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  38173. this._screenCoordinates = BABYLON.Vector2.Zero();
  38174. /**
  38175. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  38176. * @type {boolean}
  38177. */
  38178. this.useCustomMeshPosition = false;
  38179. /**
  38180. * If the post-process should inverse the light scattering direction
  38181. * @type {boolean}
  38182. */
  38183. this.invert = true;
  38184. /**
  38185. * Set to true to use the diffuseColor instead of the diffuseTexture
  38186. * @type {boolean}
  38187. */
  38188. this.useDiffuseColor = false;
  38189. /**
  38190. * Array containing the excluded meshes not rendered in the internal pass
  38191. */
  38192. this.excludedMeshes = new Array();
  38193. /**
  38194. * Controls the overall intensity of the post-process
  38195. * @type {number}
  38196. */
  38197. this.exposure = 0.3;
  38198. /**
  38199. * Dissipates each sample's contribution in range [0, 1]
  38200. * @type {number}
  38201. */
  38202. this.decay = 0.96815;
  38203. /**
  38204. * Controls the overall intensity of each sample
  38205. * @type {number}
  38206. */
  38207. this.weight = 0.58767;
  38208. /**
  38209. * Controls the density of each sample
  38210. * @type {number}
  38211. */
  38212. this.density = 0.926;
  38213. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  38214. var engine = scene.getEngine();
  38215. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  38216. // Configure mesh
  38217. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  38218. // Configure
  38219. this._createPass(scene, ratio.passRatio || ratio);
  38220. this.onActivate = function (camera) {
  38221. if (!_this.isSupported) {
  38222. _this.dispose(camera);
  38223. }
  38224. _this.onActivate = null;
  38225. };
  38226. this.onApply = function (effect) {
  38227. _this._updateMeshScreenCoordinates(scene);
  38228. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  38229. effect.setFloat("exposure", _this.exposure);
  38230. effect.setFloat("decay", _this.decay);
  38231. effect.setFloat("weight", _this.weight);
  38232. effect.setFloat("density", _this.density);
  38233. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  38234. };
  38235. }
  38236. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  38237. var mesh = subMesh.getMesh();
  38238. var defines = [];
  38239. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38240. var material = subMesh.getMaterial();
  38241. var needUV = false;
  38242. // Render this.mesh as default
  38243. if (mesh === this.mesh) {
  38244. if (this.useDiffuseColor) {
  38245. defines.push("#define DIFFUSE_COLOR_RENDER");
  38246. }
  38247. else if (material) {
  38248. if (material.diffuseTexture !== undefined) {
  38249. defines.push("#define BASIC_RENDER");
  38250. }
  38251. else {
  38252. defines.push("#define DIFFUSE_COLOR_RENDER");
  38253. }
  38254. }
  38255. defines.push("#define NEED_UV");
  38256. needUV = true;
  38257. }
  38258. // Alpha test
  38259. if (material) {
  38260. if (material.needAlphaTesting()) {
  38261. defines.push("#define ALPHATEST");
  38262. }
  38263. if (material.opacityTexture !== undefined) {
  38264. defines.push("#define OPACITY");
  38265. if (material.opacityTexture.getAlphaFromRGB) {
  38266. defines.push("#define OPACITYRGB");
  38267. }
  38268. if (!needUV) {
  38269. defines.push("#define NEED_UV");
  38270. }
  38271. }
  38272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38273. attribs.push(BABYLON.VertexBuffer.UVKind);
  38274. defines.push("#define UV1");
  38275. }
  38276. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38277. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38278. defines.push("#define UV2");
  38279. }
  38280. }
  38281. // Bones
  38282. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38285. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38286. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38287. }
  38288. else {
  38289. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38290. }
  38291. // Instances
  38292. if (useInstances) {
  38293. defines.push("#define INSTANCES");
  38294. attribs.push("world0");
  38295. attribs.push("world1");
  38296. attribs.push("world2");
  38297. attribs.push("world3");
  38298. }
  38299. // Get correct effect
  38300. var join = defines.join("\n");
  38301. if (this._cachedDefines !== join) {
  38302. this._cachedDefines = join;
  38303. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  38304. }
  38305. return this._volumetricLightScatteringPass.isReady();
  38306. };
  38307. /**
  38308. * Sets the new light position for light scattering effect
  38309. * @param {BABYLON.Vector3} The new custom light position
  38310. */
  38311. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  38312. this._customMeshPosition = position;
  38313. };
  38314. /**
  38315. * Returns the light position for light scattering effect
  38316. * @return {BABYLON.Vector3} The custom light position
  38317. */
  38318. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  38319. return this._customMeshPosition;
  38320. };
  38321. /**
  38322. * Disposes the internal assets and detaches the post-process from the camera
  38323. */
  38324. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  38325. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  38326. if (rttIndex !== -1) {
  38327. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  38328. }
  38329. this._volumetricLightScatteringRTT.dispose();
  38330. _super.prototype.dispose.call(this, camera);
  38331. };
  38332. /**
  38333. * Returns the render target texture used by the post-process
  38334. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  38335. */
  38336. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  38337. return this._volumetricLightScatteringRTT;
  38338. };
  38339. // Private methods
  38340. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  38341. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  38342. return true;
  38343. }
  38344. return false;
  38345. };
  38346. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  38347. var _this = this;
  38348. var engine = scene.getEngine();
  38349. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38350. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38351. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38352. this._volumetricLightScatteringRTT.renderList = null;
  38353. this._volumetricLightScatteringRTT.renderParticles = false;
  38354. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  38355. // Custom render function for submeshes
  38356. var renderSubMesh = function (subMesh) {
  38357. var mesh = subMesh.getRenderingMesh();
  38358. if (_this._meshExcluded(mesh)) {
  38359. return;
  38360. }
  38361. var scene = mesh.getScene();
  38362. var engine = scene.getEngine();
  38363. // Culling
  38364. engine.setState(subMesh.getMaterial().backFaceCulling);
  38365. // Managing instances
  38366. var batch = mesh._getInstancesRenderList(subMesh._id);
  38367. if (batch.mustReturn) {
  38368. return;
  38369. }
  38370. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  38371. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  38372. engine.enableEffect(_this._volumetricLightScatteringPass);
  38373. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  38374. var material = subMesh.getMaterial();
  38375. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  38376. // Alpha test
  38377. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  38378. var alphaTexture = material.getAlphaTestTexture();
  38379. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  38380. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  38381. }
  38382. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  38383. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  38384. if (alphaTexture) {
  38385. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38386. }
  38387. }
  38388. if (material.opacityTexture !== undefined) {
  38389. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  38390. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  38391. }
  38392. }
  38393. // Bones
  38394. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38395. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38396. }
  38397. // Draw
  38398. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  38399. }
  38400. };
  38401. // Render target texture callbacks
  38402. var savedSceneClearColor;
  38403. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  38404. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  38405. savedSceneClearColor = scene.clearColor;
  38406. scene.clearColor = sceneClearColor;
  38407. };
  38408. this._volumetricLightScatteringRTT.onAfterRender = function () {
  38409. scene.clearColor = savedSceneClearColor;
  38410. };
  38411. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38412. var engine = scene.getEngine();
  38413. var index;
  38414. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38415. renderSubMesh(opaqueSubMeshes.data[index]);
  38416. }
  38417. engine.setAlphaTesting(true);
  38418. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38419. renderSubMesh(alphaTestSubMeshes.data[index]);
  38420. }
  38421. engine.setAlphaTesting(false);
  38422. if (transparentSubMeshes.length) {
  38423. // Sort sub meshes
  38424. for (index = 0; index < transparentSubMeshes.length; index++) {
  38425. var submesh = transparentSubMeshes.data[index];
  38426. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  38427. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  38428. }
  38429. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  38430. sortedArray.sort(function (a, b) {
  38431. // Alpha index first
  38432. if (a._alphaIndex > b._alphaIndex) {
  38433. return 1;
  38434. }
  38435. if (a._alphaIndex < b._alphaIndex) {
  38436. return -1;
  38437. }
  38438. // Then distance to camera
  38439. if (a._distanceToCamera < b._distanceToCamera) {
  38440. return 1;
  38441. }
  38442. if (a._distanceToCamera > b._distanceToCamera) {
  38443. return -1;
  38444. }
  38445. return 0;
  38446. });
  38447. // Render sub meshes
  38448. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38449. for (index = 0; index < sortedArray.length; index++) {
  38450. renderSubMesh(sortedArray[index]);
  38451. }
  38452. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38453. }
  38454. };
  38455. };
  38456. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  38457. var transform = scene.getTransformMatrix();
  38458. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  38459. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  38460. this._screenCoordinates.x = pos.x / this._viewPort.width;
  38461. this._screenCoordinates.y = pos.y / this._viewPort.height;
  38462. if (this.invert)
  38463. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  38464. };
  38465. // Static methods
  38466. /**
  38467. * Creates a default mesh for the Volumeric Light Scattering post-process
  38468. * @param {string} The mesh name
  38469. * @param {BABYLON.Scene} The scene where to create the mesh
  38470. * @return {BABYLON.Mesh} the default mesh
  38471. */
  38472. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  38473. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  38474. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  38475. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  38476. return mesh;
  38477. };
  38478. return VolumetricLightScatteringPostProcess;
  38479. })(BABYLON.PostProcess);
  38480. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  38481. })(BABYLON || (BABYLON = {}));
  38482. // BABYLON.JS Chromatic Aberration GLSL Shader
  38483. // Author: Olivier Guyot
  38484. // Separates very slightly R, G and B colors on the edges of the screen
  38485. // Inspired by Francois Tarlier & Martins Upitis
  38486. var BABYLON;
  38487. (function (BABYLON) {
  38488. var LensRenderingPipeline = (function (_super) {
  38489. __extends(LensRenderingPipeline, _super);
  38490. /**
  38491. * @constructor
  38492. *
  38493. * Effect parameters are as follow:
  38494. * {
  38495. * chromatic_aberration: number; // from 0 to x (1 for realism)
  38496. * edge_blur: number; // from 0 to x (1 for realism)
  38497. * distortion: number; // from 0 to x (1 for realism)
  38498. * grain_amount: number; // from 0 to 1
  38499. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  38500. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  38501. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  38502. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  38503. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  38504. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  38505. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  38506. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  38507. * }
  38508. * Note: if an effect parameter is unset, effect is disabled
  38509. *
  38510. * @param {string} name - The rendering pipeline name
  38511. * @param {object} parameters - An object containing all parameters (see above)
  38512. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  38513. * @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)
  38514. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  38515. */
  38516. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  38517. var _this = this;
  38518. if (ratio === void 0) { ratio = 1.0; }
  38519. _super.call(this, scene.getEngine(), name);
  38520. // Lens effects can be of the following:
  38521. // - chromatic aberration (slight shift of RGB colors)
  38522. // - blur on the edge of the lens
  38523. // - lens distortion
  38524. // - depth-of-field blur & highlights enhancing
  38525. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  38526. // - grain effect (noise or custom texture)
  38527. // Two additional texture samplers are needed:
  38528. // - depth map (for depth-of-field)
  38529. // - grain texture
  38530. /**
  38531. * The chromatic aberration PostProcess id in the pipeline
  38532. * @type {string}
  38533. */
  38534. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  38535. /**
  38536. * The highlights enhancing PostProcess id in the pipeline
  38537. * @type {string}
  38538. */
  38539. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  38540. /**
  38541. * The depth-of-field PostProcess id in the pipeline
  38542. * @type {string}
  38543. */
  38544. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  38545. this._scene = scene;
  38546. // Fetch texture samplers
  38547. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  38548. if (parameters.grain_texture) {
  38549. this._grainTexture = parameters.grain_texture;
  38550. }
  38551. else {
  38552. this._createGrainTexture();
  38553. }
  38554. // save parameters
  38555. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  38556. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  38557. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  38558. this._distortion = parameters.distortion ? parameters.distortion : 0;
  38559. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  38560. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  38561. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  38562. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  38563. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  38564. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  38565. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  38566. // Create effects
  38567. this._createChromaticAberrationPostProcess(ratio);
  38568. this._createHighlightsPostProcess(ratio);
  38569. this._createDepthOfFieldPostProcess(ratio / 4);
  38570. // Set up pipeline
  38571. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  38572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  38573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  38574. if (this._highlightsGain === -1) {
  38575. this._disableEffect(this.HighlightsEnhancingEffect, null);
  38576. }
  38577. // Finish
  38578. scene.postProcessRenderPipelineManager.addPipeline(this);
  38579. if (cameras) {
  38580. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38581. }
  38582. }
  38583. // public methods (self explanatory)
  38584. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  38585. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  38586. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  38587. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  38588. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  38589. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  38590. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  38591. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  38592. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  38593. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  38594. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  38595. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  38596. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  38597. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  38598. };
  38599. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  38600. this._highlightsPostProcess.updateEffect();
  38601. };
  38602. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  38603. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  38604. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  38605. this._highlightsGain = amount;
  38606. };
  38607. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  38608. if (this._highlightsGain === -1) {
  38609. this._highlightsGain = 1.0;
  38610. }
  38611. this._highlightsThreshold = amount;
  38612. };
  38613. LensRenderingPipeline.prototype.disableHighlights = function () {
  38614. this._highlightsGain = -1;
  38615. };
  38616. /**
  38617. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  38618. */
  38619. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  38620. if (disableDepthRender === void 0) { disableDepthRender = false; }
  38621. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38622. this._chromaticAberrationPostProcess = undefined;
  38623. this._highlightsPostProcess = undefined;
  38624. this._depthOfFieldPostProcess = undefined;
  38625. this._grainTexture.dispose();
  38626. if (disableDepthRender)
  38627. this._scene.disableDepthRenderer();
  38628. };
  38629. // colors shifting and distortion
  38630. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  38631. var _this = this;
  38632. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  38633. [], // samplers
  38634. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38635. this._chromaticAberrationPostProcess.onApply = function (effect) {
  38636. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  38637. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38638. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38639. };
  38640. };
  38641. // highlights enhancing
  38642. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  38643. var _this = this;
  38644. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  38645. [], // samplers
  38646. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  38647. this._highlightsPostProcess.onApply = function (effect) {
  38648. effect.setFloat('gain', _this._highlightsGain);
  38649. effect.setFloat('threshold', _this._highlightsThreshold);
  38650. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  38651. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38652. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38653. };
  38654. };
  38655. // colors shifting and distortion
  38656. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  38657. var _this = this;
  38658. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  38659. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  38660. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  38661. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38662. this._depthOfFieldPostProcess.onApply = function (effect) {
  38663. effect.setTexture("depthSampler", _this._depthTexture);
  38664. effect.setTexture("grainSampler", _this._grainTexture);
  38665. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  38666. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  38667. effect.setFloat('grain_amount', _this._grainAmount);
  38668. effect.setBool('blur_noise', _this._blurNoise);
  38669. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38670. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38671. effect.setFloat('distortion', _this._distortion);
  38672. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  38673. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  38674. effect.setFloat('aperture', _this._dofAperture);
  38675. effect.setFloat('darken', _this._dofDarken);
  38676. effect.setFloat('edge_blur', _this._edgeBlur);
  38677. effect.setBool('highlights', (_this._highlightsGain !== -1));
  38678. effect.setFloat('near', _this._scene.activeCamera.minZ);
  38679. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  38680. };
  38681. };
  38682. // creates a black and white random noise texture, 512x512
  38683. LensRenderingPipeline.prototype._createGrainTexture = function () {
  38684. var size = 512;
  38685. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38686. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  38687. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  38688. var context = this._grainTexture.getContext();
  38689. var rand = function (min, max) {
  38690. return Math.random() * (max - min) + min;
  38691. };
  38692. var value;
  38693. for (var x = 0; x < size; x++) {
  38694. for (var y = 0; y < size; y++) {
  38695. value = Math.floor(rand(0.42, 0.58) * 255);
  38696. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  38697. context.fillRect(x, y, 1, 1);
  38698. }
  38699. }
  38700. this._grainTexture.update(false);
  38701. };
  38702. return LensRenderingPipeline;
  38703. })(BABYLON.PostProcessRenderPipeline);
  38704. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  38705. })(BABYLON || (BABYLON = {}));
  38706. //
  38707. // This post-process allows the modification of rendered colors by using
  38708. // a 'look-up table' (LUT). This effect is also called Color Grading.
  38709. //
  38710. // The object needs to be provided an url to a texture containing the color
  38711. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  38712. // Use an image editing software to tweak the LUT to match your needs.
  38713. //
  38714. // For an example of a color LUT, see here:
  38715. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  38716. // For explanations on color grading, see here:
  38717. // http://udn.epicgames.com/Three/ColorGrading.html
  38718. //
  38719. var BABYLON;
  38720. (function (BABYLON) {
  38721. var ColorCorrectionPostProcess = (function (_super) {
  38722. __extends(ColorCorrectionPostProcess, _super);
  38723. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  38724. var _this = this;
  38725. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  38726. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38727. this._colorTableTexture.anisotropicFilteringLevel = 1;
  38728. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38729. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38730. this.onApply = function (effect) {
  38731. effect.setTexture("colorTable", _this._colorTableTexture);
  38732. };
  38733. }
  38734. return ColorCorrectionPostProcess;
  38735. })(BABYLON.PostProcess);
  38736. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  38737. })(BABYLON || (BABYLON = {}));
  38738. var BABYLON;
  38739. (function (BABYLON) {
  38740. var AnaglyphFreeCamera = (function (_super) {
  38741. __extends(AnaglyphFreeCamera, _super);
  38742. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38743. _super.call(this, name, position, scene);
  38744. this.interaxialDistance = interaxialDistance;
  38745. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38746. }
  38747. AnaglyphFreeCamera.prototype.getTypeName = function () {
  38748. return "AnaglyphFreeCamera";
  38749. };
  38750. return AnaglyphFreeCamera;
  38751. })(BABYLON.FreeCamera);
  38752. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  38753. var AnaglyphArcRotateCamera = (function (_super) {
  38754. __extends(AnaglyphArcRotateCamera, _super);
  38755. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  38756. _super.call(this, name, alpha, beta, radius, target, scene);
  38757. this.interaxialDistance = interaxialDistance;
  38758. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38759. }
  38760. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  38761. return "AnaglyphArcRotateCamera";
  38762. };
  38763. return AnaglyphArcRotateCamera;
  38764. })(BABYLON.ArcRotateCamera);
  38765. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  38766. var AnaglyphGamepadCamera = (function (_super) {
  38767. __extends(AnaglyphGamepadCamera, _super);
  38768. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  38769. _super.call(this, name, position, scene);
  38770. this.interaxialDistance = interaxialDistance;
  38771. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38772. }
  38773. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  38774. return "AnaglyphGamepadCamera";
  38775. };
  38776. return AnaglyphGamepadCamera;
  38777. })(BABYLON.GamepadCamera);
  38778. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  38779. var AnaglyphUniversalCamera = (function (_super) {
  38780. __extends(AnaglyphUniversalCamera, _super);
  38781. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  38782. _super.call(this, name, position, scene);
  38783. this.interaxialDistance = interaxialDistance;
  38784. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38785. }
  38786. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  38787. return "AnaglyphUniversalCamera";
  38788. };
  38789. return AnaglyphUniversalCamera;
  38790. })(BABYLON.UniversalCamera);
  38791. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  38792. var StereoscopicFreeCamera = (function (_super) {
  38793. __extends(StereoscopicFreeCamera, _super);
  38794. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38795. _super.call(this, name, position, scene);
  38796. this.interaxialDistance = interaxialDistance;
  38797. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38798. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38799. }
  38800. StereoscopicFreeCamera.prototype.getTypeName = function () {
  38801. return "StereoscopicFreeCamera";
  38802. };
  38803. return StereoscopicFreeCamera;
  38804. })(BABYLON.FreeCamera);
  38805. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  38806. var StereoscopicArcRotateCamera = (function (_super) {
  38807. __extends(StereoscopicArcRotateCamera, _super);
  38808. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  38809. _super.call(this, name, alpha, beta, radius, target, scene);
  38810. this.interaxialDistance = interaxialDistance;
  38811. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38812. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38813. }
  38814. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  38815. return "StereoscopicArcRotateCamera";
  38816. };
  38817. return StereoscopicArcRotateCamera;
  38818. })(BABYLON.ArcRotateCamera);
  38819. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  38820. var StereoscopicGamepadCamera = (function (_super) {
  38821. __extends(StereoscopicGamepadCamera, _super);
  38822. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38823. _super.call(this, name, position, scene);
  38824. this.interaxialDistance = interaxialDistance;
  38825. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38826. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38827. }
  38828. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  38829. return "StereoscopicGamepadCamera";
  38830. };
  38831. return StereoscopicGamepadCamera;
  38832. })(BABYLON.GamepadCamera);
  38833. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  38834. var StereoscopicUniversalCamera = (function (_super) {
  38835. __extends(StereoscopicUniversalCamera, _super);
  38836. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38837. _super.call(this, name, position, scene);
  38838. this.interaxialDistance = interaxialDistance;
  38839. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38840. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38841. }
  38842. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  38843. return "StereoscopicUniversalCamera";
  38844. };
  38845. return StereoscopicUniversalCamera;
  38846. })(BABYLON.UniversalCamera);
  38847. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  38848. })(BABYLON || (BABYLON = {}));
  38849. var BABYLON;
  38850. (function (BABYLON) {
  38851. var HDRRenderingPipeline = (function (_super) {
  38852. __extends(HDRRenderingPipeline, _super);
  38853. /**
  38854. * @constructor
  38855. * @param {string} name - The rendering pipeline name
  38856. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  38857. * @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)
  38858. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  38859. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  38860. */
  38861. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  38862. var _this = this;
  38863. if (originalPostProcess === void 0) { originalPostProcess = null; }
  38864. _super.call(this, scene.getEngine(), name);
  38865. /**
  38866. * Public members
  38867. */
  38868. // Gaussian Blur
  38869. /**
  38870. * Gaussian blur coefficient
  38871. * @type {number}
  38872. */
  38873. this.gaussCoeff = 0.3;
  38874. /**
  38875. * Gaussian blur mean
  38876. * @type {number}
  38877. */
  38878. this.gaussMean = 1.0;
  38879. /**
  38880. * Gaussian blur standard deviation
  38881. * @type {number}
  38882. */
  38883. this.gaussStandDev = 0.8;
  38884. /**
  38885. * Gaussian blur multiplier. Multiplies the blur effect
  38886. * @type {number}
  38887. */
  38888. this.gaussMultiplier = 4.0;
  38889. // HDR
  38890. /**
  38891. * Exposure, controls the overall intensity of the pipeline
  38892. * @type {number}
  38893. */
  38894. this.exposure = 1.0;
  38895. /**
  38896. * Minimum luminance that the post-process can output. Luminance is >= 0
  38897. * @type {number}
  38898. */
  38899. this.minimumLuminance = 1.0;
  38900. /**
  38901. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  38902. * @type {number}
  38903. */
  38904. this.maximumLuminance = 1e20;
  38905. /**
  38906. * Increase rate for luminance: eye adaptation speed to dark
  38907. * @type {number}
  38908. */
  38909. this.luminanceIncreaserate = 0.5;
  38910. /**
  38911. * Decrease rate for luminance: eye adaptation speed to bright
  38912. * @type {number}
  38913. */
  38914. this.luminanceDecreaseRate = 0.5;
  38915. // Bright pass
  38916. /**
  38917. * Minimum luminance needed to compute HDR
  38918. * @type {number}
  38919. */
  38920. this.brightThreshold = 0.8;
  38921. this._needUpdate = true;
  38922. this._scene = scene;
  38923. // Bright pass
  38924. this._createBrightPassPostProcess(scene, ratio);
  38925. // Down sample X4
  38926. this._createDownSampleX4PostProcess(scene, ratio);
  38927. // Create gaussian blur post-processes
  38928. this._createGaussianBlurPostProcess(scene, ratio);
  38929. // Texture adder
  38930. this._createTextureAdderPostProcess(scene, ratio);
  38931. // Luminance generator
  38932. this._createLuminanceGeneratorPostProcess(scene);
  38933. // HDR
  38934. this._createHDRPostProcess(scene, ratio);
  38935. // Pass postprocess
  38936. if (originalPostProcess === null) {
  38937. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38938. }
  38939. else {
  38940. this._originalPostProcess = originalPostProcess;
  38941. }
  38942. // Configure pipeline
  38943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  38944. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  38945. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  38946. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  38947. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  38948. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  38949. var addDownSamplerPostProcess = function (id) {
  38950. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  38951. };
  38952. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  38953. addDownSamplerPostProcess(i);
  38954. }
  38955. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  38956. // Finish
  38957. scene.postProcessRenderPipelineManager.addPipeline(this);
  38958. if (cameras !== null) {
  38959. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38960. }
  38961. this.update();
  38962. }
  38963. /**
  38964. * Tells the pipeline to update its post-processes
  38965. */
  38966. HDRRenderingPipeline.prototype.update = function () {
  38967. this._needUpdate = true;
  38968. };
  38969. /**
  38970. * Returns the current calculated luminance
  38971. */
  38972. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  38973. return this._hdrCurrentLuminance;
  38974. };
  38975. /**
  38976. * Returns the currently drawn luminance
  38977. */
  38978. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  38979. return this._hdrOutputLuminance;
  38980. };
  38981. /**
  38982. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  38983. */
  38984. HDRRenderingPipeline.prototype.dispose = function () {
  38985. this._originalPostProcess = undefined;
  38986. this._brightPassPostProcess = undefined;
  38987. this._downSampleX4PostProcess = undefined;
  38988. this._guassianBlurHPostProcess = undefined;
  38989. this._guassianBlurVPostProcess = undefined;
  38990. this._textureAdderPostProcess = undefined;
  38991. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  38992. this._downSamplePostProcesses[i] = undefined;
  38993. }
  38994. this._hdrPostProcess = undefined;
  38995. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38996. };
  38997. /**
  38998. * Creates the HDR post-process and computes the luminance adaptation
  38999. */
  39000. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  39001. var _this = this;
  39002. var hdrLastLuminance = 0.0;
  39003. this._hdrOutputLuminance = -1.0;
  39004. this._hdrCurrentLuminance = 1.0;
  39005. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  39006. this._hdrPostProcess.onApply = function (effect) {
  39007. if (_this._hdrOutputLuminance < 0.0) {
  39008. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  39009. }
  39010. else {
  39011. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  39012. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  39013. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  39014. }
  39015. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  39016. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  39017. }
  39018. else {
  39019. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  39020. }
  39021. }
  39022. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  39023. hdrLastLuminance += scene.getEngine().getDeltaTime();
  39024. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  39025. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  39026. effect.setFloat("exposure", _this.exposure);
  39027. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  39028. _this._needUpdate = false;
  39029. };
  39030. };
  39031. /**
  39032. * Texture Adder post-process
  39033. */
  39034. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  39035. var _this = this;
  39036. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  39037. this._textureAdderPostProcess.onApply = function (effect) {
  39038. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  39039. };
  39040. };
  39041. /**
  39042. * Down sample X4 post-process
  39043. */
  39044. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  39045. var _this = this;
  39046. var downSampleX4Offsets = new Array(32);
  39047. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  39048. this._downSampleX4PostProcess.onApply = function (effect) {
  39049. if (_this._needUpdate) {
  39050. var id = 0;
  39051. for (var i = -2; i < 2; i++) {
  39052. for (var j = -2; j < 2; j++) {
  39053. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  39054. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  39055. id += 2;
  39056. }
  39057. }
  39058. }
  39059. effect.setArray2("dsOffsets", downSampleX4Offsets);
  39060. };
  39061. };
  39062. /**
  39063. * Bright pass post-process
  39064. */
  39065. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  39066. var _this = this;
  39067. var brightOffsets = new Array(8);
  39068. var brightPassCallback = function (effect) {
  39069. if (_this._needUpdate) {
  39070. var sU = (1.0 / _this._brightPassPostProcess.width);
  39071. var sV = (1.0 / _this._brightPassPostProcess.height);
  39072. brightOffsets[0] = -0.5 * sU;
  39073. brightOffsets[1] = 0.5 * sV;
  39074. brightOffsets[2] = 0.5 * sU;
  39075. brightOffsets[3] = 0.5 * sV;
  39076. brightOffsets[4] = -0.5 * sU;
  39077. brightOffsets[5] = -0.5 * sV;
  39078. brightOffsets[6] = 0.5 * sU;
  39079. brightOffsets[7] = -0.5 * sV;
  39080. }
  39081. effect.setArray2("dsOffsets", brightOffsets);
  39082. effect.setFloat("brightThreshold", _this.brightThreshold);
  39083. };
  39084. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  39085. this._brightPassPostProcess.onApply = brightPassCallback;
  39086. };
  39087. /**
  39088. * Luminance generator. Creates the luminance post-process and down sample post-processes
  39089. */
  39090. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  39091. var _this = this;
  39092. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  39093. var luminanceOffsets = new Array(8);
  39094. var downSampleOffsets = new Array(18);
  39095. var halfDestPixelSize;
  39096. this._downSamplePostProcesses = new Array(lumSteps);
  39097. // Utils for luminance
  39098. var luminanceUpdateSourceOffsets = function (width, height) {
  39099. var sU = (1.0 / width);
  39100. var sV = (1.0 / height);
  39101. luminanceOffsets[0] = -0.5 * sU;
  39102. luminanceOffsets[1] = 0.5 * sV;
  39103. luminanceOffsets[2] = 0.5 * sU;
  39104. luminanceOffsets[3] = 0.5 * sV;
  39105. luminanceOffsets[4] = -0.5 * sU;
  39106. luminanceOffsets[5] = -0.5 * sV;
  39107. luminanceOffsets[6] = 0.5 * sU;
  39108. luminanceOffsets[7] = -0.5 * sV;
  39109. };
  39110. var luminanceUpdateDestOffsets = function (width, height) {
  39111. var id = 0;
  39112. for (var x = -1; x < 2; x++) {
  39113. for (var y = -1; y < 2; y++) {
  39114. downSampleOffsets[id] = (x) / width;
  39115. downSampleOffsets[id + 1] = (y) / height;
  39116. id += 2;
  39117. }
  39118. }
  39119. };
  39120. // Luminance callback
  39121. var luminanceCallback = function (effect) {
  39122. if (_this._needUpdate) {
  39123. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  39124. }
  39125. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  39126. effect.setArray2("lumOffsets", luminanceOffsets);
  39127. };
  39128. // Down sample callbacks
  39129. var downSampleCallback = function (indice) {
  39130. var i = indice;
  39131. return function (effect) {
  39132. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  39133. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  39134. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  39135. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  39136. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  39137. effect.setArray2("dsOffsets", downSampleOffsets);
  39138. };
  39139. };
  39140. var downSampleAfterRenderCallback = function (effect) {
  39141. // Unpack result
  39142. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  39143. 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);
  39144. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  39145. };
  39146. // Create luminance post-process
  39147. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  39148. 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);
  39149. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  39150. // Create down sample post-processes
  39151. for (var i = lumSteps - 2; i >= 0; i--) {
  39152. var length = Math.pow(3, i);
  39153. ratio = { width: length, height: length };
  39154. var defines = "#define DOWN_SAMPLE\n";
  39155. if (i === 0) {
  39156. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  39157. }
  39158. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  39159. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  39160. if (i === 0) {
  39161. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  39162. }
  39163. }
  39164. };
  39165. /**
  39166. * Gaussian blur post-processes. Horizontal and Vertical
  39167. */
  39168. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  39169. var _this = this;
  39170. var blurOffsetsW = new Array(9);
  39171. var blurOffsetsH = new Array(9);
  39172. var blurWeights = new Array(9);
  39173. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  39174. // Utils for gaussian blur
  39175. var calculateBlurOffsets = function (height) {
  39176. var lastOutputDimensions = {
  39177. width: scene.getEngine().getRenderWidth(),
  39178. height: scene.getEngine().getRenderHeight()
  39179. };
  39180. for (var i = 0; i < 9; i++) {
  39181. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  39182. if (height) {
  39183. blurOffsetsH[i] = value;
  39184. }
  39185. else {
  39186. blurOffsetsW[i] = value;
  39187. }
  39188. }
  39189. };
  39190. var calculateWeights = function () {
  39191. var x = 0.0;
  39192. for (var i = 0; i < 9; i++) {
  39193. x = (i - 4.0) / 4.0;
  39194. 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));
  39195. }
  39196. };
  39197. // Callback
  39198. var gaussianBlurCallback = function (height) {
  39199. return function (effect) {
  39200. if (_this._needUpdate) {
  39201. calculateWeights();
  39202. calculateBlurOffsets(height);
  39203. }
  39204. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  39205. effect.setArray("blurWeights", blurWeights);
  39206. effect.setFloat("multiplier", _this.gaussMultiplier);
  39207. };
  39208. };
  39209. // Create horizontal gaussian blur post-processes
  39210. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  39211. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  39212. // Create vertical gaussian blur post-process
  39213. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  39214. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  39215. };
  39216. // Luminance generator
  39217. HDRRenderingPipeline.LUM_STEPS = 6;
  39218. return HDRRenderingPipeline;
  39219. })(BABYLON.PostProcessRenderPipeline);
  39220. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  39221. })(BABYLON || (BABYLON = {}));
  39222. var BABYLON;
  39223. (function (BABYLON) {
  39224. var FaceAdjacencies = (function () {
  39225. function FaceAdjacencies() {
  39226. this.edges = new Array();
  39227. this.edgesConnectedCount = 0;
  39228. }
  39229. return FaceAdjacencies;
  39230. })();
  39231. var EdgesRenderer = (function () {
  39232. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  39233. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  39234. if (epsilon === void 0) { epsilon = 0.95; }
  39235. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  39236. this.edgesWidthScalerForOrthographic = 1000.0;
  39237. this.edgesWidthScalerForPerspective = 50.0;
  39238. this._linesPositions = new Array();
  39239. this._linesNormals = new Array();
  39240. this._linesIndices = new Array();
  39241. this._buffers = new Array();
  39242. this._checkVerticesInsteadOfIndices = false;
  39243. this._source = source;
  39244. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  39245. this._epsilon = epsilon;
  39246. this._prepareRessources();
  39247. this._generateEdgesLines();
  39248. }
  39249. EdgesRenderer.prototype._prepareRessources = function () {
  39250. if (this._lineShader) {
  39251. return;
  39252. }
  39253. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  39254. attributes: ["position", "normal"],
  39255. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  39256. });
  39257. this._lineShader.disableDepthWrite = true;
  39258. this._lineShader.backFaceCulling = false;
  39259. };
  39260. EdgesRenderer.prototype.dispose = function () {
  39261. this._vb0.dispose();
  39262. this._vb1.dispose();
  39263. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  39264. this._lineShader.dispose();
  39265. };
  39266. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  39267. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  39268. return 0;
  39269. }
  39270. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  39271. return 1;
  39272. }
  39273. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  39274. return 2;
  39275. }
  39276. return -1;
  39277. };
  39278. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  39279. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  39280. return 0;
  39281. }
  39282. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  39283. return 1;
  39284. }
  39285. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  39286. return 2;
  39287. }
  39288. return -1;
  39289. };
  39290. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  39291. var needToCreateLine;
  39292. if (edge === undefined) {
  39293. needToCreateLine = true;
  39294. }
  39295. else {
  39296. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  39297. needToCreateLine = dotProduct < this._epsilon;
  39298. }
  39299. if (needToCreateLine) {
  39300. var offset = this._linesPositions.length / 3;
  39301. var normal = p0.subtract(p1);
  39302. normal.normalize();
  39303. // Positions
  39304. this._linesPositions.push(p0.x);
  39305. this._linesPositions.push(p0.y);
  39306. this._linesPositions.push(p0.z);
  39307. this._linesPositions.push(p0.x);
  39308. this._linesPositions.push(p0.y);
  39309. this._linesPositions.push(p0.z);
  39310. this._linesPositions.push(p1.x);
  39311. this._linesPositions.push(p1.y);
  39312. this._linesPositions.push(p1.z);
  39313. this._linesPositions.push(p1.x);
  39314. this._linesPositions.push(p1.y);
  39315. this._linesPositions.push(p1.z);
  39316. // Normals
  39317. this._linesNormals.push(p1.x);
  39318. this._linesNormals.push(p1.y);
  39319. this._linesNormals.push(p1.z);
  39320. this._linesNormals.push(-1);
  39321. this._linesNormals.push(p1.x);
  39322. this._linesNormals.push(p1.y);
  39323. this._linesNormals.push(p1.z);
  39324. this._linesNormals.push(1);
  39325. this._linesNormals.push(p0.x);
  39326. this._linesNormals.push(p0.y);
  39327. this._linesNormals.push(p0.z);
  39328. this._linesNormals.push(-1);
  39329. this._linesNormals.push(p0.x);
  39330. this._linesNormals.push(p0.y);
  39331. this._linesNormals.push(p0.z);
  39332. this._linesNormals.push(1);
  39333. // Indices
  39334. this._linesIndices.push(offset);
  39335. this._linesIndices.push(offset + 1);
  39336. this._linesIndices.push(offset + 2);
  39337. this._linesIndices.push(offset);
  39338. this._linesIndices.push(offset + 2);
  39339. this._linesIndices.push(offset + 3);
  39340. }
  39341. };
  39342. EdgesRenderer.prototype._generateEdgesLines = function () {
  39343. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39344. var indices = this._source.getIndices();
  39345. // First let's find adjacencies
  39346. var adjacencies = new Array();
  39347. var faceNormals = new Array();
  39348. var index;
  39349. var faceAdjacencies;
  39350. // Prepare faces
  39351. for (index = 0; index < indices.length; index += 3) {
  39352. faceAdjacencies = new FaceAdjacencies();
  39353. var p0Index = indices[index];
  39354. var p1Index = indices[index + 1];
  39355. var p2Index = indices[index + 2];
  39356. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  39357. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  39358. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  39359. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  39360. faceNormal.normalize();
  39361. faceNormals.push(faceNormal);
  39362. adjacencies.push(faceAdjacencies);
  39363. }
  39364. // Scan
  39365. for (index = 0; index < adjacencies.length; index++) {
  39366. faceAdjacencies = adjacencies[index];
  39367. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  39368. var otherFaceAdjacencies = adjacencies[otherIndex];
  39369. if (faceAdjacencies.edgesConnectedCount === 3) {
  39370. break;
  39371. }
  39372. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  39373. continue;
  39374. }
  39375. var otherP0 = indices[otherIndex * 3];
  39376. var otherP1 = indices[otherIndex * 3 + 1];
  39377. var otherP2 = indices[otherIndex * 3 + 2];
  39378. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  39379. var otherEdgeIndex;
  39380. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  39381. continue;
  39382. }
  39383. switch (edgeIndex) {
  39384. case 0:
  39385. if (this._checkVerticesInsteadOfIndices) {
  39386. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39387. }
  39388. else {
  39389. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  39390. }
  39391. break;
  39392. case 1:
  39393. if (this._checkVerticesInsteadOfIndices) {
  39394. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39395. }
  39396. else {
  39397. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  39398. }
  39399. break;
  39400. case 2:
  39401. if (this._checkVerticesInsteadOfIndices) {
  39402. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39403. }
  39404. else {
  39405. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  39406. }
  39407. break;
  39408. }
  39409. if (otherEdgeIndex === -1) {
  39410. continue;
  39411. }
  39412. faceAdjacencies.edges[edgeIndex] = otherIndex;
  39413. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  39414. faceAdjacencies.edgesConnectedCount++;
  39415. otherFaceAdjacencies.edgesConnectedCount++;
  39416. if (faceAdjacencies.edgesConnectedCount === 3) {
  39417. break;
  39418. }
  39419. }
  39420. }
  39421. }
  39422. // Create lines
  39423. for (index = 0; index < adjacencies.length; index++) {
  39424. // 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
  39425. var current = adjacencies[index];
  39426. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  39427. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  39428. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  39429. }
  39430. // Merge into a single mesh
  39431. var engine = this._source.getScene().getEngine();
  39432. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  39433. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  39434. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  39435. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  39436. this._ib = engine.createIndexBuffer(this._linesIndices);
  39437. this._indicesCount = this._linesIndices.length;
  39438. };
  39439. EdgesRenderer.prototype.render = function () {
  39440. if (!this._lineShader.isReady()) {
  39441. return;
  39442. }
  39443. var scene = this._source.getScene();
  39444. var engine = scene.getEngine();
  39445. this._lineShader._preBind();
  39446. // VBOs
  39447. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  39448. scene.resetCachedMaterial();
  39449. this._lineShader.setColor4("color", this._source.edgesColor);
  39450. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  39451. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  39452. }
  39453. else {
  39454. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  39455. }
  39456. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  39457. this._lineShader.bind(this._source.getWorldMatrix());
  39458. // Draw order
  39459. engine.draw(true, 0, this._indicesCount);
  39460. this._lineShader.unbind();
  39461. engine.setDepthWrite(true);
  39462. };
  39463. return EdgesRenderer;
  39464. })();
  39465. BABYLON.EdgesRenderer = EdgesRenderer;
  39466. })(BABYLON || (BABYLON = {}));
  39467. var BABYLON;
  39468. (function (BABYLON) {
  39469. (function (TonemappingOperator) {
  39470. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  39471. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  39472. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  39473. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  39474. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  39475. var TonemappingOperator = BABYLON.TonemappingOperator;
  39476. ;
  39477. var TonemapPostProcess = (function (_super) {
  39478. __extends(TonemapPostProcess, _super);
  39479. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  39480. var _this = this;
  39481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39482. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39483. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  39484. this._operator = _operator;
  39485. this.exposureAdjustment = exposureAdjustment;
  39486. var defines = "#define ";
  39487. if (this._operator === TonemappingOperator.Hable)
  39488. defines += "HABLE_TONEMAPPING";
  39489. else if (this._operator === TonemappingOperator.Reinhard)
  39490. defines += "REINHARD_TONEMAPPING";
  39491. else if (this._operator === TonemappingOperator.HejiDawson)
  39492. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  39493. else if (this._operator === TonemappingOperator.Photographic)
  39494. defines += "PHOTOGRAPHIC_TONEMAPPING";
  39495. //sadly a second call to create the effect.
  39496. this.updateEffect(defines);
  39497. this.onApply = function (effect) {
  39498. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  39499. };
  39500. }
  39501. return TonemapPostProcess;
  39502. })(BABYLON.PostProcess);
  39503. BABYLON.TonemapPostProcess = TonemapPostProcess;
  39504. })(BABYLON || (BABYLON = {}));
  39505. var BABYLON;
  39506. (function (BABYLON) {
  39507. var ReflectionProbe = (function () {
  39508. function ReflectionProbe(name, size, scene, generateMipMaps) {
  39509. var _this = this;
  39510. if (generateMipMaps === void 0) { generateMipMaps = true; }
  39511. this.name = name;
  39512. this._viewMatrix = BABYLON.Matrix.Identity();
  39513. this._target = BABYLON.Vector3.Zero();
  39514. this._add = BABYLON.Vector3.Zero();
  39515. this.position = BABYLON.Vector3.Zero();
  39516. this._scene = scene;
  39517. this._scene.reflectionProbes.push(this);
  39518. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  39519. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  39520. switch (faceIndex) {
  39521. case 0:
  39522. _this._add.copyFromFloats(1, 0, 0);
  39523. break;
  39524. case 1:
  39525. _this._add.copyFromFloats(-1, 0, 0);
  39526. break;
  39527. case 2:
  39528. _this._add.copyFromFloats(0, -1, 0);
  39529. break;
  39530. case 3:
  39531. _this._add.copyFromFloats(0, 1, 0);
  39532. break;
  39533. case 4:
  39534. _this._add.copyFromFloats(0, 0, 1);
  39535. break;
  39536. case 5:
  39537. _this._add.copyFromFloats(0, 0, -1);
  39538. break;
  39539. }
  39540. if (_this._attachedMesh) {
  39541. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  39542. }
  39543. _this.position.addToRef(_this._add, _this._target);
  39544. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  39545. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  39546. };
  39547. this._renderTargetTexture.onAfterUnbind = function () {
  39548. scene.updateTransformMatrix(true);
  39549. };
  39550. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  39551. }
  39552. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  39553. get: function () {
  39554. return this._renderTargetTexture.refreshRate;
  39555. },
  39556. set: function (value) {
  39557. this._renderTargetTexture.refreshRate = value;
  39558. },
  39559. enumerable: true,
  39560. configurable: true
  39561. });
  39562. ReflectionProbe.prototype.getScene = function () {
  39563. return this._scene;
  39564. };
  39565. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  39566. get: function () {
  39567. return this._renderTargetTexture;
  39568. },
  39569. enumerable: true,
  39570. configurable: true
  39571. });
  39572. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  39573. get: function () {
  39574. return this._renderTargetTexture.renderList;
  39575. },
  39576. enumerable: true,
  39577. configurable: true
  39578. });
  39579. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  39580. this._attachedMesh = mesh;
  39581. };
  39582. ReflectionProbe.prototype.dispose = function () {
  39583. var index = this._scene.reflectionProbes.indexOf(this);
  39584. if (index !== -1) {
  39585. // Remove from the scene if found
  39586. this._scene.reflectionProbes.splice(index, 1);
  39587. }
  39588. if (this._renderTargetTexture) {
  39589. this._renderTargetTexture.dispose();
  39590. this._renderTargetTexture = null;
  39591. }
  39592. };
  39593. return ReflectionProbe;
  39594. })();
  39595. BABYLON.ReflectionProbe = ReflectionProbe;
  39596. })(BABYLON || (BABYLON = {}));
  39597. var BABYLON;
  39598. (function (BABYLON) {
  39599. var SolidParticle = (function () {
  39600. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  39601. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  39602. this.position = BABYLON.Vector3.Zero(); // position
  39603. this.rotation = BABYLON.Vector3.Zero(); // rotation
  39604. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  39605. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  39606. this.velocity = BABYLON.Vector3.Zero(); // velocity
  39607. this.alive = true; // alive
  39608. this.idx = particleIndex;
  39609. this._pos = positionIndex;
  39610. this._model = model;
  39611. this.shapeId = shapeId;
  39612. this.idxInShape = idxInShape;
  39613. }
  39614. return SolidParticle;
  39615. })();
  39616. BABYLON.SolidParticle = SolidParticle;
  39617. var ModelShape = (function () {
  39618. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  39619. this.shapeID = id;
  39620. this._shape = shape;
  39621. this._shapeUV = shapeUV;
  39622. this._positionFunction = posFunction;
  39623. this._vertexFunction = vtxFunction;
  39624. }
  39625. return ModelShape;
  39626. })();
  39627. BABYLON.ModelShape = ModelShape;
  39628. })(BABYLON || (BABYLON = {}));
  39629. var BABYLON;
  39630. (function (BABYLON) {
  39631. /**
  39632. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  39633. */
  39634. var SolidParticleSystem = (function () {
  39635. /**
  39636. * Creates a SPS (Solid Particle System) object.
  39637. * @param name the SPS name, this will be the underlying mesh name
  39638. * @param scene the scene in which the SPS is added
  39639. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  39640. */
  39641. function SolidParticleSystem(name, scene, options) {
  39642. // public members
  39643. /**
  39644. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  39645. * Example : var p = SPS.particles[i];
  39646. */
  39647. this.particles = new Array();
  39648. /**
  39649. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  39650. */
  39651. this.nbParticles = 0;
  39652. /**
  39653. * If the particles must ever face the camera (default false). Useful for planar particles.
  39654. */
  39655. this.billboard = false;
  39656. /**
  39657. * This a counter ofr your own usage. It's not set by any SPS functions.
  39658. */
  39659. this.counter = 0;
  39660. /**
  39661. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  39662. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  39663. */
  39664. this.vars = {};
  39665. this._positions = new Array();
  39666. this._indices = new Array();
  39667. this._normals = new Array();
  39668. this._colors = new Array();
  39669. this._uvs = new Array();
  39670. this._index = 0; // indices index
  39671. this._updatable = true;
  39672. this._pickable = false;
  39673. this._isVisibilityBoxLocked = false;
  39674. this._alwaysVisible = false;
  39675. this._shapeCounter = 0;
  39676. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  39677. this._color = new BABYLON.Color4(0, 0, 0, 0);
  39678. this._computeParticleColor = true;
  39679. this._computeParticleTexture = true;
  39680. this._computeParticleRotation = true;
  39681. this._computeParticleVertex = false;
  39682. this._computeBoundingBox = false;
  39683. this._cam_axisZ = BABYLON.Vector3.Zero();
  39684. this._cam_axisY = BABYLON.Vector3.Zero();
  39685. this._cam_axisX = BABYLON.Vector3.Zero();
  39686. this._axisX = BABYLON.Axis.X;
  39687. this._axisY = BABYLON.Axis.Y;
  39688. this._axisZ = BABYLON.Axis.Z;
  39689. this._fakeCamPos = BABYLON.Vector3.Zero();
  39690. this._rotMatrix = new BABYLON.Matrix();
  39691. this._invertMatrix = new BABYLON.Matrix();
  39692. this._rotated = BABYLON.Vector3.Zero();
  39693. this._quaternion = new BABYLON.Quaternion();
  39694. this._vertex = BABYLON.Vector3.Zero();
  39695. this._normal = BABYLON.Vector3.Zero();
  39696. this._yaw = 0.0;
  39697. this._pitch = 0.0;
  39698. this._roll = 0.0;
  39699. this._halfroll = 0.0;
  39700. this._halfpitch = 0.0;
  39701. this._halfyaw = 0.0;
  39702. this._sinRoll = 0.0;
  39703. this._cosRoll = 0.0;
  39704. this._sinPitch = 0.0;
  39705. this._cosPitch = 0.0;
  39706. this._sinYaw = 0.0;
  39707. this._cosYaw = 0.0;
  39708. this._w = 0.0;
  39709. this._minimum = BABYLON.Tmp.Vector3[0];
  39710. this._maximum = BABYLON.Tmp.Vector3[1];
  39711. this.name = name;
  39712. this._scene = scene;
  39713. this._camera = scene.activeCamera;
  39714. this._pickable = options ? options.isPickable : false;
  39715. if (options && options.updatable) {
  39716. this._updatable = options.updatable;
  39717. }
  39718. else {
  39719. this._updatable = true;
  39720. }
  39721. if (this._pickable) {
  39722. this.pickedParticles = [];
  39723. }
  39724. }
  39725. /**
  39726. * Builds the SPS underlying mesh. Returns a standard Mesh.
  39727. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  39728. */
  39729. SolidParticleSystem.prototype.buildMesh = function () {
  39730. if (this.nbParticles === 0) {
  39731. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  39732. this.addShape(triangle, 1);
  39733. triangle.dispose();
  39734. }
  39735. this._positions32 = new Float32Array(this._positions);
  39736. this._uvs32 = new Float32Array(this._uvs);
  39737. this._colors32 = new Float32Array(this._colors);
  39738. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  39739. this._normals32 = new Float32Array(this._normals);
  39740. this._fixedNormal32 = new Float32Array(this._normals);
  39741. var vertexData = new BABYLON.VertexData();
  39742. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  39743. vertexData.indices = this._indices;
  39744. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  39745. if (this._uvs32) {
  39746. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  39747. ;
  39748. }
  39749. if (this._colors32) {
  39750. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  39751. }
  39752. var mesh = new BABYLON.Mesh(this.name, this._scene);
  39753. vertexData.applyToMesh(mesh, this._updatable);
  39754. this.mesh = mesh;
  39755. this.mesh.isPickable = this._pickable;
  39756. // free memory
  39757. this._positions = null;
  39758. this._normals = null;
  39759. this._uvs = null;
  39760. this._colors = null;
  39761. if (!this._updatable) {
  39762. this.particles.length = 0;
  39763. }
  39764. return mesh;
  39765. };
  39766. /**
  39767. * Digests the mesh and generates as many solid particles in the system as wanted.
  39768. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  39769. * Thus the particles generated from digest() have their property "positiion" yet set.
  39770. * @param mesh the mesh to be digested
  39771. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  39772. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  39773. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  39774. */
  39775. SolidParticleSystem.prototype.digest = function (mesh, options) {
  39776. var size = (options && options.facetNb) || 1;
  39777. var number = (options && options.number);
  39778. var delta = (options && options.delta) || 0;
  39779. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39780. var meshInd = mesh.getIndices();
  39781. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39782. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39783. var f = 0; // facet counter
  39784. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  39785. // compute size from number
  39786. if (number) {
  39787. number = (number > totalFacets) ? totalFacets : number;
  39788. size = Math.round(totalFacets / number);
  39789. delta = 0;
  39790. }
  39791. else {
  39792. size = (size > totalFacets) ? totalFacets : size;
  39793. }
  39794. var facetPos = []; // submesh positions
  39795. var facetInd = []; // submesh indices
  39796. var facetUV = []; // submesh UV
  39797. var facetCol = []; // submesh colors
  39798. var barycenter = BABYLON.Tmp.Vector3[0];
  39799. var rand;
  39800. var sizeO = size;
  39801. while (f < totalFacets) {
  39802. size = sizeO + Math.floor((1 + delta) * Math.random());
  39803. if (f > totalFacets - size) {
  39804. size = totalFacets - f;
  39805. }
  39806. // reset temp arrays
  39807. facetPos.length = 0;
  39808. facetInd.length = 0;
  39809. facetUV.length = 0;
  39810. facetCol.length = 0;
  39811. // iterate over "size" facets
  39812. var fi = 0;
  39813. for (var j = f * 3; j < (f + size) * 3; j++) {
  39814. facetInd.push(fi);
  39815. var i = meshInd[j];
  39816. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  39817. if (meshUV) {
  39818. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  39819. }
  39820. if (meshCol) {
  39821. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  39822. }
  39823. fi++;
  39824. }
  39825. // create a model shape for each single particle
  39826. var idx = this.nbParticles;
  39827. var shape = this._posToShape(facetPos);
  39828. var shapeUV = this._uvsToShapeUV(facetUV);
  39829. // compute the barycenter of the shape
  39830. var v;
  39831. for (v = 0; v < shape.length; v++) {
  39832. barycenter.addInPlace(shape[v]);
  39833. }
  39834. barycenter.scaleInPlace(1 / shape.length);
  39835. // shift the shape from its barycenter to the origin
  39836. for (v = 0; v < shape.length; v++) {
  39837. shape[v].subtractInPlace(barycenter);
  39838. }
  39839. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  39840. // add the particle in the SPS
  39841. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  39842. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  39843. // initialize the particle position
  39844. this.particles[this.nbParticles].position.addInPlace(barycenter);
  39845. this._index += shape.length;
  39846. idx++;
  39847. this.nbParticles++;
  39848. this._shapeCounter++;
  39849. f += size;
  39850. }
  39851. };
  39852. //reset copy
  39853. SolidParticleSystem.prototype._resetCopy = function () {
  39854. this._copy.position.x = 0;
  39855. this._copy.position.y = 0;
  39856. this._copy.position.z = 0;
  39857. this._copy.rotation.x = 0;
  39858. this._copy.rotation.y = 0;
  39859. this._copy.rotation.z = 0;
  39860. this._copy.quaternion = null;
  39861. this._copy.scale.x = 1;
  39862. this._copy.scale.y = 1;
  39863. this._copy.scale.z = 1;
  39864. this._copy.uvs.x = 0;
  39865. this._copy.uvs.y = 0;
  39866. this._copy.uvs.z = 1;
  39867. this._copy.uvs.w = 1;
  39868. this._copy.color = null;
  39869. };
  39870. // _meshBuilder : inserts the shape model in the global SPS mesh
  39871. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  39872. var i;
  39873. var u = 0;
  39874. var c = 0;
  39875. this._resetCopy();
  39876. if (options && options.positionFunction) {
  39877. options.positionFunction(this._copy, idx, idxInShape);
  39878. }
  39879. if (this._copy.quaternion) {
  39880. this._quaternion.x = this._copy.quaternion.x;
  39881. this._quaternion.y = this._copy.quaternion.y;
  39882. this._quaternion.z = this._copy.quaternion.z;
  39883. this._quaternion.w = this._copy.quaternion.w;
  39884. }
  39885. else {
  39886. this._yaw = this._copy.rotation.y;
  39887. this._pitch = this._copy.rotation.x;
  39888. this._roll = this._copy.rotation.z;
  39889. this._quaternionRotationYPR();
  39890. }
  39891. this._quaternionToRotationMatrix();
  39892. for (i = 0; i < shape.length; i++) {
  39893. this._vertex.x = shape[i].x;
  39894. this._vertex.y = shape[i].y;
  39895. this._vertex.z = shape[i].z;
  39896. if (options && options.vertexFunction) {
  39897. options.vertexFunction(this._copy, this._vertex, i);
  39898. }
  39899. this._vertex.x *= this._copy.scale.x;
  39900. this._vertex.y *= this._copy.scale.y;
  39901. this._vertex.z *= this._copy.scale.z;
  39902. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  39903. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  39904. if (meshUV) {
  39905. 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);
  39906. u += 2;
  39907. }
  39908. if (this._copy.color) {
  39909. this._color = this._copy.color;
  39910. }
  39911. else if (meshCol && meshCol[c]) {
  39912. this._color.r = meshCol[c];
  39913. this._color.g = meshCol[c + 1];
  39914. this._color.b = meshCol[c + 2];
  39915. this._color.a = meshCol[c + 3];
  39916. }
  39917. else {
  39918. this._color.r = 1;
  39919. this._color.g = 1;
  39920. this._color.b = 1;
  39921. this._color.a = 1;
  39922. }
  39923. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  39924. c += 4;
  39925. }
  39926. for (i = 0; i < meshInd.length; i++) {
  39927. indices.push(p + meshInd[i]);
  39928. }
  39929. if (this._pickable) {
  39930. var nbfaces = meshInd.length / 3;
  39931. for (i = 0; i < nbfaces; i++) {
  39932. this.pickedParticles.push({ idx: idx, faceId: i });
  39933. }
  39934. }
  39935. };
  39936. // returns a shape array from positions array
  39937. SolidParticleSystem.prototype._posToShape = function (positions) {
  39938. var shape = [];
  39939. for (var i = 0; i < positions.length; i += 3) {
  39940. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  39941. }
  39942. return shape;
  39943. };
  39944. // returns a shapeUV array from a Vector4 uvs
  39945. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  39946. var shapeUV = [];
  39947. if (uvs) {
  39948. for (var i = 0; i < uvs.length; i++)
  39949. shapeUV.push(uvs[i]);
  39950. }
  39951. return shapeUV;
  39952. };
  39953. // adds a new particle object in the particles array
  39954. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  39955. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  39956. };
  39957. /**
  39958. * Adds some particles to the SPS from the model shape.
  39959. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  39960. * @param mesh any Mesh object that will be used as a model for the solid particles.
  39961. * @param nb the number of particles to be created from this model
  39962. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  39963. */
  39964. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  39965. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39966. var meshInd = mesh.getIndices();
  39967. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39968. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39969. var shape = this._posToShape(meshPos);
  39970. var shapeUV = this._uvsToShapeUV(meshUV);
  39971. var posfunc = options ? options.positionFunction : null;
  39972. var vtxfunc = options ? options.vertexFunction : null;
  39973. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  39974. // particles
  39975. var idx = this.nbParticles;
  39976. for (var i = 0; i < nb; i++) {
  39977. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  39978. if (this._updatable) {
  39979. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  39980. }
  39981. this._index += shape.length;
  39982. idx++;
  39983. }
  39984. this.nbParticles += nb;
  39985. this._shapeCounter++;
  39986. return this._shapeCounter - 1;
  39987. };
  39988. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  39989. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  39990. this._resetCopy();
  39991. if (particle._model._positionFunction) {
  39992. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  39993. }
  39994. if (this._copy.quaternion) {
  39995. this._quaternion.x = this._copy.quaternion.x;
  39996. this._quaternion.y = this._copy.quaternion.y;
  39997. this._quaternion.z = this._copy.quaternion.z;
  39998. this._quaternion.w = this._copy.quaternion.w;
  39999. }
  40000. else {
  40001. this._yaw = this._copy.rotation.y;
  40002. this._pitch = this._copy.rotation.x;
  40003. this._roll = this._copy.rotation.z;
  40004. this._quaternionRotationYPR();
  40005. }
  40006. this._quaternionToRotationMatrix();
  40007. this._shape = particle._model._shape;
  40008. for (var pt = 0; pt < this._shape.length; pt++) {
  40009. this._vertex.x = this._shape[pt].x;
  40010. this._vertex.y = this._shape[pt].y;
  40011. this._vertex.z = this._shape[pt].z;
  40012. if (particle._model._vertexFunction) {
  40013. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  40014. }
  40015. this._vertex.x *= this._copy.scale.x;
  40016. this._vertex.y *= this._copy.scale.y;
  40017. this._vertex.z *= this._copy.scale.z;
  40018. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40019. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  40020. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  40021. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  40022. }
  40023. particle.position.x = 0;
  40024. particle.position.y = 0;
  40025. particle.position.z = 0;
  40026. particle.rotation.x = 0;
  40027. particle.rotation.y = 0;
  40028. particle.rotation.z = 0;
  40029. particle.quaternion = null;
  40030. particle.scale.x = 1;
  40031. particle.scale.y = 1;
  40032. particle.scale.z = 1;
  40033. };
  40034. /**
  40035. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  40036. */
  40037. SolidParticleSystem.prototype.rebuildMesh = function () {
  40038. for (var p = 0; p < this.particles.length; p++) {
  40039. this._rebuildParticle(this.particles[p]);
  40040. }
  40041. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40042. };
  40043. /**
  40044. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  40045. * This method calls updateParticle() for each particles of the SPS.
  40046. * For an animated SPS, it is usually called within the render loop.
  40047. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  40048. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  40049. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  40050. */
  40051. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  40052. if (start === void 0) { start = 0; }
  40053. if (end === void 0) { end = this.nbParticles - 1; }
  40054. if (update === void 0) { update = true; }
  40055. if (!this._updatable) {
  40056. return;
  40057. }
  40058. // custom beforeUpdate
  40059. this.beforeUpdateParticles(start, end, update);
  40060. this._cam_axisX.x = 1;
  40061. this._cam_axisX.y = 0;
  40062. this._cam_axisX.z = 0;
  40063. this._cam_axisY.x = 0;
  40064. this._cam_axisY.y = 1;
  40065. this._cam_axisY.z = 0;
  40066. this._cam_axisZ.x = 0;
  40067. this._cam_axisZ.y = 0;
  40068. this._cam_axisZ.z = 1;
  40069. // if the particles will always face the camera
  40070. if (this.billboard) {
  40071. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  40072. this._yaw = this.mesh.rotation.y;
  40073. this._pitch = this.mesh.rotation.x;
  40074. this._roll = this.mesh.rotation.z;
  40075. this._quaternionRotationYPR();
  40076. this._quaternionToRotationMatrix();
  40077. this._rotMatrix.invertToRef(this._invertMatrix);
  40078. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  40079. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  40080. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  40081. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  40082. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  40083. this._cam_axisY.normalize();
  40084. this._cam_axisX.normalize();
  40085. this._cam_axisZ.normalize();
  40086. }
  40087. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  40088. var idx = 0;
  40089. var index = 0;
  40090. var colidx = 0;
  40091. var colorIndex = 0;
  40092. var uvidx = 0;
  40093. var uvIndex = 0;
  40094. if (this._computeBoundingBox) {
  40095. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  40096. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  40097. }
  40098. // particle loop
  40099. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  40100. for (var p = start; p <= end; p++) {
  40101. this._particle = this.particles[p];
  40102. this._shape = this._particle._model._shape;
  40103. this._shapeUV = this._particle._model._shapeUV;
  40104. // call to custom user function to update the particle properties
  40105. this.updateParticle(this._particle);
  40106. // particle rotation matrix
  40107. if (this.billboard) {
  40108. this._particle.rotation.x = 0.0;
  40109. this._particle.rotation.y = 0.0;
  40110. }
  40111. if (this._computeParticleRotation) {
  40112. if (this._particle.quaternion) {
  40113. this._quaternion.x = this._particle.quaternion.x;
  40114. this._quaternion.y = this._particle.quaternion.y;
  40115. this._quaternion.z = this._particle.quaternion.z;
  40116. this._quaternion.w = this._particle.quaternion.w;
  40117. }
  40118. else {
  40119. this._yaw = this._particle.rotation.y;
  40120. this._pitch = this._particle.rotation.x;
  40121. this._roll = this._particle.rotation.z;
  40122. this._quaternionRotationYPR();
  40123. }
  40124. this._quaternionToRotationMatrix();
  40125. }
  40126. for (var pt = 0; pt < this._shape.length; pt++) {
  40127. idx = index + pt * 3;
  40128. colidx = colorIndex + pt * 4;
  40129. uvidx = uvIndex + pt * 2;
  40130. this._vertex.x = this._shape[pt].x;
  40131. this._vertex.y = this._shape[pt].y;
  40132. this._vertex.z = this._shape[pt].z;
  40133. if (this._computeParticleVertex) {
  40134. this.updateParticleVertex(this._particle, this._vertex, pt);
  40135. }
  40136. // positions
  40137. this._vertex.x *= this._particle.scale.x;
  40138. this._vertex.y *= this._particle.scale.y;
  40139. this._vertex.z *= this._particle.scale.z;
  40140. 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];
  40141. 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;
  40142. 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;
  40143. 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;
  40144. 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;
  40145. 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;
  40146. 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;
  40147. if (this._computeBoundingBox) {
  40148. if (this._positions32[idx] < this._minimum.x) {
  40149. this._minimum.x = this._positions32[idx];
  40150. }
  40151. if (this._positions32[idx] > this._maximum.x) {
  40152. this._maximum.x = this._positions32[idx];
  40153. }
  40154. if (this._positions32[idx + 1] < this._minimum.y) {
  40155. this._minimum.y = this._positions32[idx + 1];
  40156. }
  40157. if (this._positions32[idx + 1] > this._maximum.y) {
  40158. this._maximum.y = this._positions32[idx + 1];
  40159. }
  40160. if (this._positions32[idx + 2] < this._minimum.z) {
  40161. this._minimum.z = this._positions32[idx + 2];
  40162. }
  40163. if (this._positions32[idx + 2] > this._maximum.z) {
  40164. this._maximum.z = this._positions32[idx + 2];
  40165. }
  40166. }
  40167. // normals : if the particles can't be morphed then just rotate the normals
  40168. if (!this._computeParticleVertex && !this.billboard) {
  40169. this._normal.x = this._fixedNormal32[idx];
  40170. this._normal.y = this._fixedNormal32[idx + 1];
  40171. this._normal.z = this._fixedNormal32[idx + 2];
  40172. 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];
  40173. 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;
  40174. 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;
  40175. 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;
  40176. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  40177. 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;
  40178. 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;
  40179. }
  40180. if (this._computeParticleColor) {
  40181. this._colors32[colidx] = this._particle.color.r;
  40182. this._colors32[colidx + 1] = this._particle.color.g;
  40183. this._colors32[colidx + 2] = this._particle.color.b;
  40184. this._colors32[colidx + 3] = this._particle.color.a;
  40185. }
  40186. if (this._computeParticleTexture) {
  40187. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40188. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40189. }
  40190. }
  40191. index = idx + 3;
  40192. colorIndex = colidx + 4;
  40193. uvIndex = uvidx + 2;
  40194. }
  40195. if (update) {
  40196. if (this._computeParticleColor) {
  40197. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  40198. }
  40199. if (this._computeParticleTexture) {
  40200. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  40201. }
  40202. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40203. if (!this.mesh.areNormalsFrozen) {
  40204. if (this._computeParticleVertex || this.billboard) {
  40205. // recompute the normals only if the particles can be morphed, update then the normal reference array
  40206. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  40207. for (var i = 0; i < this._normals32.length; i++) {
  40208. this._fixedNormal32[i] = this._normals32[i];
  40209. }
  40210. }
  40211. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  40212. }
  40213. }
  40214. if (this._computeBoundingBox) {
  40215. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  40216. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  40217. }
  40218. this.afterUpdateParticles(start, end, update);
  40219. };
  40220. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  40221. this._halfroll = this._roll * 0.5;
  40222. this._halfpitch = this._pitch * 0.5;
  40223. this._halfyaw = this._yaw * 0.5;
  40224. this._sinRoll = Math.sin(this._halfroll);
  40225. this._cosRoll = Math.cos(this._halfroll);
  40226. this._sinPitch = Math.sin(this._halfpitch);
  40227. this._cosPitch = Math.cos(this._halfpitch);
  40228. this._sinYaw = Math.sin(this._halfyaw);
  40229. this._cosYaw = Math.cos(this._halfyaw);
  40230. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  40231. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  40232. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  40233. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  40234. };
  40235. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  40236. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  40237. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  40238. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  40239. this._rotMatrix.m[3] = 0;
  40240. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  40241. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  40242. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  40243. this._rotMatrix.m[7] = 0;
  40244. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  40245. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  40246. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  40247. this._rotMatrix.m[11] = 0;
  40248. this._rotMatrix.m[12] = 0;
  40249. this._rotMatrix.m[13] = 0;
  40250. this._rotMatrix.m[14] = 0;
  40251. this._rotMatrix.m[15] = 1.0;
  40252. };
  40253. /**
  40254. * Disposes the SPS
  40255. */
  40256. SolidParticleSystem.prototype.dispose = function () {
  40257. this.mesh.dispose();
  40258. this.vars = null;
  40259. // drop references to internal big arrays for the GC
  40260. this._positions = null;
  40261. this._indices = null;
  40262. this._normals = null;
  40263. this._uvs = null;
  40264. this._colors = null;
  40265. this._positions32 = null;
  40266. this._normals32 = null;
  40267. this._fixedNormal32 = null;
  40268. this._uvs32 = null;
  40269. this._colors32 = null;
  40270. this.pickedParticles = null;
  40271. };
  40272. /**
  40273. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  40274. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40275. */
  40276. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  40277. if (!this._isVisibilityBoxLocked) {
  40278. this.mesh.refreshBoundingInfo();
  40279. }
  40280. };
  40281. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  40282. * @param size the size (float) of the visibility box
  40283. * note : this doesn't lock the SPS mesh bounding box.
  40284. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40285. */
  40286. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  40287. var vis = size / 2;
  40288. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  40289. };
  40290. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  40291. // getter and setter
  40292. /**
  40293. * True if the SPS is set as always visible
  40294. */
  40295. get: function () {
  40296. return this._alwaysVisible;
  40297. },
  40298. /**
  40299. * Sets the SPS as always visible or not
  40300. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40301. */
  40302. set: function (val) {
  40303. this._alwaysVisible = val;
  40304. this.mesh.alwaysSelectAsActiveMesh = val;
  40305. },
  40306. enumerable: true,
  40307. configurable: true
  40308. });
  40309. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  40310. /**
  40311. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  40312. */
  40313. get: function () {
  40314. return this._isVisibilityBoxLocked;
  40315. },
  40316. /**
  40317. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  40318. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40319. */
  40320. set: function (val) {
  40321. this._isVisibilityBoxLocked = val;
  40322. this.mesh.getBoundingInfo().isLocked = val;
  40323. },
  40324. enumerable: true,
  40325. configurable: true
  40326. });
  40327. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  40328. // getters
  40329. get: function () {
  40330. return this._computeParticleRotation;
  40331. },
  40332. // Optimizer setters
  40333. /**
  40334. * Tells to setParticles() to compute the particle rotations or not.
  40335. * Default value : true. The SPS is faster when it's set to false.
  40336. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  40337. */
  40338. set: function (val) {
  40339. this._computeParticleRotation = val;
  40340. },
  40341. enumerable: true,
  40342. configurable: true
  40343. });
  40344. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  40345. get: function () {
  40346. return this._computeParticleColor;
  40347. },
  40348. /**
  40349. * Tells to setParticles() to compute the particle colors or not.
  40350. * Default value : true. The SPS is faster when it's set to false.
  40351. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  40352. */
  40353. set: function (val) {
  40354. this._computeParticleColor = val;
  40355. },
  40356. enumerable: true,
  40357. configurable: true
  40358. });
  40359. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  40360. get: function () {
  40361. return this._computeParticleTexture;
  40362. },
  40363. /**
  40364. * Tells to setParticles() to compute the particle textures or not.
  40365. * Default value : true. The SPS is faster when it's set to false.
  40366. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  40367. */
  40368. set: function (val) {
  40369. this._computeParticleTexture = val;
  40370. },
  40371. enumerable: true,
  40372. configurable: true
  40373. });
  40374. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  40375. get: function () {
  40376. return this._computeParticleVertex;
  40377. },
  40378. /**
  40379. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  40380. * Default value : false. The SPS is faster when it's set to false.
  40381. * Note : the particle custom vertex positions aren't stored values.
  40382. */
  40383. set: function (val) {
  40384. this._computeParticleVertex = val;
  40385. },
  40386. enumerable: true,
  40387. configurable: true
  40388. });
  40389. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  40390. get: function () {
  40391. return this._computeBoundingBox;
  40392. },
  40393. /**
  40394. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  40395. */
  40396. set: function (val) {
  40397. this._computeBoundingBox = val;
  40398. },
  40399. enumerable: true,
  40400. configurable: true
  40401. });
  40402. // =======================================================================
  40403. // Particle behavior logic
  40404. // these following methods may be overwritten by the user to fit his needs
  40405. /**
  40406. * This function does nothing. It may be overwritten to set all the particles first values.
  40407. * The SPS doesn't call this function, you may have to call it by your own.
  40408. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40409. */
  40410. SolidParticleSystem.prototype.initParticles = function () {
  40411. };
  40412. /**
  40413. * This function does nothing. It may be overwritten to recycle a particle.
  40414. * The SPS doesn't call this function, you may have to call it by your own.
  40415. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40416. */
  40417. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  40418. return particle;
  40419. };
  40420. /**
  40421. * Updates a particle : this function should be overwritten by the user.
  40422. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  40423. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40424. * ex : just set a particle position or velocity and recycle conditions
  40425. */
  40426. SolidParticleSystem.prototype.updateParticle = function (particle) {
  40427. return particle;
  40428. };
  40429. /**
  40430. * Updates a vertex of a particle : it can be overwritten by the user.
  40431. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  40432. * @param particle the current particle
  40433. * @param vertex the current index of the current particle
  40434. * @param pt the index of the current vertex in the particle shape
  40435. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  40436. * ex : just set a vertex particle position
  40437. */
  40438. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  40439. return vertex;
  40440. };
  40441. /**
  40442. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  40443. * This does nothing and may be overwritten by the user.
  40444. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40445. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40446. * @param update the boolean update value actually passed to setParticles()
  40447. */
  40448. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  40449. };
  40450. /**
  40451. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  40452. * This will be passed three parameters.
  40453. * This does nothing and may be overwritten by the user.
  40454. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40455. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40456. * @param update the boolean update value actually passed to setParticles()
  40457. */
  40458. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  40459. };
  40460. return SolidParticleSystem;
  40461. })();
  40462. BABYLON.SolidParticleSystem = SolidParticleSystem;
  40463. })(BABYLON || (BABYLON = {}));
  40464. var BABYLON;
  40465. (function (BABYLON) {
  40466. var Internals;
  40467. (function (Internals) {
  40468. var FileFaceOrientation = (function () {
  40469. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40470. this.name = name;
  40471. this.worldAxisForNormal = worldAxisForNormal;
  40472. this.worldAxisForFileX = worldAxisForFileX;
  40473. this.worldAxisForFileY = worldAxisForFileY;
  40474. }
  40475. return FileFaceOrientation;
  40476. })();
  40477. ;
  40478. /**
  40479. * Helper class dealing with the extraction of spherical polynomial dataArray
  40480. * from a cube map.
  40481. */
  40482. var CubeMapToSphericalPolynomialTools = (function () {
  40483. function CubeMapToSphericalPolynomialTools() {
  40484. }
  40485. /**
  40486. * Converts a cubemap to the according Spherical Polynomial data.
  40487. * This extracts the first 3 orders only as they are the only one used in the lighting.
  40488. *
  40489. * @param cubeInfo The Cube map to extract the information from.
  40490. * @return The Spherical Polynomial data.
  40491. */
  40492. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40493. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40494. var totalSolidAngle = 0.0;
  40495. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40496. var du = 2.0 / cubeInfo.size;
  40497. var dv = du;
  40498. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40499. var minUV = du * 0.5 - 1.0;
  40500. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40501. var fileFace = this.FileFaces[faceIndex];
  40502. var dataArray = cubeInfo[fileFace.name];
  40503. var v = minUV;
  40504. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40505. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40506. // Because SP is still linear, so summation is fine in that basis.
  40507. for (var y = 0; y < cubeInfo.size; y++) {
  40508. var u = minUV;
  40509. for (var x = 0; x < cubeInfo.size; x++) {
  40510. // World direction (not normalised)
  40511. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40512. worldDirection.normalize();
  40513. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40514. if (1) {
  40515. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40516. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40517. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40518. var color = new BABYLON.Color3(r, g, b);
  40519. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40520. }
  40521. else {
  40522. if (faceIndex == 0) {
  40523. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40524. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40525. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40526. }
  40527. else if (faceIndex == 1) {
  40528. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40529. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40530. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40531. }
  40532. else if (faceIndex == 2) {
  40533. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40534. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40535. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40536. }
  40537. else if (faceIndex == 3) {
  40538. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40539. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40540. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40541. }
  40542. else if (faceIndex == 4) {
  40543. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40544. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40545. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40546. }
  40547. else if (faceIndex == 5) {
  40548. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40549. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40550. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40551. }
  40552. 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]);
  40553. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40554. }
  40555. totalSolidAngle += deltaSolidAngle;
  40556. u += du;
  40557. }
  40558. v += dv;
  40559. }
  40560. }
  40561. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40562. var correction = correctSolidAngle / totalSolidAngle;
  40563. sphericalHarmonics.scale(correction);
  40564. // Additionally scale by pi -- audit needed
  40565. sphericalHarmonics.scale(1.0 / Math.PI);
  40566. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40567. };
  40568. CubeMapToSphericalPolynomialTools.FileFaces = [
  40569. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40570. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40571. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40572. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40573. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40574. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40575. ];
  40576. return CubeMapToSphericalPolynomialTools;
  40577. })();
  40578. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40579. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40580. })(BABYLON || (BABYLON = {}));
  40581. var BABYLON;
  40582. (function (BABYLON) {
  40583. var Internals;
  40584. (function (Internals) {
  40585. /**
  40586. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  40587. */
  40588. var PanoramaToCubeMapTools = (function () {
  40589. function PanoramaToCubeMapTools() {
  40590. }
  40591. /**
  40592. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  40593. *
  40594. * @param float32Array The source data.
  40595. * @param inputWidth The width of the input panorama.
  40596. * @param inputhHeight The height of the input panorama.
  40597. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  40598. * @return The cubemap data
  40599. */
  40600. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40601. if (!float32Array) {
  40602. throw "ConvertPanoramaToCubemap: input cannot be null";
  40603. }
  40604. if (float32Array.length != inputWidth * inputHeight * 3) {
  40605. throw "ConvertPanoramaToCubemap: input size is wrong";
  40606. }
  40607. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40608. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40609. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40610. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40611. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40612. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40613. return {
  40614. front: textureFront,
  40615. back: textureBack,
  40616. left: textureLeft,
  40617. right: textureRight,
  40618. up: textureUp,
  40619. down: textureDown,
  40620. size: size
  40621. };
  40622. };
  40623. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40624. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40625. var textureArray = new Float32Array(buffer);
  40626. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40627. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40628. var dy = 1 / texSize;
  40629. var fy = 0;
  40630. for (var y = 0; y < texSize; y++) {
  40631. var xv1 = faceData[0];
  40632. var xv2 = faceData[2];
  40633. for (var x = 0; x < texSize; x++) {
  40634. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40635. v.normalize();
  40636. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40637. // 3 channels per pixels
  40638. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40639. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40640. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40641. xv1 = xv1.add(rotDX1);
  40642. xv2 = xv2.add(rotDX2);
  40643. }
  40644. fy += dy;
  40645. }
  40646. return textureArray;
  40647. };
  40648. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  40649. var theta = Math.atan2(vDir.z, vDir.x);
  40650. var phi = Math.acos(vDir.y);
  40651. while (theta < -Math.PI)
  40652. theta += 2 * Math.PI;
  40653. while (theta > Math.PI)
  40654. theta -= 2 * Math.PI;
  40655. var dx = theta / Math.PI;
  40656. var dy = phi / Math.PI;
  40657. // recenter.
  40658. dx = dx * 0.5 + 0.5;
  40659. var px = Math.round(dx * inputWidth);
  40660. if (px < 0)
  40661. px = 0;
  40662. else if (px >= inputWidth)
  40663. px = inputWidth - 1;
  40664. var py = Math.round(dy * inputHeight);
  40665. if (py < 0)
  40666. py = 0;
  40667. else if (py >= inputHeight)
  40668. py = inputHeight - 1;
  40669. var inputY = (inputHeight - py - 1);
  40670. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  40671. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  40672. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  40673. return {
  40674. r: r,
  40675. g: g,
  40676. b: b
  40677. };
  40678. };
  40679. PanoramaToCubeMapTools.FACE_FRONT = [
  40680. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40681. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40682. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40683. new BABYLON.Vector3(1.0, 1.0, -1.0)
  40684. ];
  40685. PanoramaToCubeMapTools.FACE_BACK = [
  40686. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40687. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40688. new BABYLON.Vector3(1.0, 1.0, 1.0),
  40689. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  40690. ];
  40691. PanoramaToCubeMapTools.FACE_RIGHT = [
  40692. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40693. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40694. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40695. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40696. ];
  40697. PanoramaToCubeMapTools.FACE_LEFT = [
  40698. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40699. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40700. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40701. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  40702. ];
  40703. PanoramaToCubeMapTools.FACE_DOWN = [
  40704. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40705. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40706. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40707. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40708. ];
  40709. PanoramaToCubeMapTools.FACE_UP = [
  40710. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40711. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40712. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40713. new BABYLON.Vector3(1.0, -1.0, -1.0)
  40714. ];
  40715. return PanoramaToCubeMapTools;
  40716. })();
  40717. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  40718. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40719. })(BABYLON || (BABYLON = {}));
  40720. var BABYLON;
  40721. (function (BABYLON) {
  40722. var Internals;
  40723. (function (Internals) {
  40724. ;
  40725. /**
  40726. * This groups tools to convert HDR texture to native colors array.
  40727. */
  40728. var HDRTools = (function () {
  40729. function HDRTools() {
  40730. }
  40731. HDRTools.Ldexp = function (mantissa, exponent) {
  40732. if (exponent > 1023) {
  40733. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  40734. }
  40735. if (exponent < -1074) {
  40736. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  40737. }
  40738. return mantissa * Math.pow(2, exponent);
  40739. };
  40740. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  40741. if (exponent > 0) {
  40742. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  40743. float32array[index + 0] = red * exponent;
  40744. float32array[index + 1] = green * exponent;
  40745. float32array[index + 2] = blue * exponent;
  40746. }
  40747. else {
  40748. float32array[index + 0] = 0;
  40749. float32array[index + 1] = 0;
  40750. float32array[index + 2] = 0;
  40751. }
  40752. };
  40753. HDRTools.readStringLine = function (uint8array, startIndex) {
  40754. var line = "";
  40755. var character = "";
  40756. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  40757. character = String.fromCharCode(uint8array[i]);
  40758. if (character == "\n") {
  40759. break;
  40760. }
  40761. line += character;
  40762. }
  40763. return line;
  40764. };
  40765. /**
  40766. * Reads header information from an RGBE texture stored in a native array.
  40767. * More information on this format are available here:
  40768. * https://en.wikipedia.org/wiki/RGBE_image_format
  40769. *
  40770. * @param uint8array The binary file stored in native array.
  40771. * @return The header information.
  40772. */
  40773. HDRTools.RGBE_ReadHeader = function (uint8array) {
  40774. var height = 0;
  40775. var width = 0;
  40776. var line = this.readStringLine(uint8array, 0);
  40777. if (line[0] != '#' || line[1] != '?') {
  40778. throw "Bad HDR Format.";
  40779. }
  40780. var endOfHeader = false;
  40781. var findFormat = false;
  40782. var lineIndex = 0;
  40783. do {
  40784. lineIndex += (line.length + 1);
  40785. line = this.readStringLine(uint8array, lineIndex);
  40786. if (line == "FORMAT=32-bit_rle_rgbe") {
  40787. findFormat = true;
  40788. }
  40789. else if (line.length == 0) {
  40790. endOfHeader = true;
  40791. }
  40792. } while (!endOfHeader);
  40793. if (!findFormat) {
  40794. throw "HDR Bad header format, unsupported FORMAT";
  40795. }
  40796. lineIndex += (line.length + 1);
  40797. line = this.readStringLine(uint8array, lineIndex);
  40798. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  40799. var match = sizeRegexp.exec(line);
  40800. // TODO. Support +Y and -X if needed.
  40801. if (match.length < 3) {
  40802. throw "HDR Bad header format, no size";
  40803. }
  40804. width = parseInt(match[2]);
  40805. height = parseInt(match[1]);
  40806. if (width < 8 || width > 0x7fff) {
  40807. throw "HDR Bad header format, unsupported size";
  40808. }
  40809. lineIndex += (line.length + 1);
  40810. return {
  40811. height: height,
  40812. width: width,
  40813. dataPosition: lineIndex
  40814. };
  40815. };
  40816. /**
  40817. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  40818. * This RGBE texture needs to store the information as a panorama.
  40819. *
  40820. * More information on this format are available here:
  40821. * https://en.wikipedia.org/wiki/RGBE_image_format
  40822. *
  40823. * @param buffer The binary file stored in an array buffer.
  40824. * @param size The expected size of the extracted cubemap.
  40825. * @return The Cube Map information.
  40826. */
  40827. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  40828. var uint8array = new Uint8Array(buffer);
  40829. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  40830. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40831. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  40832. return cubeMapData;
  40833. };
  40834. /**
  40835. * Returns the pixels data extracted from an RGBE texture.
  40836. * This pixels will be stored left to right up to down in the R G B order in one array.
  40837. *
  40838. * More information on this format are available here:
  40839. * https://en.wikipedia.org/wiki/RGBE_image_format
  40840. *
  40841. * @param uint8array The binary file stored in an array buffer.
  40842. * @param hdrInfo The header information of the file.
  40843. * @return The pixels data in RGB right to left up to down order.
  40844. */
  40845. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  40846. // Keep for multi format supports.
  40847. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40848. };
  40849. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  40850. var num_scanlines = hdrInfo.height;
  40851. var scanline_width = hdrInfo.width;
  40852. var a, b, c, d, count;
  40853. var dataIndex = hdrInfo.dataPosition;
  40854. var index = 0, endIndex = 0, i = 0;
  40855. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  40856. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  40857. // 3 channels of 4 bytes per pixel in float.
  40858. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  40859. var resultArray = new Float32Array(resultBuffer);
  40860. // read in each successive scanline
  40861. while (num_scanlines > 0) {
  40862. a = uint8array[dataIndex++];
  40863. b = uint8array[dataIndex++];
  40864. c = uint8array[dataIndex++];
  40865. d = uint8array[dataIndex++];
  40866. if (a != 2 || b != 2 || (c & 0x80)) {
  40867. // this file is not run length encoded
  40868. throw "HDR Bad header format, not RLE";
  40869. }
  40870. if (((c << 8) | d) != scanline_width) {
  40871. throw "HDR Bad header format, wrong scan line width";
  40872. }
  40873. index = 0;
  40874. // read each of the four channels for the scanline into the buffer
  40875. for (i = 0; i < 4; i++) {
  40876. endIndex = (i + 1) * scanline_width;
  40877. while (index < endIndex) {
  40878. a = uint8array[dataIndex++];
  40879. b = uint8array[dataIndex++];
  40880. if (a > 128) {
  40881. // a run of the same value
  40882. count = a - 128;
  40883. if ((count == 0) || (count > endIndex - index)) {
  40884. throw "HDR Bad Format, bad scanline data (run)";
  40885. }
  40886. while (count-- > 0) {
  40887. scanLineArray[index++] = b;
  40888. }
  40889. }
  40890. else {
  40891. // a non-run
  40892. count = a;
  40893. if ((count == 0) || (count > endIndex - index)) {
  40894. throw "HDR Bad Format, bad scanline data (non-run)";
  40895. }
  40896. scanLineArray[index++] = b;
  40897. if (--count > 0) {
  40898. for (var j = 0; j < count; j++) {
  40899. scanLineArray[index++] = uint8array[dataIndex++];
  40900. }
  40901. }
  40902. }
  40903. }
  40904. }
  40905. // now convert data from buffer into floats
  40906. for (i = 0; i < scanline_width; i++) {
  40907. a = scanLineArray[i];
  40908. b = scanLineArray[i + scanline_width];
  40909. c = scanLineArray[i + 2 * scanline_width];
  40910. d = scanLineArray[i + 3 * scanline_width];
  40911. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  40912. }
  40913. num_scanlines--;
  40914. }
  40915. return resultArray;
  40916. };
  40917. return HDRTools;
  40918. })();
  40919. Internals.HDRTools = HDRTools;
  40920. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40921. })(BABYLON || (BABYLON = {}));
  40922. //_______________________________________________________________
  40923. // Extracted from CubeMapGen:
  40924. // https://code.google.com/archive/p/cubemapgen/
  40925. //
  40926. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  40927. //_______________________________________________________________
  40928. var BABYLON;
  40929. (function (BABYLON) {
  40930. var Internals;
  40931. (function (Internals) {
  40932. /**
  40933. * The bounding box information used during the conversion process.
  40934. */
  40935. var CMGBoundinBox = (function () {
  40936. function CMGBoundinBox() {
  40937. this.min = new BABYLON.Vector3(0, 0, 0);
  40938. this.max = new BABYLON.Vector3(0, 0, 0);
  40939. this.clear();
  40940. }
  40941. CMGBoundinBox.prototype.clear = function () {
  40942. this.min.x = CMGBoundinBox.MAX;
  40943. this.min.y = CMGBoundinBox.MAX;
  40944. this.min.z = CMGBoundinBox.MAX;
  40945. this.max.x = CMGBoundinBox.MIN;
  40946. this.max.y = CMGBoundinBox.MIN;
  40947. this.max.z = CMGBoundinBox.MIN;
  40948. };
  40949. CMGBoundinBox.prototype.augment = function (x, y, z) {
  40950. this.min.x = Math.min(this.min.x, x);
  40951. this.min.y = Math.min(this.min.y, y);
  40952. this.min.z = Math.min(this.min.z, z);
  40953. this.max.x = Math.max(this.max.x, x);
  40954. this.max.y = Math.max(this.max.y, y);
  40955. this.max.z = Math.max(this.max.z, z);
  40956. };
  40957. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  40958. this.min.x = Math.max(this.min.x, x);
  40959. this.min.y = Math.max(this.min.y, y);
  40960. this.min.z = Math.max(this.min.z, z);
  40961. };
  40962. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  40963. this.max.x = Math.min(this.max.x, x);
  40964. this.max.y = Math.min(this.max.y, y);
  40965. this.max.z = Math.min(this.max.z, z);
  40966. };
  40967. CMGBoundinBox.prototype.empty = function () {
  40968. if ((this.min.x > this.max.y) ||
  40969. (this.min.y > this.max.y) ||
  40970. (this.min.z > this.max.y)) {
  40971. return true;
  40972. }
  40973. else {
  40974. return false;
  40975. }
  40976. };
  40977. CMGBoundinBox.MAX = Number.MAX_VALUE;
  40978. CMGBoundinBox.MIN = Number.MIN_VALUE;
  40979. return CMGBoundinBox;
  40980. })();
  40981. /**
  40982. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  40983. * required by the glossinees of a material.
  40984. *
  40985. * This only supports the cosine drop power as well as Warp fixup generation method.
  40986. *
  40987. * This is using the process from CubeMapGen described here:
  40988. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  40989. */
  40990. var PMREMGenerator = (function () {
  40991. /**
  40992. * Constructor of the generator.
  40993. *
  40994. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  40995. * @param inputSize The size of the cubemap faces
  40996. * @param outputSize The size of the output cubemap faces
  40997. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  40998. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  40999. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  41000. * @param specularPower The max specular level of the desired cubemap
  41001. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  41002. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  41003. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  41004. */
  41005. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  41006. this.input = input;
  41007. this.inputSize = inputSize;
  41008. this.outputSize = outputSize;
  41009. this.maxNumMipLevels = maxNumMipLevels;
  41010. this.numChannels = numChannels;
  41011. this.isFloat = isFloat;
  41012. this.specularPower = specularPower;
  41013. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  41014. this.excludeBase = excludeBase;
  41015. this.fixup = fixup;
  41016. this._outputSurface = [];
  41017. this._numMipLevels = 0;
  41018. }
  41019. /**
  41020. * Launches the filter process and return the result.
  41021. *
  41022. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  41023. */
  41024. PMREMGenerator.prototype.filterCubeMap = function () {
  41025. // Init cubemap processor
  41026. this.init();
  41027. // Filters the cubemap
  41028. this.filterCubeMapMipChain();
  41029. // Returns the filtered mips.
  41030. return this._outputSurface;
  41031. };
  41032. PMREMGenerator.prototype.init = function () {
  41033. var i;
  41034. var j;
  41035. var mipLevelSize;
  41036. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  41037. if (this.maxNumMipLevels == 0) {
  41038. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  41039. }
  41040. //first miplevel size
  41041. mipLevelSize = this.outputSize;
  41042. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  41043. for (j = 0; j < this.maxNumMipLevels; j++) {
  41044. this._outputSurface.length++;
  41045. this._outputSurface[j] = [];
  41046. //Iterate over faces for output images
  41047. for (i = 0; i < 6; i++) {
  41048. this._outputSurface[j].length++;
  41049. // Initializes a new array for the output.
  41050. if (this.isFloat) {
  41051. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  41052. }
  41053. else {
  41054. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  41055. }
  41056. }
  41057. //next mip level is half size
  41058. mipLevelSize >>= 1;
  41059. this._numMipLevels++;
  41060. //terminate if mip chain becomes too small
  41061. if (mipLevelSize == 0) {
  41062. this.maxNumMipLevels = j;
  41063. return;
  41064. }
  41065. }
  41066. };
  41067. //--------------------------------------------------------------------------------------
  41068. //Cube map filtering and mip chain generation.
  41069. // the cube map filtereing is specified using a number of parameters:
  41070. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  41071. // indicates the region of the hemisphere to filter over for each tap.
  41072. //
  41073. // Note that the top mip level is also a filtered version of the original input images
  41074. // as well in order to create mip chains for diffuse environment illumination.
  41075. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  41076. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  41077. //
  41078. // Then the mip angle used to genreate the next level of the mip chain from the first level
  41079. // is a_InitialMipAngle
  41080. //
  41081. // The angle for the subsequent levels of the mip chain are specified by their parents
  41082. // filtering angle and a per-level scale and bias
  41083. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  41084. //
  41085. //--------------------------------------------------------------------------------------
  41086. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  41087. // First, take count of the lighting model to modify SpecularPower
  41088. // 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;
  41089. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  41090. //Cone angle start (for generating subsequent mip levels)
  41091. var currentSpecularPower = this.specularPower;
  41092. //Build filter lookup tables based on the source miplevel size
  41093. this.precomputeFilterLookupTables(this.inputSize);
  41094. // Note that we need to filter the first level before generating mipmap
  41095. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  41096. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  41097. // TODO : Write a function to copy and scale the base mipmap in output
  41098. // I am just lazy here and just put a high specular power value, and do some if.
  41099. if (this.excludeBase && (levelIndex == 0)) {
  41100. // 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).
  41101. currentSpecularPower = 100000.0;
  41102. }
  41103. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  41104. var srcCubeImage = this.input;
  41105. var dstCubeImage = this._outputSurface[levelIndex];
  41106. var dstSize = this.outputSize >> levelIndex;
  41107. // Compute required angle.
  41108. var angle = this.getBaseFilterAngle(currentSpecularPower);
  41109. // filter cube surfaces
  41110. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  41111. // fix seams
  41112. if (this.fixup) {
  41113. this.fixupCubeEdges(dstCubeImage, dstSize);
  41114. }
  41115. // Decrease the specular power to generate the mipmap chain
  41116. // TODO : Use another method for Exclude (see first comment at start of the function
  41117. if (this.excludeBase && (levelIndex == 0)) {
  41118. currentSpecularPower = this.specularPower;
  41119. }
  41120. currentSpecularPower *= this.cosinePowerDropPerMip;
  41121. }
  41122. };
  41123. //--------------------------------------------------------------------------------------
  41124. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  41125. // It allow to optimize the texel to access base on the specular power.
  41126. //--------------------------------------------------------------------------------------
  41127. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  41128. // We want to find the alpha such that:
  41129. // cos(alpha)^cosinePower = epsilon
  41130. // That's: acos(epsilon^(1/cosinePower))
  41131. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  41132. var angle = 180.0;
  41133. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  41134. angle *= 180.0 / Math.PI; // Convert to degree
  41135. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  41136. return angle;
  41137. };
  41138. //--------------------------------------------------------------------------------------
  41139. //Builds the following lookup tables prior to filtering:
  41140. // -normalizer cube map
  41141. // -tap weight lookup table
  41142. //
  41143. //--------------------------------------------------------------------------------------
  41144. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  41145. var srcTexelAngle;
  41146. var iCubeFace;
  41147. //clear pre-existing normalizer cube map
  41148. this._normCubeMap = [];
  41149. //Normalized vectors per cubeface and per-texel solid angle
  41150. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  41151. };
  41152. //--------------------------------------------------------------------------------------
  41153. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  41154. //
  41155. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  41156. //
  41157. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  41158. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  41159. // below
  41160. //--------------------------------------------------------------------------------------
  41161. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  41162. var iCubeFace;
  41163. var u;
  41164. var v;
  41165. //iterate over cube faces
  41166. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41167. //First three channels for norm cube, and last channel for solid angle
  41168. this._normCubeMap.push(new Float32Array(size * size * 4));
  41169. //fast texture walk, build normalizer cube map
  41170. var facesData = this.input[iCubeFace];
  41171. for (v = 0; v < size; v++) {
  41172. for (u = 0; u < size; u++) {
  41173. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  41174. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  41175. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  41176. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  41177. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  41178. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  41179. }
  41180. }
  41181. }
  41182. };
  41183. //--------------------------------------------------------------------------------------
  41184. // Convert cubemap face texel coordinates and face idx to 3D vector
  41185. // note the U and V coords are integer coords and range from 0 to size-1
  41186. // this routine can be used to generate a normalizer cube map
  41187. //--------------------------------------------------------------------------------------
  41188. // SL BEGIN
  41189. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  41190. var nvcU;
  41191. var nvcV;
  41192. var tempVec;
  41193. // Change from original AMD code
  41194. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  41195. // + 0.5f is for texel center addressing
  41196. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  41197. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  41198. // warp fixup
  41199. if (fixup && size > 1) {
  41200. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  41201. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  41202. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  41203. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  41204. }
  41205. // Get current vector
  41206. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  41207. // U contribution
  41208. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  41209. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  41210. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  41211. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  41212. // V contribution and Sum
  41213. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  41214. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  41215. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  41216. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  41217. //add face axis
  41218. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  41219. PMREMGenerator._vectorTemp.x += faceAxis[0];
  41220. PMREMGenerator._vectorTemp.y += faceAxis[1];
  41221. PMREMGenerator._vectorTemp.z += faceAxis[2];
  41222. //normalize vector
  41223. PMREMGenerator._vectorTemp.normalize();
  41224. return PMREMGenerator._vectorTemp;
  41225. };
  41226. //--------------------------------------------------------------------------------------
  41227. // Convert 3D vector to cubemap face texel coordinates and face idx
  41228. // note the U and V coords are integer coords and range from 0 to size-1
  41229. // this routine can be used to generate a normalizer cube map
  41230. //
  41231. // returns face IDX and texel coords
  41232. //--------------------------------------------------------------------------------------
  41233. // SL BEGIN
  41234. /*
  41235. Mapping Texture Coordinates to Cube Map Faces
  41236. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  41237. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  41238. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  41239. map arrangement in Pixar's RenderMan package.
  41240. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  41241. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  41242. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  41243. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  41244. the major axis direction). The target column in the table below explains how the major axis direction
  41245. maps to the 2D image of a particular cube map target.
  41246. major axis
  41247. direction target sc tc ma
  41248. ---------- --------------------------------- --- --- ---
  41249. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  41250. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  41251. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  41252. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  41253. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  41254. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  41255. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  41256. an updated (s,t) is calculated as follows
  41257. s = ( sc/|ma| + 1 ) / 2
  41258. t = ( tc/|ma| + 1 ) / 2
  41259. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  41260. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  41261. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  41262. */
  41263. // Note this method return U and V in range from 0 to size-1
  41264. // SL END
  41265. // Store the information in vector3 for convenience (faceindex, u, v)
  41266. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  41267. var maxCoord;
  41268. var faceIdx;
  41269. //absolute value 3
  41270. var absX = Math.abs(x);
  41271. var absY = Math.abs(y);
  41272. var absZ = Math.abs(z);
  41273. if (absX >= absY && absX >= absZ) {
  41274. maxCoord = absX;
  41275. if (x >= 0) {
  41276. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  41277. }
  41278. else {
  41279. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  41280. }
  41281. }
  41282. else if (absY >= absX && absY >= absZ) {
  41283. maxCoord = absY;
  41284. if (y >= 0) {
  41285. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  41286. }
  41287. else {
  41288. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  41289. }
  41290. }
  41291. else {
  41292. maxCoord = absZ;
  41293. if (z >= 0) {
  41294. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  41295. }
  41296. else {
  41297. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  41298. }
  41299. }
  41300. //divide through by max coord so face vector lies on cube face
  41301. var scale = 1 / maxCoord;
  41302. x *= scale;
  41303. y *= scale;
  41304. z *= scale;
  41305. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  41306. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  41307. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  41308. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  41309. // Modify original AMD code to return value from 0 to Size - 1
  41310. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  41311. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  41312. PMREMGenerator._vectorTemp.x = faceIdx;
  41313. PMREMGenerator._vectorTemp.y = u;
  41314. PMREMGenerator._vectorTemp.z = v;
  41315. return PMREMGenerator._vectorTemp;
  41316. };
  41317. //--------------------------------------------------------------------------------------
  41318. //Original code from Ignacio CastaÒo
  41319. // This formula is from Manne ÷hrstrˆm's thesis.
  41320. // Take two coordiantes in the range [-1, 1] that define a portion of a
  41321. // cube face and return the area of the projection of that portion on the
  41322. // surface of the sphere.
  41323. //--------------------------------------------------------------------------------------
  41324. PMREMGenerator.prototype.areaElement = function (x, y) {
  41325. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  41326. };
  41327. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  41328. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  41329. // (+ 0.5f is for texel center addressing)
  41330. u = (2.0 * (u + 0.5) / size) - 1.0;
  41331. v = (2.0 * (v + 0.5) / size) - 1.0;
  41332. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  41333. var invResolution = 1.0 / size;
  41334. // U and V are the -1..1 texture coordinate on the current face.
  41335. // Get projected area for this texel
  41336. var x0 = u - invResolution;
  41337. var y0 = v - invResolution;
  41338. var x1 = u + invResolution;
  41339. var y1 = v + invResolution;
  41340. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  41341. return solidAngle;
  41342. };
  41343. //--------------------------------------------------------------------------------------
  41344. //The key to the speed of these filtering routines is to quickly define a per-face
  41345. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  41346. // Later these pixels are selectively processed based on their dot products to see if
  41347. // they reside within the filtering cone.
  41348. //
  41349. //This is done by computing the smallest per-texel angle to get a conservative estimate
  41350. // of the number of texels needed to be covered in width and height order to filter the
  41351. // region. the bounding box for the center taps face is defined first, and if the
  41352. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  41353. // defined next
  41354. //--------------------------------------------------------------------------------------
  41355. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  41356. // note that pixels within these regions may be rejected
  41357. // based on the anlge
  41358. var iCubeFace;
  41359. var u;
  41360. var v;
  41361. // bounding box per face to specify region to process
  41362. var filterExtents = [];
  41363. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41364. filterExtents.push(new CMGBoundinBox());
  41365. }
  41366. // min angle a src texel can cover (in degrees)
  41367. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  41368. // angle about center tap to define filter cone
  41369. // filter angle is 1/2 the cone angle
  41370. var filterAngle = filterConeAngle / 2.0;
  41371. //ensure filter angle is larger than a texel
  41372. if (filterAngle < srcTexelAngle) {
  41373. filterAngle = srcTexelAngle;
  41374. }
  41375. //ensure filter cone is always smaller than the hemisphere
  41376. if (filterAngle > 90.0) {
  41377. filterAngle = 90.0;
  41378. }
  41379. // the maximum number of texels in 1D the filter cone angle will cover
  41380. // used to determine bounding box size for filter extents
  41381. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  41382. // ensure conservative region always covers at least one texel
  41383. if (filterSize < 1) {
  41384. filterSize = 1;
  41385. }
  41386. // dotProdThresh threshold based on cone angle to determine whether or not taps
  41387. // reside within the cone angle
  41388. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  41389. // process required faces
  41390. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41391. //iterate over dst cube map face texel
  41392. for (v = 0; v < dstSize; v++) {
  41393. for (u = 0; u < dstSize; u++) {
  41394. //get center tap direction
  41395. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  41396. //clear old per-face filter extents
  41397. this.clearFilterExtents(filterExtents);
  41398. //define per-face filter extents
  41399. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  41400. //perform filtering of src faces using filter extents
  41401. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  41402. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  41403. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  41404. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  41405. }
  41406. }
  41407. }
  41408. };
  41409. //--------------------------------------------------------------------------------------
  41410. //Clear filter extents for the 6 cube map faces
  41411. //--------------------------------------------------------------------------------------
  41412. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  41413. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  41414. filterExtents[iCubeFaces].clear();
  41415. }
  41416. };
  41417. //--------------------------------------------------------------------------------------
  41418. //Define per-face bounding box filter extents
  41419. //
  41420. // These define conservative texel regions in each of the faces the filter can possibly
  41421. // process. When the pixels in the regions are actually processed, the dot product
  41422. // between the tap vector and the center tap vector is used to determine the weight of
  41423. // the tap and whether or not the tap is within the cone.
  41424. //
  41425. //--------------------------------------------------------------------------------------
  41426. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  41427. //neighboring face and bleed over amount, and width of BBOX for
  41428. // left, right, top, and bottom edges of this face
  41429. var bleedOverAmount = [0, 0, 0, 0];
  41430. var bleedOverBBoxMin = [0, 0, 0, 0];
  41431. var bleedOverBBoxMax = [0, 0, 0, 0];
  41432. var neighborFace;
  41433. var neighborEdge;
  41434. var oppositeFaceIdx;
  41435. //get face idx, and u, v info from center tap dir
  41436. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  41437. var faceIdx = result.x;
  41438. var u = result.y;
  41439. var v = result.z;
  41440. //define bbox size within face
  41441. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  41442. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  41443. filterExtents[faceIdx].clampMin(0, 0, 0);
  41444. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  41445. //u and v extent in face corresponding to center tap
  41446. var minU = filterExtents[faceIdx].min.x;
  41447. var minV = filterExtents[faceIdx].min.y;
  41448. var maxU = filterExtents[faceIdx].max.x;
  41449. var maxV = filterExtents[faceIdx].max.y;
  41450. //bleed over amounts for face across u=0 edge (left)
  41451. bleedOverAmount[0] = (bboxSize - u);
  41452. bleedOverBBoxMin[0] = minV;
  41453. bleedOverBBoxMax[0] = maxV;
  41454. //bleed over amounts for face across u=1 edge (right)
  41455. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  41456. bleedOverBBoxMin[1] = minV;
  41457. bleedOverBBoxMax[1] = maxV;
  41458. //bleed over to face across v=0 edge (up)
  41459. bleedOverAmount[2] = (bboxSize - v);
  41460. bleedOverBBoxMin[2] = minU;
  41461. bleedOverBBoxMax[2] = maxU;
  41462. //bleed over to face across v=1 edge (down)
  41463. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  41464. bleedOverBBoxMin[3] = minU;
  41465. bleedOverBBoxMax[3] = maxU;
  41466. //compute bleed over regions in neighboring faces
  41467. for (var i = 0; i < 4; i++) {
  41468. if (bleedOverAmount[i] > 0) {
  41469. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  41470. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  41471. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  41472. // be flipped: the cases are
  41473. // if a left edge mates with a left or bottom edge on the neighbor
  41474. // if a top edge mates with a top or right edge on the neighbor
  41475. // if a right edge mates with a right or top edge on the neighbor
  41476. // if a bottom edge mates with a bottom or left edge on the neighbor
  41477. //Seeing as the edges are enumerated as follows
  41478. // left =0
  41479. // right =1
  41480. // top =2
  41481. // bottom =3
  41482. //
  41483. // so if the edge enums are the same, or the sum of the enums == 3,
  41484. // the bbox needs to be flipped
  41485. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  41486. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  41487. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  41488. }
  41489. //The way the bounding box is extended onto the neighboring face
  41490. // depends on which edge of neighboring face abuts with this one
  41491. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  41492. case PMREMGenerator.CP_EDGE_LEFT:
  41493. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  41494. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  41495. break;
  41496. case PMREMGenerator.CP_EDGE_RIGHT:
  41497. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  41498. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  41499. break;
  41500. case PMREMGenerator.CP_EDGE_TOP:
  41501. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  41502. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  41503. break;
  41504. case PMREMGenerator.CP_EDGE_BOTTOM:
  41505. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  41506. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  41507. break;
  41508. }
  41509. //clamp filter extents in non-center tap faces to remain within surface
  41510. filterExtents[neighborFace].clampMin(0, 0, 0);
  41511. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  41512. }
  41513. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  41514. // from the center tap face, then process the opposite face entirely for now.
  41515. //Note that the cases in which this happens, what usually happens is that
  41516. // more than one edge bleeds onto the opposite face, and the bounding box
  41517. // encompasses the entire cube map face.
  41518. if (bleedOverAmount[i] > srcSize) {
  41519. //determine opposite face
  41520. switch (faceIdx) {
  41521. case PMREMGenerator.CP_FACE_X_POS:
  41522. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  41523. break;
  41524. case PMREMGenerator.CP_FACE_X_NEG:
  41525. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  41526. break;
  41527. case PMREMGenerator.CP_FACE_Y_POS:
  41528. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  41529. break;
  41530. case PMREMGenerator.CP_FACE_Y_NEG:
  41531. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  41532. break;
  41533. case PMREMGenerator.CP_FACE_Z_POS:
  41534. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  41535. break;
  41536. case PMREMGenerator.CP_FACE_Z_NEG:
  41537. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  41538. break;
  41539. default:
  41540. break;
  41541. }
  41542. //just encompass entire face for now
  41543. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  41544. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  41545. }
  41546. }
  41547. };
  41548. //--------------------------------------------------------------------------------------
  41549. //ProcessFilterExtents
  41550. // Process bounding box in each cube face
  41551. //
  41552. //--------------------------------------------------------------------------------------
  41553. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  41554. //accumulators are 64-bit floats in order to have the precision needed
  41555. // over a summation of a large number of pixels
  41556. var dstAccum = [0, 0, 0, 0];
  41557. var weightAccum = 0;
  41558. var k = 0;
  41559. var nSrcChannels = this.numChannels;
  41560. // norm cube map and srcCubeMap have same face width
  41561. var faceWidth = srcSize;
  41562. //amount to add to pointer to move to next scanline in images
  41563. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  41564. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  41565. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  41566. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  41567. // iterate over cubefaces
  41568. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  41569. //if bbox is non empty
  41570. if (!filterExtents[iFaceIdx].empty()) {
  41571. var uStart = filterExtents[iFaceIdx].min.x;
  41572. var vStart = filterExtents[iFaceIdx].min.y;
  41573. var uEnd = filterExtents[iFaceIdx].max.x;
  41574. var vEnd = filterExtents[iFaceIdx].max.y;
  41575. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  41576. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  41577. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  41578. for (var v = vStart; v <= vEnd; v++) {
  41579. var normCubeRowWalk = 0;
  41580. var srcCubeRowWalk = 0;
  41581. for (var u = uStart; u <= uEnd; u++) {
  41582. //pointer to direction in cube map associated with texel
  41583. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  41584. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  41585. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  41586. //check dot product to see if texel is within cone
  41587. var tapDotProd = texelVectX * centerTapDir.x +
  41588. texelVectY * centerTapDir.y +
  41589. texelVectZ * centerTapDir.z;
  41590. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  41591. //solid angle stored in 4th channel of normalizer/solid angle cube map
  41592. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  41593. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  41594. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  41595. // so just adding one to specularpower do the trick.
  41596. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  41597. //iterate over channels
  41598. for (k = 0; k < nSrcChannels; k++) {
  41599. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  41600. srcCubeRowWalk++;
  41601. }
  41602. weightAccum += weight; //accumulate weight
  41603. }
  41604. else {
  41605. //step across source pixel
  41606. srcCubeRowWalk += nSrcChannels;
  41607. }
  41608. normCubeRowWalk += 4; // 4 channels per norm cube map.
  41609. }
  41610. startIndexNormCubeMap += normCubePitch;
  41611. startIndexSrcCubeMap += srcCubePitch;
  41612. }
  41613. }
  41614. }
  41615. //divide through by weights if weight is non zero
  41616. if (weightAccum != 0.0) {
  41617. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  41618. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  41619. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  41620. if (this.numChannels > 3) {
  41621. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  41622. }
  41623. }
  41624. else {
  41625. // otherwise sample nearest
  41626. // get face idx and u, v texel coordinate in face
  41627. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  41628. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  41629. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  41630. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  41631. if (this.numChannels > 3) {
  41632. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  41633. }
  41634. }
  41635. return PMREMGenerator._vectorTemp;
  41636. };
  41637. //--------------------------------------------------------------------------------------
  41638. // Fixup cube edges
  41639. //
  41640. // average texels on cube map faces across the edges
  41641. // WARP/BENT Method Only.
  41642. //--------------------------------------------------------------------------------------
  41643. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  41644. var k;
  41645. var j;
  41646. var i;
  41647. var iFace;
  41648. var iCorner = 0;
  41649. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  41650. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  41651. // note that if functionality to filter across the three texels for each corner, then
  41652. //indexed by corner and face idx. the array contains the face the start points belongs to.
  41653. var cornerPtr = [
  41654. [[], [], []],
  41655. [[], [], []],
  41656. [[], [], []],
  41657. [[], [], []],
  41658. [[], [], []],
  41659. [[], [], []],
  41660. [[], [], []],
  41661. [[], [], []]
  41662. ];
  41663. //if there is no fixup, or fixup width = 0, do nothing
  41664. if (cubeMapSize < 1) {
  41665. return;
  41666. }
  41667. //special case 1x1 cubemap, average face colors
  41668. if (cubeMapSize == 1) {
  41669. //iterate over channels
  41670. for (k = 0; k < this.numChannels; k++) {
  41671. var accum = 0.0;
  41672. //iterate over faces to accumulate face colors
  41673. for (iFace = 0; iFace < 6; iFace++) {
  41674. accum += cubeMap[iFace][k];
  41675. }
  41676. //compute average over 6 face colors
  41677. accum /= 6.0;
  41678. //iterate over faces to distribute face colors
  41679. for (iFace = 0; iFace < 6; iFace++) {
  41680. cubeMap[iFace][k] = accum;
  41681. }
  41682. }
  41683. return;
  41684. }
  41685. //iterate over faces to collect list of corner texel pointers
  41686. for (iFace = 0; iFace < 6; iFace++) {
  41687. //the 4 corner pointers for this face
  41688. faceCornerStartIndicies[0] = [iFace, 0];
  41689. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  41690. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  41691. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  41692. //iterate over face corners to collect cube corner pointers
  41693. for (iCorner = 0; iCorner < 4; iCorner++) {
  41694. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  41695. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  41696. cornerNumPtrs[corner]++;
  41697. }
  41698. }
  41699. //iterate over corners to average across corner tap values
  41700. for (iCorner = 0; iCorner < 8; iCorner++) {
  41701. for (k = 0; k < this.numChannels; k++) {
  41702. var cornerTapAccum = 0.0;
  41703. //iterate over corner texels and average results
  41704. for (i = 0; i < 3; i++) {
  41705. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  41706. }
  41707. //divide by 3 to compute average of corner tap values
  41708. cornerTapAccum *= (1.0 / 3.0);
  41709. //iterate over corner texels and average results
  41710. for (i = 0; i < 3; i++) {
  41711. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  41712. }
  41713. }
  41714. }
  41715. //iterate over the twelve edges of the cube to average across edges
  41716. for (i = 0; i < 12; i++) {
  41717. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  41718. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  41719. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  41720. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  41721. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  41722. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  41723. var edgeWalk = 0;
  41724. var neighborEdgeWalk = 0;
  41725. //Determine walking pointers based on edge type
  41726. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  41727. switch (edge) {
  41728. case PMREMGenerator.CP_EDGE_LEFT:
  41729. // no change to faceEdgeStartPtr
  41730. edgeWalk = this.numChannels * cubeMapSize;
  41731. break;
  41732. case PMREMGenerator.CP_EDGE_RIGHT:
  41733. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  41734. edgeWalk = this.numChannels * cubeMapSize;
  41735. break;
  41736. case PMREMGenerator.CP_EDGE_TOP:
  41737. // no change to faceEdgeStartPtr
  41738. edgeWalk = this.numChannels;
  41739. break;
  41740. case PMREMGenerator.CP_EDGE_BOTTOM:
  41741. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  41742. edgeWalk = this.numChannels;
  41743. break;
  41744. }
  41745. //For certain types of edge abutments, the neighbor edge walk needs to
  41746. // be flipped: the cases are
  41747. // if a left edge mates with a left or bottom edge on the neighbor
  41748. // if a top edge mates with a top or right edge on the neighbor
  41749. // if a right edge mates with a right or top edge on the neighbor
  41750. // if a bottom edge mates with a bottom or left edge on the neighbor
  41751. //Seeing as the edges are enumerated as follows
  41752. // left =0
  41753. // right =1
  41754. // top =2
  41755. // bottom =3
  41756. //
  41757. //If the edge enums are the same, or the sum of the enums == 3,
  41758. // the neighbor edge walk needs to be flipped
  41759. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  41760. switch (neighborEdge) {
  41761. case PMREMGenerator.CP_EDGE_LEFT:
  41762. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  41763. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  41764. break;
  41765. case PMREMGenerator.CP_EDGE_RIGHT:
  41766. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  41767. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  41768. break;
  41769. case PMREMGenerator.CP_EDGE_TOP:
  41770. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  41771. neighborEdgeWalk = -this.numChannels;
  41772. break;
  41773. case PMREMGenerator.CP_EDGE_BOTTOM:
  41774. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  41775. neighborEdgeWalk = -this.numChannels;
  41776. break;
  41777. }
  41778. }
  41779. else {
  41780. //swapped direction neighbor edge walk
  41781. switch (neighborEdge) {
  41782. case PMREMGenerator.CP_EDGE_LEFT:
  41783. //no change to neighborEdgeStartPtr for this case since it points
  41784. // to the upper left corner already
  41785. neighborEdgeWalk = this.numChannels * cubeMapSize;
  41786. break;
  41787. case PMREMGenerator.CP_EDGE_RIGHT:
  41788. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  41789. neighborEdgeWalk = this.numChannels * cubeMapSize;
  41790. break;
  41791. case PMREMGenerator.CP_EDGE_TOP:
  41792. //no change to neighborEdgeStartPtr for this case since it points
  41793. // to the upper left corner already
  41794. neighborEdgeWalk = this.numChannels;
  41795. break;
  41796. case PMREMGenerator.CP_EDGE_BOTTOM:
  41797. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  41798. neighborEdgeWalk = this.numChannels;
  41799. break;
  41800. }
  41801. }
  41802. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  41803. //nearby neighborhood
  41804. //step ahead one texel on edge
  41805. edgeStartIndex += edgeWalk;
  41806. neighborEdgeStartIndex += neighborEdgeWalk;
  41807. // note that this loop does not process the corner texels, since they have already been
  41808. // averaged across faces across earlier
  41809. for (j = 1; j < (cubeMapSize - 1); j++) {
  41810. //for each set of taps along edge, average them
  41811. // and rewrite the results into the edges
  41812. for (k = 0; k < this.numChannels; k++) {
  41813. var edgeTap = cubeMap[face][edgeStartIndex + k];
  41814. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  41815. //compute average of tap intensity values
  41816. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  41817. //propagate average of taps to edge taps
  41818. cubeMap[face][edgeStartIndex + k] = avgTap;
  41819. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  41820. }
  41821. edgeStartIndex += edgeWalk;
  41822. neighborEdgeStartIndex += neighborEdgeWalk;
  41823. }
  41824. }
  41825. };
  41826. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  41827. PMREMGenerator.CP_UDIR = 0;
  41828. PMREMGenerator.CP_VDIR = 1;
  41829. PMREMGenerator.CP_FACEAXIS = 2;
  41830. //used to index cube faces
  41831. PMREMGenerator.CP_FACE_X_POS = 0;
  41832. PMREMGenerator.CP_FACE_X_NEG = 1;
  41833. PMREMGenerator.CP_FACE_Y_POS = 2;
  41834. PMREMGenerator.CP_FACE_Y_NEG = 3;
  41835. PMREMGenerator.CP_FACE_Z_POS = 4;
  41836. PMREMGenerator.CP_FACE_Z_NEG = 5;
  41837. //used to index image edges
  41838. // NOTE.. the actual number corresponding to the edge is important
  41839. // do not change these, or the code will break
  41840. //
  41841. // CP_EDGE_LEFT is u = 0
  41842. // CP_EDGE_RIGHT is u = width-1
  41843. // CP_EDGE_TOP is v = 0
  41844. // CP_EDGE_BOTTOM is v = height-1
  41845. PMREMGenerator.CP_EDGE_LEFT = 0;
  41846. PMREMGenerator.CP_EDGE_RIGHT = 1;
  41847. PMREMGenerator.CP_EDGE_TOP = 2;
  41848. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  41849. //corners of CUBE map (P or N specifys if it corresponds to the
  41850. // positive or negative direction each of X, Y, and Z
  41851. PMREMGenerator.CP_CORNER_NNN = 0;
  41852. PMREMGenerator.CP_CORNER_NNP = 1;
  41853. PMREMGenerator.CP_CORNER_NPN = 2;
  41854. PMREMGenerator.CP_CORNER_NPP = 3;
  41855. PMREMGenerator.CP_CORNER_PNN = 4;
  41856. PMREMGenerator.CP_CORNER_PNP = 5;
  41857. PMREMGenerator.CP_CORNER_PPN = 6;
  41858. PMREMGenerator.CP_CORNER_PPP = 7;
  41859. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  41860. //3x2 matrices that map cube map indexing vectors in 3d
  41861. // (after face selection and divide through by the
  41862. // _ABSOLUTE VALUE_ of the max coord)
  41863. // into NVC space
  41864. //Note this currently assumes the D3D cube face ordering and orientation
  41865. PMREMGenerator._sgFace2DMapping = [
  41866. //XPOS face
  41867. [[0, 0, -1],
  41868. [0, -1, 0],
  41869. [1, 0, 0]],
  41870. //XNEG face
  41871. [[0, 0, 1],
  41872. [0, -1, 0],
  41873. [-1, 0, 0]],
  41874. //YPOS face
  41875. [[1, 0, 0],
  41876. [0, 0, 1],
  41877. [0, 1, 0]],
  41878. //YNEG face
  41879. [[1, 0, 0],
  41880. [0, 0, -1],
  41881. [0, -1, 0]],
  41882. //ZPOS face
  41883. [[1, 0, 0],
  41884. [0, -1, 0],
  41885. [0, 0, 1]],
  41886. //ZNEG face
  41887. [[-1, 0, 0],
  41888. [0, -1, 0],
  41889. [0, 0, -1]],
  41890. ];
  41891. //------------------------------------------------------------------------------
  41892. // D3D cube map face specification
  41893. // mapping from 3D x,y,z cube map lookup coordinates
  41894. // to 2D within face u,v coordinates
  41895. //
  41896. // --------------------> U direction
  41897. // | (within-face texture space)
  41898. // | _____
  41899. // | | |
  41900. // | | +Y |
  41901. // | _____|_____|_____ _____
  41902. // | | | | | |
  41903. // | | -X | +Z | +X | -Z |
  41904. // | |_____|_____|_____|_____|
  41905. // | | |
  41906. // | | -Y |
  41907. // | |_____|
  41908. // |
  41909. // v V direction
  41910. // (within-face texture space)
  41911. //------------------------------------------------------------------------------
  41912. //Information about neighbors and how texture coorrdinates change across faces
  41913. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  41914. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  41915. //Note this currently assumes the D3D cube face ordering and orientation
  41916. PMREMGenerator._sgCubeNgh = [
  41917. //XPOS face
  41918. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  41919. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  41920. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  41921. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  41922. //XNEG face
  41923. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  41924. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  41925. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  41926. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  41927. //YPOS face
  41928. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  41929. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  41930. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  41931. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  41932. //YNEG face
  41933. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  41934. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  41935. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  41936. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  41937. //ZPOS face
  41938. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  41939. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  41940. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  41941. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  41942. //ZNEG face
  41943. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  41944. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  41945. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  41946. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  41947. ];
  41948. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  41949. // this table is used to average over the edges.
  41950. PMREMGenerator._sgCubeEdgeList = [
  41951. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  41952. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  41953. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  41954. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  41955. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  41956. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  41957. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  41958. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  41959. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  41960. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  41961. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  41962. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  41963. ];
  41964. //Information about which of the 8 cube corners are correspond to the
  41965. // the 4 corners in each cube face
  41966. // the order is upper left, upper right, lower left, lower right
  41967. PMREMGenerator._sgCubeCornerList = [
  41968. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  41969. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  41970. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  41971. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  41972. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  41973. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  41974. ];
  41975. return PMREMGenerator;
  41976. })();
  41977. Internals.PMREMGenerator = PMREMGenerator;
  41978. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41979. })(BABYLON || (BABYLON = {}));
  41980. var BABYLON;
  41981. (function (BABYLON) {
  41982. /**
  41983. * This represents a texture coming from an HDR input.
  41984. *
  41985. * The only supported format is currently panorama picture stored in RGBE format.
  41986. * Example of such files can be found on HDRLib: http://hdrlib.com/
  41987. */
  41988. var HDRCubeTexture = (function (_super) {
  41989. __extends(HDRCubeTexture, _super);
  41990. /**
  41991. * Instantiates an HDRTexture from the following parameters.
  41992. *
  41993. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  41994. * @param scene The scene the texture will be used in
  41995. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  41996. * @param noMipmap Forces to not generate the mipmap if true
  41997. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  41998. * @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)
  41999. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  42000. */
  42001. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  42002. if (noMipmap === void 0) { noMipmap = false; }
  42003. if (generateHarmonics === void 0) { generateHarmonics = true; }
  42004. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  42005. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  42006. _super.call(this, scene);
  42007. this._useInGammaSpace = false;
  42008. this._generateHarmonics = true;
  42009. /**
  42010. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  42011. */
  42012. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42013. /**
  42014. * The spherical polynomial data extracted from the texture.
  42015. */
  42016. this.sphericalPolynomial = null;
  42017. /**
  42018. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  42019. * This is usefull at run time to apply the good shader.
  42020. */
  42021. this.isPMREM = false;
  42022. this.name = url;
  42023. this.url = url;
  42024. this._noMipmap = noMipmap;
  42025. this.hasAlpha = false;
  42026. this._size = size;
  42027. this._useInGammaSpace = useInGammaSpace;
  42028. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  42029. this.isPMREM = this._usePMREMGenerator;
  42030. if (!url) {
  42031. return;
  42032. }
  42033. this._texture = this._getFromCache(url, noMipmap);
  42034. if (!this._texture) {
  42035. if (!scene.useDelayedTextureLoading) {
  42036. this.loadTexture();
  42037. }
  42038. else {
  42039. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42040. }
  42041. }
  42042. this.isCube = true;
  42043. this._textureMatrix = BABYLON.Matrix.Identity();
  42044. }
  42045. HDRCubeTexture.prototype.loadTexture = function () {
  42046. var _this = this;
  42047. var callback = function (buffer) {
  42048. // Extract the raw linear data.
  42049. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  42050. // Generate harmonics if needed.
  42051. if (_this._generateHarmonics) {
  42052. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  42053. }
  42054. var results = [];
  42055. var byteArray = null;
  42056. // Create uintarray fallback.
  42057. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  42058. // 3 channels of 1 bytes per pixel in bytes.
  42059. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  42060. byteArray = new Uint8Array(byteBuffer);
  42061. }
  42062. // Push each faces.
  42063. for (var j = 0; j < 6; j++) {
  42064. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  42065. // If special cases.
  42066. if (_this._useInGammaSpace || byteArray) {
  42067. for (var i = 0; i < _this._size * _this._size; i++) {
  42068. // Put in gamma space if requested.
  42069. if (_this._useInGammaSpace) {
  42070. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  42071. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  42072. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  42073. }
  42074. // Convert to int texture for fallback.
  42075. if (byteArray) {
  42076. // R
  42077. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  42078. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  42079. // G
  42080. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  42081. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  42082. // B
  42083. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  42084. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  42085. }
  42086. }
  42087. }
  42088. results.push(dataFace);
  42089. }
  42090. return results;
  42091. };
  42092. var mipmapGenerator = null;
  42093. if (!this._noMipmap && this._usePMREMGenerator) {
  42094. mipmapGenerator = function (data) {
  42095. // Custom setup of the generator matching with the PBR shader values.
  42096. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  42097. return generator.filterCubeMap();
  42098. };
  42099. }
  42100. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  42101. };
  42102. HDRCubeTexture.prototype.clone = function () {
  42103. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  42104. // Base texture
  42105. newTexture.level = this.level;
  42106. newTexture.wrapU = this.wrapU;
  42107. newTexture.wrapV = this.wrapV;
  42108. newTexture.coordinatesIndex = this.coordinatesIndex;
  42109. newTexture.coordinatesMode = this.coordinatesMode;
  42110. return newTexture;
  42111. };
  42112. // Methods
  42113. HDRCubeTexture.prototype.delayLoad = function () {
  42114. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42115. return;
  42116. }
  42117. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42118. this._texture = this._getFromCache(this.url, this._noMipmap);
  42119. if (!this._texture) {
  42120. this.loadTexture();
  42121. }
  42122. };
  42123. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  42124. return this._textureMatrix;
  42125. };
  42126. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42127. var texture = null;
  42128. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  42129. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  42130. texture.name = parsedTexture.name;
  42131. texture.hasAlpha = parsedTexture.hasAlpha;
  42132. texture.level = parsedTexture.level;
  42133. texture.coordinatesMode = parsedTexture.coordinatesMode;
  42134. }
  42135. return texture;
  42136. };
  42137. HDRCubeTexture.prototype.serialize = function () {
  42138. if (!this.name) {
  42139. return null;
  42140. }
  42141. var serializationObject = {};
  42142. serializationObject.name = this.name;
  42143. serializationObject.hasAlpha = this.hasAlpha;
  42144. serializationObject.isCube = true;
  42145. serializationObject.level = this.level;
  42146. serializationObject.size = this._size;
  42147. serializationObject.coordinatesMode = this.coordinatesMode;
  42148. serializationObject.useInGammaSpace = this._useInGammaSpace;
  42149. serializationObject.generateHarmonics = this._generateHarmonics;
  42150. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  42151. return serializationObject;
  42152. };
  42153. HDRCubeTexture._facesMapping = [
  42154. "right",
  42155. "up",
  42156. "front",
  42157. "left",
  42158. "down",
  42159. "back"
  42160. ];
  42161. return HDRCubeTexture;
  42162. })(BABYLON.BaseTexture);
  42163. BABYLON.HDRCubeTexture = HDRCubeTexture;
  42164. })(BABYLON || (BABYLON = {}));
  42165. var BABYLON;
  42166. (function (BABYLON) {
  42167. var Debug;
  42168. (function (Debug) {
  42169. /**
  42170. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  42171. */
  42172. var SkeletonViewer = (function () {
  42173. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  42174. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  42175. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  42176. this.skeleton = skeleton;
  42177. this.mesh = mesh;
  42178. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  42179. this.renderingGroupId = renderingGroupId;
  42180. this.color = BABYLON.Color3.White();
  42181. this._debugLines = [];
  42182. this._isEnabled = false;
  42183. this._scene = scene;
  42184. this.update();
  42185. this._renderFunction = this.update.bind(this);
  42186. }
  42187. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  42188. get: function () {
  42189. return this._isEnabled;
  42190. },
  42191. set: function (value) {
  42192. if (this._isEnabled === value) {
  42193. return;
  42194. }
  42195. this._isEnabled = value;
  42196. if (value) {
  42197. this._scene.registerBeforeRender(this._renderFunction);
  42198. }
  42199. else {
  42200. this._scene.unregisterBeforeRender(this._renderFunction);
  42201. }
  42202. },
  42203. enumerable: true,
  42204. configurable: true
  42205. });
  42206. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  42207. if (x === void 0) { x = 0; }
  42208. if (y === void 0) { y = 0; }
  42209. if (z === void 0) { z = 0; }
  42210. var tmat = BABYLON.Tmp.Matrix[0];
  42211. var parentBone = bone.getParent();
  42212. tmat.copyFrom(bone.getLocalMatrix());
  42213. if (x !== 0 || y !== 0 || z !== 0) {
  42214. var tmat2 = BABYLON.Tmp.Matrix[1];
  42215. BABYLON.Matrix.IdentityToRef(tmat2);
  42216. tmat2.m[12] = x;
  42217. tmat2.m[13] = y;
  42218. tmat2.m[14] = z;
  42219. tmat2.multiplyToRef(tmat, tmat);
  42220. }
  42221. if (parentBone) {
  42222. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  42223. }
  42224. tmat.multiplyToRef(meshMat, tmat);
  42225. position.x = tmat.m[12];
  42226. position.y = tmat.m[13];
  42227. position.z = tmat.m[14];
  42228. };
  42229. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  42230. var len = bones.length;
  42231. for (var i = 0; i < len; i++) {
  42232. var bone = bones[i];
  42233. var points = this._debugLines[i];
  42234. if (!points) {
  42235. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  42236. this._debugLines[i] = points;
  42237. }
  42238. this._getBonePosition(points[0], bone, meshMat);
  42239. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  42240. }
  42241. };
  42242. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  42243. var len = bones.length;
  42244. var boneNum = 0;
  42245. for (var i = len - 1; i >= 0; i--) {
  42246. var childBone = bones[i];
  42247. var parentBone = childBone.getParent();
  42248. if (!parentBone) {
  42249. continue;
  42250. }
  42251. var points = this._debugLines[boneNum];
  42252. if (!points) {
  42253. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  42254. this._debugLines[boneNum] = points;
  42255. }
  42256. this._getBonePosition(points[0], childBone, meshMat);
  42257. this._getBonePosition(points[1], parentBone, meshMat);
  42258. boneNum++;
  42259. }
  42260. };
  42261. SkeletonViewer.prototype.update = function () {
  42262. if (this.autoUpdateBonesMatrices) {
  42263. this._updateBoneMatrix(this.skeleton.bones[0]);
  42264. }
  42265. if (this.skeleton.bones[0].length === undefined) {
  42266. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  42267. }
  42268. else {
  42269. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  42270. }
  42271. if (!this._debugMesh) {
  42272. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  42273. this._debugMesh.renderingGroupId = this.renderingGroupId;
  42274. }
  42275. else {
  42276. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  42277. }
  42278. this._debugMesh.color = this.color;
  42279. };
  42280. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  42281. if (bone.getParent()) {
  42282. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  42283. }
  42284. var children = bone.children;
  42285. var len = children.length;
  42286. for (var i = 0; i < len; i++) {
  42287. this._updateBoneMatrix(children[i]);
  42288. }
  42289. };
  42290. SkeletonViewer.prototype.dispose = function () {
  42291. if (this._debugMesh) {
  42292. this.isEnabled = false;
  42293. this._debugMesh.dispose();
  42294. this._debugMesh = null;
  42295. }
  42296. };
  42297. return SkeletonViewer;
  42298. })();
  42299. Debug.SkeletonViewer = SkeletonViewer;
  42300. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  42301. })(BABYLON || (BABYLON = {}));
  42302. 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}","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}","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) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n#if defined(DIFFUSE_COLOR_RENDER)\nuniform vec3 color;\n#endif\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\n#endif\n#ifdef ALPHATEST\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\n#ifdef OPACITY\nvec4 opacityColor=texture2D(opacitySampler,vUV);\nfloat alpha=1.0;\n#ifdef OPACITYRGB\nopacityColor.rgb=opacityColor.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityColor.x+opacityColor.y+opacityColor.z)*opacityLevel;\n#else\nalpha*=opacityColor.a*opacityLevel;\n#endif\n#if defined(BASIC_RENDER)\ngl_FragColor=vec4(diffuseColor.rgb,alpha);\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,alpha);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,alpha);\n#endif\ngl_FragColor.a=alpha;\n#else\n#if defined(BASIC_RENDER)\ngl_FragColor=diffuseColor;\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,1.0);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n#endif\n#endif\n}\n","vrDistortionCorrectionPixelShader":"\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}"};
  42303. 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\n#ifdef PARALLAXOCCLUSION\nif (diffuseUV.x>1.0 || diffuseUV.y>1.0 || diffuseUV.x<0.0 || diffuseUV.y<0.0) {\ndiscard;\n}\n#endif\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","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","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"};
  42304. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,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]?!1:!0},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.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={}));";
  42305. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  42306. module.exports = BABYLON;
  42307. };