babylon.max.js 2.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128
  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.camera = 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. if (this.attachedElement) {
  11108. input.attachControl(this.attachedElement);
  11109. }
  11110. };
  11111. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11112. for (var cam in this.attached) {
  11113. var input = this.attached[cam];
  11114. if (input == inputToRemove) {
  11115. input.detachControl(this.attachedElement);
  11116. delete this.attached[cam];
  11117. }
  11118. }
  11119. };
  11120. CameraInputsManager.prototype.removeByType = function (inputType) {
  11121. for (var cam in this.attached) {
  11122. var input = this.attached[cam];
  11123. if (input.getTypeName() == inputType) {
  11124. input.detachControl(this.attachedElement);
  11125. delete this.attached[cam];
  11126. }
  11127. }
  11128. };
  11129. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11130. var current = this.checkInputs;
  11131. return function () {
  11132. current();
  11133. fn();
  11134. };
  11135. };
  11136. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11137. this.attachedElement = element;
  11138. for (var cam in this.attached) {
  11139. var input = this.attached[cam];
  11140. this.attached[cam].attachControl(element, noPreventDefault);
  11141. }
  11142. };
  11143. CameraInputsManager.prototype.detachElement = function (element) {
  11144. for (var cam in this.attached) {
  11145. var input = this.attached[cam];
  11146. this.attached[cam].detachControl(element);
  11147. }
  11148. };
  11149. CameraInputsManager.prototype.rebuildInputCheck = function (element) {
  11150. this.checkInputs = function () { };
  11151. for (var cam in this.attached) {
  11152. var input = this.attached[cam];
  11153. if (input.checkInputs) {
  11154. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11155. }
  11156. }
  11157. };
  11158. CameraInputsManager.prototype.clear = function () {
  11159. this.detachElement(this.attachedElement);
  11160. this.attached = {};
  11161. this.attachedElement = null;
  11162. this.checkInputs = function () { };
  11163. };
  11164. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11165. var inputs = {};
  11166. for (var cam in this.attached) {
  11167. var input = this.attached[cam];
  11168. var res = BABYLON.SerializationHelper.Serialize(input, serializedCamera);
  11169. inputs[input.getTypeName()] = res;
  11170. }
  11171. serializedCamera.inputsmgr = inputs;
  11172. };
  11173. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11174. var parsedInputs = parsedCamera.inputsmgr;
  11175. if (parsedInputs) {
  11176. this.clear();
  11177. for (var n in parsedInputs) {
  11178. var construct = BABYLON.CameraInputTypes[n];
  11179. if (construct) {
  11180. var parsedinput = parsedInputs[n];
  11181. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11182. this.add(input);
  11183. }
  11184. }
  11185. }
  11186. else {
  11187. //2016-03-08 this part is for managing backward compatibility
  11188. for (var n in this.attached) {
  11189. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11190. if (construct) {
  11191. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11192. this.add(input);
  11193. }
  11194. }
  11195. }
  11196. };
  11197. return CameraInputsManager;
  11198. })();
  11199. BABYLON.CameraInputsManager = CameraInputsManager;
  11200. })(BABYLON || (BABYLON = {}));
  11201. var BABYLON;
  11202. (function (BABYLON) {
  11203. var FreeCameraMouseInput = (function () {
  11204. function FreeCameraMouseInput() {
  11205. this.angularSensibility = 2000.0;
  11206. }
  11207. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11208. var _this = this;
  11209. var previousPosition;
  11210. if (this._onMouseDown === undefined) {
  11211. var camera = this.camera;
  11212. var engine = this.camera.getEngine();
  11213. this._onMouseDown = function (evt) {
  11214. previousPosition = {
  11215. x: evt.clientX,
  11216. y: evt.clientY
  11217. };
  11218. if (!noPreventDefault) {
  11219. evt.preventDefault();
  11220. }
  11221. };
  11222. this._onMouseUp = function (evt) {
  11223. previousPosition = null;
  11224. if (!noPreventDefault) {
  11225. evt.preventDefault();
  11226. }
  11227. };
  11228. this._onMouseOut = function (evt) {
  11229. previousPosition = null;
  11230. if (!noPreventDefault) {
  11231. evt.preventDefault();
  11232. }
  11233. };
  11234. this._onMouseMove = function (evt) {
  11235. if (!previousPosition && !engine.isPointerLock) {
  11236. return;
  11237. }
  11238. var offsetX;
  11239. var offsetY;
  11240. if (!engine.isPointerLock) {
  11241. offsetX = evt.clientX - previousPosition.x;
  11242. offsetY = evt.clientY - previousPosition.y;
  11243. }
  11244. else {
  11245. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11246. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11247. }
  11248. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11249. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11250. previousPosition = {
  11251. x: evt.clientX,
  11252. y: evt.clientY
  11253. };
  11254. if (!noPreventDefault) {
  11255. evt.preventDefault();
  11256. }
  11257. };
  11258. }
  11259. element.addEventListener("mousedown", this._onMouseDown, false);
  11260. element.addEventListener("mouseup", this._onMouseUp, false);
  11261. element.addEventListener("mouseout", this._onMouseOut, false);
  11262. element.addEventListener("mousemove", this._onMouseMove, false);
  11263. };
  11264. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11265. if (this._onMouseDown && element) {
  11266. element.removeEventListener("mousedown", this._onMouseDown);
  11267. element.removeEventListener("mouseup", this._onMouseUp);
  11268. element.removeEventListener("mouseout", this._onMouseOut);
  11269. element.removeEventListener("mousemove", this._onMouseMove);
  11270. }
  11271. };
  11272. FreeCameraMouseInput.prototype.getTypeName = function () {
  11273. return "FreeCameraMouseInput";
  11274. };
  11275. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11276. return "mouse";
  11277. };
  11278. __decorate([
  11279. BABYLON.serialize()
  11280. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11281. return FreeCameraMouseInput;
  11282. })();
  11283. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11284. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11285. })(BABYLON || (BABYLON = {}));
  11286. var BABYLON;
  11287. (function (BABYLON) {
  11288. var FreeCameraKeyboardMoveInput = (function () {
  11289. function FreeCameraKeyboardMoveInput() {
  11290. this._keys = [];
  11291. this.keysUp = [38];
  11292. this.keysDown = [40];
  11293. this.keysLeft = [37];
  11294. this.keysRight = [39];
  11295. }
  11296. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11297. var _this = this;
  11298. if (this._onKeyDown === undefined) {
  11299. this._onKeyDown = function (evt) {
  11300. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11301. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11302. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11303. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11304. var index = _this._keys.indexOf(evt.keyCode);
  11305. if (index === -1) {
  11306. _this._keys.push(evt.keyCode);
  11307. }
  11308. if (!noPreventDefault) {
  11309. evt.preventDefault();
  11310. }
  11311. }
  11312. };
  11313. this._onKeyUp = function (evt) {
  11314. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11315. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11316. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11317. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11318. var index = _this._keys.indexOf(evt.keyCode);
  11319. if (index >= 0) {
  11320. _this._keys.splice(index, 1);
  11321. }
  11322. if (!noPreventDefault) {
  11323. evt.preventDefault();
  11324. }
  11325. }
  11326. };
  11327. BABYLON.Tools.RegisterTopRootEvents([
  11328. { name: "keydown", handler: this._onKeyDown },
  11329. { name: "keyup", handler: this._onKeyUp },
  11330. { name: "blur", handler: this._onLostFocus }
  11331. ]);
  11332. }
  11333. };
  11334. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11335. BABYLON.Tools.UnregisterTopRootEvents([
  11336. { name: "keydown", handler: this._onKeyDown },
  11337. { name: "keyup", handler: this._onKeyUp },
  11338. { name: "blur", handler: this._onLostFocus }
  11339. ]);
  11340. };
  11341. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11342. var camera = this.camera;
  11343. // Keyboard
  11344. for (var index = 0; index < this._keys.length; index++) {
  11345. var keyCode = this._keys[index];
  11346. var speed = camera._computeLocalCameraSpeed();
  11347. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11348. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11349. }
  11350. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11351. camera._localDirection.copyFromFloats(0, 0, speed);
  11352. }
  11353. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11354. camera._localDirection.copyFromFloats(speed, 0, 0);
  11355. }
  11356. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11357. camera._localDirection.copyFromFloats(0, 0, -speed);
  11358. }
  11359. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11360. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11361. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11362. }
  11363. };
  11364. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11365. return "FreeCameraKeyboardMoveInput";
  11366. };
  11367. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11368. this._keys = [];
  11369. };
  11370. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11371. return "keyboard";
  11372. };
  11373. __decorate([
  11374. BABYLON.serialize()
  11375. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11376. __decorate([
  11377. BABYLON.serialize()
  11378. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11379. __decorate([
  11380. BABYLON.serialize()
  11381. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11382. __decorate([
  11383. BABYLON.serialize()
  11384. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11385. return FreeCameraKeyboardMoveInput;
  11386. })();
  11387. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11388. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11389. })(BABYLON || (BABYLON = {}));
  11390. var BABYLON;
  11391. (function (BABYLON) {
  11392. var FreeCameraTouchInput = (function () {
  11393. function FreeCameraTouchInput() {
  11394. this._offsetX = null;
  11395. this._offsetY = null;
  11396. this._pointerCount = 0;
  11397. this._pointerPressed = [];
  11398. this.touchAngularSensibility = 200000.0;
  11399. this.touchMoveSensibility = 250.0;
  11400. }
  11401. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11402. var _this = this;
  11403. var previousPosition;
  11404. if (this._onPointerDown === undefined) {
  11405. this._onLostFocus = function (evt) {
  11406. _this._offsetX = null;
  11407. _this._offsetY = null;
  11408. };
  11409. this._onPointerDown = function (evt) {
  11410. if (evt.pointerType === "mouse") {
  11411. return;
  11412. }
  11413. if (!noPreventDefault) {
  11414. evt.preventDefault();
  11415. }
  11416. _this._pointerPressed.push(evt.pointerId);
  11417. if (_this._pointerPressed.length !== 1) {
  11418. return;
  11419. }
  11420. previousPosition = {
  11421. x: evt.clientX,
  11422. y: evt.clientY
  11423. };
  11424. };
  11425. this._onPointerUp = function (evt) {
  11426. if (evt.pointerType === "mouse") {
  11427. return;
  11428. }
  11429. if (!noPreventDefault) {
  11430. evt.preventDefault();
  11431. }
  11432. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11433. if (index === -1) {
  11434. return;
  11435. }
  11436. _this._pointerPressed.splice(index, 1);
  11437. if (index != 0) {
  11438. return;
  11439. }
  11440. previousPosition = null;
  11441. _this._offsetX = null;
  11442. _this._offsetY = null;
  11443. };
  11444. this._onPointerMove = function (evt) {
  11445. if (evt.pointerType === "mouse") {
  11446. return;
  11447. }
  11448. if (!noPreventDefault) {
  11449. evt.preventDefault();
  11450. }
  11451. if (!previousPosition) {
  11452. return;
  11453. }
  11454. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11455. if (index != 0) {
  11456. return;
  11457. }
  11458. _this._offsetX = evt.clientX - previousPosition.x;
  11459. _this._offsetY = -(evt.clientY - previousPosition.y);
  11460. };
  11461. }
  11462. element.addEventListener("blur", this._onLostFocus);
  11463. element.addEventListener("pointerdown", this._onPointerDown);
  11464. element.addEventListener("pointerup", this._onPointerUp);
  11465. element.addEventListener("pointerout", this._onPointerUp);
  11466. element.addEventListener("pointermove", this._onPointerMove);
  11467. };
  11468. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11469. element.removeEventListener("blur", this._onLostFocus);
  11470. element.removeEventListener("pointerdown", this._onPointerDown);
  11471. element.removeEventListener("pointerup", this._onPointerUp);
  11472. element.removeEventListener("pointerout", this._onPointerUp);
  11473. element.removeEventListener("pointermove", this._onPointerMove);
  11474. };
  11475. FreeCameraTouchInput.prototype.checkInputs = function () {
  11476. if (this._offsetX) {
  11477. var camera = this.camera;
  11478. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11479. if (this._pointerPressed.length > 1) {
  11480. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11481. }
  11482. else {
  11483. var speed = camera._computeLocalCameraSpeed();
  11484. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11485. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11486. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11487. }
  11488. }
  11489. };
  11490. FreeCameraTouchInput.prototype.getTypeName = function () {
  11491. return "FreeCameraTouchInput";
  11492. };
  11493. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11494. return "touch";
  11495. };
  11496. __decorate([
  11497. BABYLON.serialize()
  11498. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11499. __decorate([
  11500. BABYLON.serialize()
  11501. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11502. return FreeCameraTouchInput;
  11503. })();
  11504. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11505. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11506. })(BABYLON || (BABYLON = {}));
  11507. var BABYLON;
  11508. (function (BABYLON) {
  11509. var FreeCameraDeviceOrientationInput = (function () {
  11510. function FreeCameraDeviceOrientationInput() {
  11511. this._offsetX = null;
  11512. this._offsetY = null;
  11513. this._orientationGamma = 0;
  11514. this._orientationBeta = 0;
  11515. this._initialOrientationGamma = 0;
  11516. this._initialOrientationBeta = 0;
  11517. this.angularSensibility = 10000.0;
  11518. this.moveSensibility = 50.0;
  11519. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11520. this._orientationChanged = this.orientationChanged.bind(this);
  11521. }
  11522. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11523. window.addEventListener("resize", this._resetOrientationGamma, false);
  11524. window.addEventListener("deviceorientation", this._orientationChanged);
  11525. };
  11526. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11527. this._initialOrientationGamma = null;
  11528. };
  11529. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11530. if (!this._initialOrientationGamma) {
  11531. this._initialOrientationGamma = evt.gamma;
  11532. this._initialOrientationBeta = evt.beta;
  11533. }
  11534. this._orientationGamma = evt.gamma;
  11535. this._orientationBeta = evt.beta;
  11536. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11537. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11538. };
  11539. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11540. window.removeEventListener("resize", this._resetOrientationGamma);
  11541. window.removeEventListener("deviceorientation", this._orientationChanged);
  11542. this._orientationGamma = 0;
  11543. this._orientationBeta = 0;
  11544. this._initialOrientationGamma = 0;
  11545. this._initialOrientationBeta = 0;
  11546. };
  11547. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11548. if (!this._offsetX) {
  11549. return;
  11550. }
  11551. var camera = this.camera;
  11552. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11553. var speed = camera._computeLocalCameraSpeed();
  11554. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11555. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11556. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11557. };
  11558. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11559. return "FreeCameraDeviceOrientationInput";
  11560. };
  11561. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11562. return "deviceOrientation";
  11563. };
  11564. __decorate([
  11565. BABYLON.serialize()
  11566. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11567. __decorate([
  11568. BABYLON.serialize()
  11569. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11570. return FreeCameraDeviceOrientationInput;
  11571. })();
  11572. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11573. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11574. })(BABYLON || (BABYLON = {}));
  11575. var BABYLON;
  11576. (function (BABYLON) {
  11577. var FreeCameraVRDeviceOrientationInput = (function () {
  11578. function FreeCameraVRDeviceOrientationInput() {
  11579. this.alphaCorrection = 1;
  11580. this.betaCorrection = 1;
  11581. this.gammaCorrection = 1;
  11582. this._alpha = 0;
  11583. this._beta = 0;
  11584. this._gamma = 0;
  11585. this._dirty = false;
  11586. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11587. }
  11588. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11589. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11590. };
  11591. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11592. var camera = this.camera;
  11593. this._alpha = +evt.alpha | 0;
  11594. this._beta = +evt.beta | 0;
  11595. this._gamma = +evt.gamma | 0;
  11596. this._dirty = true;
  11597. };
  11598. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  11599. if (this._dirty) {
  11600. this._dirty = false;
  11601. var rotationX = this._gamma;
  11602. if (rotationX < 0) {
  11603. rotationX = 90 + rotationX;
  11604. }
  11605. else {
  11606. // Incline it in the correct angle.
  11607. rotationX = 270 - rotationX;
  11608. }
  11609. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  11610. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  11611. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  11612. }
  11613. };
  11614. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  11615. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11616. };
  11617. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  11618. return "FreeCameraVRDeviceOrientationInput";
  11619. };
  11620. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  11621. return "VRDeviceOrientation";
  11622. };
  11623. return FreeCameraVRDeviceOrientationInput;
  11624. })();
  11625. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  11626. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  11627. })(BABYLON || (BABYLON = {}));
  11628. var BABYLON;
  11629. (function (BABYLON) {
  11630. var FreeCameraGamepadInput = (function () {
  11631. function FreeCameraGamepadInput() {
  11632. this.gamepadAngularSensibility = 200;
  11633. this.gamepadMoveSensibility = 40;
  11634. }
  11635. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  11636. var _this = this;
  11637. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11638. };
  11639. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  11640. this._gamepads.dispose();
  11641. this.gamepad = null;
  11642. };
  11643. FreeCameraGamepadInput.prototype.checkInputs = function () {
  11644. if (this.gamepad) {
  11645. var camera = this.camera;
  11646. var LSValues = this.gamepad.leftStick;
  11647. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  11648. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  11649. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11650. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11651. var RSValues = this.gamepad.rightStick;
  11652. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  11653. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  11654. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11655. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11656. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11657. var speed = camera._computeLocalCameraSpeed() * 50.0;
  11658. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11659. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11660. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11661. }
  11662. };
  11663. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  11664. // Only the first gamepad can control the camera
  11665. if (gamepad.index === 0) {
  11666. this.gamepad = gamepad;
  11667. }
  11668. };
  11669. FreeCameraGamepadInput.prototype.getTypeName = function () {
  11670. return "FreeCameraGamepadInput";
  11671. };
  11672. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  11673. return "gamepad";
  11674. };
  11675. __decorate([
  11676. BABYLON.serialize()
  11677. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  11678. __decorate([
  11679. BABYLON.serialize()
  11680. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  11681. return FreeCameraGamepadInput;
  11682. })();
  11683. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  11684. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  11685. })(BABYLON || (BABYLON = {}));
  11686. var BABYLON;
  11687. (function (BABYLON) {
  11688. var FreeCameraVirtualJoystickInput = (function () {
  11689. function FreeCameraVirtualJoystickInput() {
  11690. }
  11691. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  11692. return this._leftjoystick;
  11693. };
  11694. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  11695. return this._rightjoystick;
  11696. };
  11697. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  11698. if (this._leftjoystick) {
  11699. var camera = this.camera;
  11700. var speed = camera._computeLocalCameraSpeed() * 50;
  11701. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11702. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  11703. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11704. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  11705. if (!this._leftjoystick.pressed) {
  11706. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  11707. }
  11708. if (!this._rightjoystick.pressed) {
  11709. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  11710. }
  11711. }
  11712. };
  11713. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  11714. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  11715. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  11716. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  11717. this._leftjoystick.setJoystickSensibility(0.15);
  11718. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  11719. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  11720. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  11721. this._rightjoystick.reverseUpDown = true;
  11722. this._rightjoystick.setJoystickSensibility(0.05);
  11723. this._rightjoystick.setJoystickColor("yellow");
  11724. };
  11725. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  11726. this._leftjoystick.releaseCanvas();
  11727. this._rightjoystick.releaseCanvas();
  11728. };
  11729. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  11730. return "FreeCameraVirtualJoystickInput";
  11731. };
  11732. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  11733. return "virtualJoystick";
  11734. };
  11735. return FreeCameraVirtualJoystickInput;
  11736. })();
  11737. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  11738. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  11739. })(BABYLON || (BABYLON = {}));
  11740. var BABYLON;
  11741. (function (BABYLON) {
  11742. var ArcRotateCameraKeyboardMoveInput = (function () {
  11743. function ArcRotateCameraKeyboardMoveInput() {
  11744. this._keys = [];
  11745. this.keysUp = [38];
  11746. this.keysDown = [40];
  11747. this.keysLeft = [37];
  11748. this.keysRight = [39];
  11749. }
  11750. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11751. var _this = this;
  11752. this._onKeyDown = function (evt) {
  11753. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11754. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11755. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11756. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11757. var index = _this._keys.indexOf(evt.keyCode);
  11758. if (index === -1) {
  11759. _this._keys.push(evt.keyCode);
  11760. }
  11761. if (evt.preventDefault) {
  11762. if (!noPreventDefault) {
  11763. evt.preventDefault();
  11764. }
  11765. }
  11766. }
  11767. };
  11768. this._onKeyUp = function (evt) {
  11769. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11770. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11771. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11772. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11773. var index = _this._keys.indexOf(evt.keyCode);
  11774. if (index >= 0) {
  11775. _this._keys.splice(index, 1);
  11776. }
  11777. if (evt.preventDefault) {
  11778. if (!noPreventDefault) {
  11779. evt.preventDefault();
  11780. }
  11781. }
  11782. }
  11783. };
  11784. this._onLostFocus = function () {
  11785. _this._keys = [];
  11786. };
  11787. BABYLON.Tools.RegisterTopRootEvents([
  11788. { name: "keydown", handler: this._onKeyDown },
  11789. { name: "keyup", handler: this._onKeyUp },
  11790. { name: "blur", handler: this._onLostFocus }
  11791. ]);
  11792. };
  11793. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11794. BABYLON.Tools.UnregisterTopRootEvents([
  11795. { name: "keydown", handler: this._onKeyDown },
  11796. { name: "keyup", handler: this._onKeyUp },
  11797. { name: "blur", handler: this._onLostFocus }
  11798. ]);
  11799. };
  11800. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11801. var camera = this.camera;
  11802. for (var index = 0; index < this._keys.length; index++) {
  11803. var keyCode = this._keys[index];
  11804. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11805. camera.inertialAlphaOffset -= 0.01;
  11806. }
  11807. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11808. camera.inertialBetaOffset -= 0.01;
  11809. }
  11810. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11811. camera.inertialAlphaOffset += 0.01;
  11812. }
  11813. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11814. camera.inertialBetaOffset += 0.01;
  11815. }
  11816. }
  11817. };
  11818. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11819. return "ArcRotateCameraKeyboardMoveInput";
  11820. };
  11821. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11822. return "keyboard";
  11823. };
  11824. __decorate([
  11825. BABYLON.serialize()
  11826. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11827. __decorate([
  11828. BABYLON.serialize()
  11829. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11830. __decorate([
  11831. BABYLON.serialize()
  11832. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11833. __decorate([
  11834. BABYLON.serialize()
  11835. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11836. return ArcRotateCameraKeyboardMoveInput;
  11837. })();
  11838. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  11839. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  11840. })(BABYLON || (BABYLON = {}));
  11841. var BABYLON;
  11842. (function (BABYLON) {
  11843. var ArcRotateCameraMouseWheelInput = (function () {
  11844. function ArcRotateCameraMouseWheelInput() {
  11845. this.wheelPrecision = 3.0;
  11846. }
  11847. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  11848. var _this = this;
  11849. this._wheel = function (event) {
  11850. var delta = 0;
  11851. if (event.wheelDelta) {
  11852. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11853. }
  11854. else if (event.detail) {
  11855. delta = -event.detail / _this.wheelPrecision;
  11856. }
  11857. if (delta)
  11858. _this.camera.inertialRadiusOffset += delta;
  11859. if (event.preventDefault) {
  11860. if (!_this.camera._noPreventDefault) {
  11861. event.preventDefault();
  11862. }
  11863. }
  11864. };
  11865. element.addEventListener('mousewheel', this._wheel, false);
  11866. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11867. };
  11868. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  11869. if (this._wheel && element) {
  11870. element.removeEventListener('mousewheel', this._wheel);
  11871. element.removeEventListener('DOMMouseScroll', this._wheel);
  11872. }
  11873. };
  11874. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  11875. return "ArcRotateCameraMouseWheelInput";
  11876. };
  11877. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  11878. return "mousewheel";
  11879. };
  11880. __decorate([
  11881. BABYLON.serialize()
  11882. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  11883. return ArcRotateCameraMouseWheelInput;
  11884. })();
  11885. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  11886. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  11887. })(BABYLON || (BABYLON = {}));
  11888. var BABYLON;
  11889. (function (BABYLON) {
  11890. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11891. var ArcRotateCameraPointersInput = (function () {
  11892. function ArcRotateCameraPointersInput() {
  11893. this._isRightClick = false;
  11894. this._isCtrlPushed = false;
  11895. this.pinchInwards = true;
  11896. this.angularSensibilityX = 1000.0;
  11897. this.angularSensibilityY = 1000.0;
  11898. this.pinchPrecision = 6.0;
  11899. this.panningSensibility = 50.0;
  11900. }
  11901. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  11902. var _this = this;
  11903. var engine = this.camera.getEngine();
  11904. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11905. var pointers = new BABYLON.SmartCollection();
  11906. var previousPinchDistance = 0;
  11907. if (!this.camera._useCtrlForPanning) {
  11908. element.addEventListener("contextmenu", this._onContextMenu, false);
  11909. }
  11910. this._onLostFocus = function () {
  11911. //this._keys = [];
  11912. pointers.empty();
  11913. previousPinchDistance = 0;
  11914. cacheSoloPointer = null;
  11915. };
  11916. this._onKeyDown = function (evt) {
  11917. _this._isCtrlPushed = evt.ctrlKey;
  11918. };
  11919. this._onKeyUp = function (evt) {
  11920. _this._isCtrlPushed = evt.ctrlKey;
  11921. };
  11922. this._onPointerDown = function (evt) {
  11923. // Manage panning with right click
  11924. _this._isRightClick = evt.button === 2;
  11925. // manage pointers
  11926. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11927. cacheSoloPointer = pointers.item(evt.pointerId);
  11928. if (!noPreventDefault) {
  11929. evt.preventDefault();
  11930. }
  11931. };
  11932. this._onPointerUp = function (evt) {
  11933. cacheSoloPointer = null;
  11934. previousPinchDistance = 0;
  11935. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11936. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11937. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11938. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11939. pointers.empty();
  11940. if (!noPreventDefault) {
  11941. evt.preventDefault();
  11942. }
  11943. };
  11944. this._onContextMenu = function (evt) {
  11945. evt.preventDefault();
  11946. };
  11947. this._onPointerMove = function (evt) {
  11948. if (!noPreventDefault) {
  11949. evt.preventDefault();
  11950. }
  11951. switch (pointers.count) {
  11952. case 1:
  11953. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  11954. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11955. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11956. }
  11957. else {
  11958. var offsetX = evt.clientX - cacheSoloPointer.x;
  11959. var offsetY = evt.clientY - cacheSoloPointer.y;
  11960. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11961. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11962. }
  11963. cacheSoloPointer.x = evt.clientX;
  11964. cacheSoloPointer.y = evt.clientY;
  11965. break;
  11966. case 2:
  11967. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11968. pointers.item(evt.pointerId).x = evt.clientX;
  11969. pointers.item(evt.pointerId).y = evt.clientY;
  11970. var direction = _this.pinchInwards ? 1 : -1;
  11971. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11972. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11973. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11974. if (previousPinchDistance === 0) {
  11975. previousPinchDistance = pinchSquaredDistance;
  11976. return;
  11977. }
  11978. if (pinchSquaredDistance !== previousPinchDistance) {
  11979. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11980. previousPinchDistance = pinchSquaredDistance;
  11981. }
  11982. break;
  11983. default:
  11984. if (pointers.item(evt.pointerId)) {
  11985. pointers.item(evt.pointerId).x = evt.clientX;
  11986. pointers.item(evt.pointerId).y = evt.clientY;
  11987. }
  11988. }
  11989. };
  11990. this._onMouseMove = function (evt) {
  11991. if (!engine.isPointerLock) {
  11992. return;
  11993. }
  11994. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11995. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11996. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11997. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11998. if (!noPreventDefault) {
  11999. evt.preventDefault();
  12000. }
  12001. };
  12002. this._onGestureStart = function (e) {
  12003. if (window.MSGesture === undefined) {
  12004. return;
  12005. }
  12006. if (!_this._MSGestureHandler) {
  12007. _this._MSGestureHandler = new MSGesture();
  12008. _this._MSGestureHandler.target = element;
  12009. }
  12010. _this._MSGestureHandler.addPointer(e.pointerId);
  12011. };
  12012. this._onGesture = function (e) {
  12013. _this.camera.radius *= e.scale;
  12014. if (e.preventDefault) {
  12015. if (!noPreventDefault) {
  12016. e.stopPropagation();
  12017. e.preventDefault();
  12018. }
  12019. }
  12020. };
  12021. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12022. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12023. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12024. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12025. element.addEventListener("mousemove", this._onMouseMove, false);
  12026. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12027. element.addEventListener("MSGestureChange", this._onGesture, false);
  12028. BABYLON.Tools.RegisterTopRootEvents([
  12029. { name: "blur", handler: this._onLostFocus }
  12030. ]);
  12031. };
  12032. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12033. this._MSGestureHandler = null;
  12034. if (element && this._onPointerDown) {
  12035. element.removeEventListener("contextmenu", this._onContextMenu);
  12036. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12037. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12038. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12039. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12040. element.removeEventListener("mousemove", this._onMouseMove);
  12041. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12042. element.removeEventListener("MSGestureChange", this._onGesture);
  12043. }
  12044. BABYLON.Tools.UnregisterTopRootEvents([
  12045. { name: "blur", handler: this._onLostFocus }
  12046. ]);
  12047. };
  12048. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12049. return "ArcRotateCameraPointersInput";
  12050. };
  12051. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12052. return "pointers";
  12053. };
  12054. __decorate([
  12055. BABYLON.serialize()
  12056. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12057. __decorate([
  12058. BABYLON.serialize()
  12059. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12060. __decorate([
  12061. BABYLON.serialize()
  12062. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12063. __decorate([
  12064. BABYLON.serialize()
  12065. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12066. return ArcRotateCameraPointersInput;
  12067. })();
  12068. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12069. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12070. })(BABYLON || (BABYLON = {}));
  12071. var BABYLON;
  12072. (function (BABYLON) {
  12073. var ArcRotateCameraGamepadInput = (function () {
  12074. function ArcRotateCameraGamepadInput() {
  12075. this.gamepadRotationSensibility = 80;
  12076. this.gamepadMoveSensibility = 40;
  12077. }
  12078. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12079. var _this = this;
  12080. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12081. };
  12082. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12083. this._gamepads.dispose();
  12084. this.gamepad = null;
  12085. };
  12086. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12087. if (this.gamepad) {
  12088. var camera = this.camera;
  12089. var RSValues = this.gamepad.rightStick;
  12090. if (RSValues.x != 0) {
  12091. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12092. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12093. camera.inertialAlphaOffset += normalizedRX;
  12094. }
  12095. }
  12096. if (RSValues.y != 0) {
  12097. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12098. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12099. camera.inertialBetaOffset += normalizedRY;
  12100. }
  12101. }
  12102. var LSValues = this.gamepad.leftStick;
  12103. if (LSValues.y != 0) {
  12104. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12105. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12106. this.camera.inertialRadiusOffset -= normalizedLY;
  12107. }
  12108. }
  12109. }
  12110. };
  12111. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12112. // Only the first gamepad can control the camera
  12113. if (gamepad.index === 0) {
  12114. this.gamepad = gamepad;
  12115. }
  12116. };
  12117. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12118. return "ArcRotateCameraGamepadInput";
  12119. };
  12120. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12121. return "gamepad";
  12122. };
  12123. __decorate([
  12124. BABYLON.serialize()
  12125. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12126. __decorate([
  12127. BABYLON.serialize()
  12128. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12129. return ArcRotateCameraGamepadInput;
  12130. })();
  12131. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12132. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12133. })(BABYLON || (BABYLON = {}));
  12134. var BABYLON;
  12135. (function (BABYLON) {
  12136. var TargetCamera = (function (_super) {
  12137. __extends(TargetCamera, _super);
  12138. function TargetCamera(name, position, scene) {
  12139. _super.call(this, name, position, scene);
  12140. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12141. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12142. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12143. this.speed = 2.0;
  12144. this.noRotationConstraint = false;
  12145. this.lockedTarget = null;
  12146. this._currentTarget = BABYLON.Vector3.Zero();
  12147. this._viewMatrix = BABYLON.Matrix.Zero();
  12148. this._camMatrix = BABYLON.Matrix.Zero();
  12149. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12150. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12151. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12152. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12153. this._lookAtTemp = BABYLON.Matrix.Zero();
  12154. this._tempMatrix = BABYLON.Matrix.Zero();
  12155. }
  12156. TargetCamera.prototype.getFrontPosition = function (distance) {
  12157. var direction = this.getTarget().subtract(this.position);
  12158. direction.normalize();
  12159. direction.scaleInPlace(distance);
  12160. return this.globalPosition.add(direction);
  12161. };
  12162. TargetCamera.prototype._getLockedTargetPosition = function () {
  12163. if (!this.lockedTarget) {
  12164. return null;
  12165. }
  12166. return this.lockedTarget.position || this.lockedTarget;
  12167. };
  12168. // Cache
  12169. TargetCamera.prototype._initCache = function () {
  12170. _super.prototype._initCache.call(this);
  12171. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12172. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12173. };
  12174. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12175. if (!ignoreParentClass) {
  12176. _super.prototype._updateCache.call(this);
  12177. }
  12178. var lockedTargetPosition = this._getLockedTargetPosition();
  12179. if (!lockedTargetPosition) {
  12180. this._cache.lockedTarget = null;
  12181. }
  12182. else {
  12183. if (!this._cache.lockedTarget) {
  12184. this._cache.lockedTarget = lockedTargetPosition.clone();
  12185. }
  12186. else {
  12187. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12188. }
  12189. }
  12190. this._cache.rotation.copyFrom(this.rotation);
  12191. };
  12192. // Synchronized
  12193. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12194. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12195. return false;
  12196. }
  12197. var lockedTargetPosition = this._getLockedTargetPosition();
  12198. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12199. && this._cache.rotation.equals(this.rotation);
  12200. };
  12201. // Methods
  12202. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12203. var engine = this.getEngine();
  12204. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12205. };
  12206. // Target
  12207. TargetCamera.prototype.setTarget = function (target) {
  12208. this.upVector.normalize();
  12209. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12210. this._camMatrix.invert();
  12211. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12212. var vDir = target.subtract(this.position);
  12213. if (vDir.x >= 0.0) {
  12214. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12215. }
  12216. else {
  12217. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12218. }
  12219. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12220. if (isNaN(this.rotation.x)) {
  12221. this.rotation.x = 0;
  12222. }
  12223. if (isNaN(this.rotation.y)) {
  12224. this.rotation.y = 0;
  12225. }
  12226. if (isNaN(this.rotation.z)) {
  12227. this.rotation.z = 0;
  12228. }
  12229. };
  12230. TargetCamera.prototype.getTarget = function () {
  12231. return this._currentTarget;
  12232. };
  12233. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12234. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12235. };
  12236. TargetCamera.prototype._updatePosition = function () {
  12237. this.position.addInPlace(this.cameraDirection);
  12238. };
  12239. TargetCamera.prototype._checkInputs = function () {
  12240. var needToMove = this._decideIfNeedsToMove();
  12241. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12242. // Move
  12243. if (needToMove) {
  12244. this._updatePosition();
  12245. }
  12246. // Rotate
  12247. if (needToRotate) {
  12248. this.rotation.x += this.cameraRotation.x;
  12249. this.rotation.y += this.cameraRotation.y;
  12250. if (!this.noRotationConstraint) {
  12251. var limit = (Math.PI / 2) * 0.95;
  12252. if (this.rotation.x > limit)
  12253. this.rotation.x = limit;
  12254. if (this.rotation.x < -limit)
  12255. this.rotation.x = -limit;
  12256. }
  12257. }
  12258. // Inertia
  12259. if (needToMove) {
  12260. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12261. this.cameraDirection.x = 0;
  12262. }
  12263. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12264. this.cameraDirection.y = 0;
  12265. }
  12266. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12267. this.cameraDirection.z = 0;
  12268. }
  12269. this.cameraDirection.scaleInPlace(this.inertia);
  12270. }
  12271. if (needToRotate) {
  12272. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12273. this.cameraRotation.x = 0;
  12274. }
  12275. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12276. this.cameraRotation.y = 0;
  12277. }
  12278. this.cameraRotation.scaleInPlace(this.inertia);
  12279. }
  12280. _super.prototype._checkInputs.call(this);
  12281. };
  12282. TargetCamera.prototype._getViewMatrix = function () {
  12283. if (!this.lockedTarget) {
  12284. // Compute
  12285. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12286. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12287. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12288. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12289. this._lookAtTemp.invert();
  12290. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12291. }
  12292. else {
  12293. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12294. }
  12295. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12296. // Computing target and final matrix
  12297. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12298. }
  12299. else {
  12300. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12301. }
  12302. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12303. return this._viewMatrix;
  12304. };
  12305. TargetCamera.prototype._getVRViewMatrix = function () {
  12306. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12307. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12308. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12309. // Computing target and final matrix
  12310. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12311. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12312. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12313. return this._viewMatrix;
  12314. };
  12315. /**
  12316. * @override
  12317. * Override Camera.createRigCamera
  12318. */
  12319. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12320. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12321. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12322. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12323. rigCamera._cameraRigParams = {};
  12324. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12325. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12326. }
  12327. return rigCamera;
  12328. }
  12329. return null;
  12330. };
  12331. /**
  12332. * @override
  12333. * Override Camera._updateRigCameras
  12334. */
  12335. TargetCamera.prototype._updateRigCameras = function () {
  12336. switch (this.cameraRigMode) {
  12337. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12339. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12341. case BABYLON.Camera.RIG_MODE_VR:
  12342. var camLeft = this._rigCameras[0];
  12343. var camRight = this._rigCameras[1];
  12344. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12345. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12346. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12347. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12348. camLeft.position.copyFrom(this.position);
  12349. camRight.position.copyFrom(this.position);
  12350. }
  12351. else {
  12352. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12353. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12354. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12355. camLeft.setTarget(this.getTarget());
  12356. camRight.setTarget(this.getTarget());
  12357. }
  12358. break;
  12359. }
  12360. _super.prototype._updateRigCameras.call(this);
  12361. };
  12362. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12363. if (!this._rigCamTransformMatrix) {
  12364. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12365. }
  12366. var target = this.getTarget();
  12367. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12368. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12369. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12370. };
  12371. TargetCamera.prototype.getTypeName = function () {
  12372. return "TargetCamera";
  12373. };
  12374. __decorate([
  12375. BABYLON.serializeAsVector3()
  12376. ], TargetCamera.prototype, "rotation", void 0);
  12377. __decorate([
  12378. BABYLON.serialize()
  12379. ], TargetCamera.prototype, "speed", void 0);
  12380. __decorate([
  12381. BABYLON.serializeAsMeshReference("lockedTargetId")
  12382. ], TargetCamera.prototype, "lockedTarget", void 0);
  12383. return TargetCamera;
  12384. })(BABYLON.Camera);
  12385. BABYLON.TargetCamera = TargetCamera;
  12386. })(BABYLON || (BABYLON = {}));
  12387. var BABYLON;
  12388. (function (BABYLON) {
  12389. var FreeCamera = (function (_super) {
  12390. __extends(FreeCamera, _super);
  12391. function FreeCamera(name, position, scene) {
  12392. var _this = this;
  12393. _super.call(this, name, position, scene);
  12394. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12395. this.checkCollisions = false;
  12396. this.applyGravity = false;
  12397. this._collider = new BABYLON.Collider();
  12398. this._needMoveForGravity = false;
  12399. this._oldPosition = BABYLON.Vector3.Zero();
  12400. this._diffPosition = BABYLON.Vector3.Zero();
  12401. this._newPosition = BABYLON.Vector3.Zero();
  12402. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12403. if (collidedMesh === void 0) { collidedMesh = null; }
  12404. //TODO move this to the collision coordinator!
  12405. if (_this.getScene().workerCollisions)
  12406. newPosition.multiplyInPlace(_this._collider.radius);
  12407. var updatePosition = function (newPos) {
  12408. _this._newPosition.copyFrom(newPos);
  12409. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12410. var oldPosition = _this.position.clone();
  12411. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12412. _this.position.addInPlace(_this._diffPosition);
  12413. if (_this.onCollide && collidedMesh) {
  12414. _this.onCollide(collidedMesh);
  12415. }
  12416. }
  12417. };
  12418. updatePosition(newPosition);
  12419. };
  12420. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12421. this.inputs.addKeyboard().addMouse();
  12422. }
  12423. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12424. //-- begin properties for backward compatibility for inputs
  12425. get: function () {
  12426. var mouse = this.inputs.attached["mouse"];
  12427. if (mouse)
  12428. return mouse.angularSensibility;
  12429. },
  12430. set: function (value) {
  12431. var mouse = this.inputs.attached["mouse"];
  12432. if (mouse)
  12433. mouse.angularSensibility = value;
  12434. },
  12435. enumerable: true,
  12436. configurable: true
  12437. });
  12438. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12439. get: function () {
  12440. var keyboard = this.inputs.attached["keyboard"];
  12441. if (keyboard)
  12442. return keyboard.keysUp;
  12443. },
  12444. set: function (value) {
  12445. var keyboard = this.inputs.attached["keyboard"];
  12446. if (keyboard)
  12447. keyboard.keysUp = value;
  12448. },
  12449. enumerable: true,
  12450. configurable: true
  12451. });
  12452. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12453. get: function () {
  12454. var keyboard = this.inputs.attached["keyboard"];
  12455. if (keyboard)
  12456. return keyboard.keysDown;
  12457. },
  12458. set: function (value) {
  12459. var keyboard = this.inputs.attached["keyboard"];
  12460. if (keyboard)
  12461. keyboard.keysDown = value;
  12462. },
  12463. enumerable: true,
  12464. configurable: true
  12465. });
  12466. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12467. get: function () {
  12468. var keyboard = this.inputs.attached["keyboard"];
  12469. if (keyboard)
  12470. return keyboard.keysLeft;
  12471. },
  12472. set: function (value) {
  12473. var keyboard = this.inputs.attached["keyboard"];
  12474. if (keyboard)
  12475. keyboard.keysLeft = value;
  12476. },
  12477. enumerable: true,
  12478. configurable: true
  12479. });
  12480. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12481. get: function () {
  12482. var keyboard = this.inputs.attached["keyboard"];
  12483. if (keyboard)
  12484. return keyboard.keysRight;
  12485. },
  12486. set: function (value) {
  12487. var keyboard = this.inputs.attached["keyboard"];
  12488. if (keyboard)
  12489. keyboard.keysRight = value;
  12490. },
  12491. enumerable: true,
  12492. configurable: true
  12493. });
  12494. // Controls
  12495. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12496. if (this._attachedElement) {
  12497. return;
  12498. }
  12499. this._noPreventDefault = noPreventDefault;
  12500. this._attachedElement = element;
  12501. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12502. this.inputs.attachElement(element, noPreventDefault);
  12503. };
  12504. FreeCamera.prototype.detachControl = function (element) {
  12505. if (this._attachedElement !== element) {
  12506. return;
  12507. }
  12508. this.inputs.detachElement(this._attachedElement);
  12509. this._attachedElement = null;
  12510. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12511. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12512. };
  12513. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12514. var globalPosition;
  12515. if (this.parent) {
  12516. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12517. }
  12518. else {
  12519. globalPosition = this.position;
  12520. }
  12521. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12522. this._collider.radius = this.ellipsoid;
  12523. //no need for clone, as long as gravity is not on.
  12524. var actualVelocity = velocity;
  12525. //add gravity to the velocity to prevent the dual-collision checking
  12526. if (this.applyGravity) {
  12527. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12528. actualVelocity = velocity.add(this.getScene().gravity);
  12529. }
  12530. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12531. };
  12532. FreeCamera.prototype._checkInputs = function () {
  12533. if (!this._localDirection) {
  12534. this._localDirection = BABYLON.Vector3.Zero();
  12535. this._transformedDirection = BABYLON.Vector3.Zero();
  12536. }
  12537. this.inputs.checkInputs();
  12538. _super.prototype._checkInputs.call(this);
  12539. };
  12540. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12541. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12542. };
  12543. FreeCamera.prototype._updatePosition = function () {
  12544. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  12545. this._collideWithWorld(this.cameraDirection);
  12546. }
  12547. else {
  12548. this.position.addInPlace(this.cameraDirection);
  12549. }
  12550. };
  12551. FreeCamera.prototype.dispose = function () {
  12552. this.inputs.clear();
  12553. _super.prototype.dispose.call(this);
  12554. };
  12555. FreeCamera.prototype.getTypeName = function () {
  12556. return "FreeCamera";
  12557. };
  12558. __decorate([
  12559. BABYLON.serializeAsVector3()
  12560. ], FreeCamera.prototype, "ellipsoid", void 0);
  12561. __decorate([
  12562. BABYLON.serialize()
  12563. ], FreeCamera.prototype, "checkCollisions", void 0);
  12564. __decorate([
  12565. BABYLON.serialize()
  12566. ], FreeCamera.prototype, "applyGravity", void 0);
  12567. return FreeCamera;
  12568. })(BABYLON.TargetCamera);
  12569. BABYLON.FreeCamera = FreeCamera;
  12570. })(BABYLON || (BABYLON = {}));
  12571. var BABYLON;
  12572. (function (BABYLON) {
  12573. var FreeCameraInputsManager = (function (_super) {
  12574. __extends(FreeCameraInputsManager, _super);
  12575. function FreeCameraInputsManager(camera) {
  12576. _super.call(this, camera);
  12577. }
  12578. FreeCameraInputsManager.prototype.addKeyboard = function () {
  12579. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  12580. return this;
  12581. };
  12582. FreeCameraInputsManager.prototype.addMouse = function () {
  12583. this.add(new BABYLON.FreeCameraMouseInput());
  12584. return this;
  12585. };
  12586. FreeCameraInputsManager.prototype.addGamepad = function () {
  12587. this.add(new BABYLON.FreeCameraGamepadInput());
  12588. return this;
  12589. };
  12590. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  12591. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  12592. return this;
  12593. };
  12594. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  12595. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  12596. return this;
  12597. };
  12598. FreeCameraInputsManager.prototype.addTouch = function () {
  12599. this.add(new BABYLON.FreeCameraTouchInput());
  12600. return this;
  12601. };
  12602. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  12603. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  12604. return this;
  12605. };
  12606. return FreeCameraInputsManager;
  12607. })(BABYLON.CameraInputsManager);
  12608. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  12609. })(BABYLON || (BABYLON = {}));
  12610. var BABYLON;
  12611. (function (BABYLON) {
  12612. var FollowCamera = (function (_super) {
  12613. __extends(FollowCamera, _super);
  12614. function FollowCamera(name, position, scene, target) {
  12615. _super.call(this, name, position, scene);
  12616. this.radius = 12;
  12617. this.rotationOffset = 0;
  12618. this.heightOffset = 4;
  12619. this.cameraAcceleration = 0.05;
  12620. this.maxCameraSpeed = 20;
  12621. this.target = target;
  12622. }
  12623. FollowCamera.prototype.getRadians = function (degrees) {
  12624. return degrees * Math.PI / 180;
  12625. };
  12626. FollowCamera.prototype.follow = function (cameraTarget) {
  12627. if (!cameraTarget)
  12628. return;
  12629. var yRotation;
  12630. if (cameraTarget.rotationQuaternion) {
  12631. var rotMatrix = new BABYLON.Matrix();
  12632. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  12633. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  12634. }
  12635. else {
  12636. yRotation = cameraTarget.rotation.y;
  12637. }
  12638. var radians = this.getRadians(this.rotationOffset) + yRotation;
  12639. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  12640. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  12641. var dx = targetX - this.position.x;
  12642. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  12643. var dz = (targetZ) - this.position.z;
  12644. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  12645. var vy = dy * this.cameraAcceleration;
  12646. var vz = dz * this.cameraAcceleration * 2;
  12647. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  12648. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12649. }
  12650. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  12651. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12652. }
  12653. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  12654. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12655. }
  12656. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  12657. this.setTarget(cameraTarget.position);
  12658. };
  12659. FollowCamera.prototype._checkInputs = function () {
  12660. _super.prototype._checkInputs.call(this);
  12661. this.follow(this.target);
  12662. };
  12663. FollowCamera.prototype.getTypeName = function () {
  12664. return "FollowCamera";
  12665. };
  12666. __decorate([
  12667. BABYLON.serialize()
  12668. ], FollowCamera.prototype, "radius", void 0);
  12669. __decorate([
  12670. BABYLON.serialize()
  12671. ], FollowCamera.prototype, "rotationOffset", void 0);
  12672. __decorate([
  12673. BABYLON.serialize()
  12674. ], FollowCamera.prototype, "heightOffset", void 0);
  12675. __decorate([
  12676. BABYLON.serialize()
  12677. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  12678. __decorate([
  12679. BABYLON.serialize()
  12680. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  12681. __decorate([
  12682. BABYLON.serializeAsMeshReference("lockedTargetId")
  12683. ], FollowCamera.prototype, "target", void 0);
  12684. return FollowCamera;
  12685. })(BABYLON.TargetCamera);
  12686. BABYLON.FollowCamera = FollowCamera;
  12687. var ArcFollowCamera = (function (_super) {
  12688. __extends(ArcFollowCamera, _super);
  12689. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  12690. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12691. this.alpha = alpha;
  12692. this.beta = beta;
  12693. this.radius = radius;
  12694. this.target = target;
  12695. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  12696. this.follow();
  12697. }
  12698. ArcFollowCamera.prototype.follow = function () {
  12699. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  12700. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  12701. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  12702. this.position = this.target.position.add(this._cartesianCoordinates);
  12703. this.setTarget(this.target.position);
  12704. };
  12705. ArcFollowCamera.prototype._checkInputs = function () {
  12706. _super.prototype._checkInputs.call(this);
  12707. this.follow();
  12708. };
  12709. ArcFollowCamera.prototype.getTypeName = function () {
  12710. return "ArcFollowCamera";
  12711. };
  12712. return ArcFollowCamera;
  12713. })(BABYLON.TargetCamera);
  12714. BABYLON.ArcFollowCamera = ArcFollowCamera;
  12715. })(BABYLON || (BABYLON = {}));
  12716. var BABYLON;
  12717. (function (BABYLON) {
  12718. // We're mainly based on the logic defined into the FreeCamera code
  12719. var TouchCamera = (function (_super) {
  12720. __extends(TouchCamera, _super);
  12721. //-- end properties for backward compatibility for inputs
  12722. function TouchCamera(name, position, scene) {
  12723. _super.call(this, name, position, scene);
  12724. this.inputs.addTouch();
  12725. }
  12726. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  12727. //-- Begin properties for backward compatibility for inputs
  12728. get: function () {
  12729. var touch = this.inputs.attached["touch"];
  12730. if (touch)
  12731. return touch.touchAngularSensibility;
  12732. },
  12733. set: function (value) {
  12734. var touch = this.inputs.attached["touch"];
  12735. if (touch)
  12736. touch.touchAngularSensibility = value;
  12737. },
  12738. enumerable: true,
  12739. configurable: true
  12740. });
  12741. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  12742. get: function () {
  12743. var touch = this.inputs.attached["touch"];
  12744. if (touch)
  12745. return touch.touchMoveSensibility;
  12746. },
  12747. set: function (value) {
  12748. var touch = this.inputs.attached["touch"];
  12749. if (touch)
  12750. touch.touchMoveSensibility = value;
  12751. },
  12752. enumerable: true,
  12753. configurable: true
  12754. });
  12755. TouchCamera.prototype.getTypeName = function () {
  12756. return "TouchCamera";
  12757. };
  12758. return TouchCamera;
  12759. })(BABYLON.FreeCamera);
  12760. BABYLON.TouchCamera = TouchCamera;
  12761. })(BABYLON || (BABYLON = {}));
  12762. var BABYLON;
  12763. (function (BABYLON) {
  12764. var ArcRotateCamera = (function (_super) {
  12765. __extends(ArcRotateCamera, _super);
  12766. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  12767. var _this = this;
  12768. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12769. this.inertialAlphaOffset = 0;
  12770. this.inertialBetaOffset = 0;
  12771. this.inertialRadiusOffset = 0;
  12772. this.lowerAlphaLimit = null;
  12773. this.upperAlphaLimit = null;
  12774. this.lowerBetaLimit = 0.01;
  12775. this.upperBetaLimit = Math.PI;
  12776. this.lowerRadiusLimit = null;
  12777. this.upperRadiusLimit = null;
  12778. this.inertialPanningX = 0;
  12779. this.inertialPanningY = 0;
  12780. //-- end properties for backward compatibility for inputs
  12781. this.zoomOnFactor = 1;
  12782. this.targetScreenOffset = BABYLON.Vector2.Zero();
  12783. this.allowUpsideDown = true;
  12784. this._viewMatrix = new BABYLON.Matrix();
  12785. // Panning
  12786. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  12787. this.checkCollisions = false;
  12788. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12789. this._collider = new BABYLON.Collider();
  12790. this._previousPosition = BABYLON.Vector3.Zero();
  12791. this._collisionVelocity = BABYLON.Vector3.Zero();
  12792. this._newPosition = BABYLON.Vector3.Zero();
  12793. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12794. if (collidedMesh === void 0) { collidedMesh = null; }
  12795. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  12796. newPosition.multiplyInPlace(_this._collider.radius);
  12797. }
  12798. if (!collidedMesh) {
  12799. _this._previousPosition.copyFrom(_this.position);
  12800. }
  12801. else {
  12802. _this.setPosition(newPosition);
  12803. if (_this.onCollide) {
  12804. _this.onCollide(collidedMesh);
  12805. }
  12806. }
  12807. // Recompute because of constraints
  12808. var cosa = Math.cos(_this.alpha);
  12809. var sina = Math.sin(_this.alpha);
  12810. var cosb = Math.cos(_this.beta);
  12811. var sinb = Math.sin(_this.beta);
  12812. if (sinb === 0) {
  12813. sinb = 0.0001;
  12814. }
  12815. var target = _this._getTargetPosition();
  12816. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  12817. _this.position.copyFrom(_this._newPosition);
  12818. var up = _this.upVector;
  12819. if (_this.allowUpsideDown && _this.beta < 0) {
  12820. up = up.clone();
  12821. up = up.negate();
  12822. }
  12823. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  12824. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  12825. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  12826. _this._collisionTriggered = false;
  12827. };
  12828. if (!target) {
  12829. this.target = BABYLON.Vector3.Zero();
  12830. }
  12831. else {
  12832. this.target = target;
  12833. }
  12834. this.alpha = alpha;
  12835. this.beta = beta;
  12836. this.radius = radius;
  12837. this.getViewMatrix();
  12838. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  12839. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  12840. }
  12841. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  12842. //-- begin properties for backward compatibility for inputs
  12843. get: function () {
  12844. var pointers = this.inputs.attached["pointers"];
  12845. if (pointers)
  12846. return pointers.angularSensibilityX;
  12847. },
  12848. set: function (value) {
  12849. var pointers = this.inputs.attached["pointers"];
  12850. if (pointers) {
  12851. pointers.angularSensibilityX = value;
  12852. }
  12853. },
  12854. enumerable: true,
  12855. configurable: true
  12856. });
  12857. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  12858. get: function () {
  12859. var pointers = this.inputs.attached["pointers"];
  12860. if (pointers)
  12861. return pointers.angularSensibilityY;
  12862. },
  12863. set: function (value) {
  12864. var pointers = this.inputs.attached["pointers"];
  12865. if (pointers) {
  12866. pointers.angularSensibilityY = value;
  12867. }
  12868. },
  12869. enumerable: true,
  12870. configurable: true
  12871. });
  12872. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  12873. get: function () {
  12874. var pointers = this.inputs.attached["pointers"];
  12875. if (pointers)
  12876. return pointers.pinchPrecision;
  12877. },
  12878. set: function (value) {
  12879. var pointers = this.inputs.attached["pointers"];
  12880. if (pointers) {
  12881. pointers.pinchPrecision = value;
  12882. }
  12883. },
  12884. enumerable: true,
  12885. configurable: true
  12886. });
  12887. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  12888. get: function () {
  12889. var pointers = this.inputs.attached["pointers"];
  12890. if (pointers)
  12891. return pointers.panningSensibility;
  12892. },
  12893. set: function (value) {
  12894. var pointers = this.inputs.attached["pointers"];
  12895. if (pointers) {
  12896. pointers.panningSensibility = value;
  12897. }
  12898. },
  12899. enumerable: true,
  12900. configurable: true
  12901. });
  12902. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  12903. get: function () {
  12904. var keyboard = this.inputs.attached["keyboard"];
  12905. if (keyboard)
  12906. return keyboard.keysUp;
  12907. },
  12908. set: function (value) {
  12909. var keyboard = this.inputs.attached["keyboard"];
  12910. if (keyboard)
  12911. keyboard.keysUp = value;
  12912. },
  12913. enumerable: true,
  12914. configurable: true
  12915. });
  12916. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  12917. get: function () {
  12918. var keyboard = this.inputs.attached["keyboard"];
  12919. if (keyboard)
  12920. return keyboard.keysDown;
  12921. },
  12922. set: function (value) {
  12923. var keyboard = this.inputs.attached["keyboard"];
  12924. if (keyboard)
  12925. keyboard.keysDown = value;
  12926. },
  12927. enumerable: true,
  12928. configurable: true
  12929. });
  12930. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  12931. get: function () {
  12932. var keyboard = this.inputs.attached["keyboard"];
  12933. if (keyboard)
  12934. return keyboard.keysLeft;
  12935. },
  12936. set: function (value) {
  12937. var keyboard = this.inputs.attached["keyboard"];
  12938. if (keyboard)
  12939. keyboard.keysLeft = value;
  12940. },
  12941. enumerable: true,
  12942. configurable: true
  12943. });
  12944. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  12945. get: function () {
  12946. var keyboard = this.inputs.attached["keyboard"];
  12947. if (keyboard)
  12948. return keyboard.keysRight;
  12949. },
  12950. set: function (value) {
  12951. var keyboard = this.inputs.attached["keyboard"];
  12952. if (keyboard)
  12953. keyboard.keysRight = value;
  12954. },
  12955. enumerable: true,
  12956. configurable: true
  12957. });
  12958. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  12959. get: function () {
  12960. var mousewheel = this.inputs.attached["mousewheel"];
  12961. if (mousewheel)
  12962. return mousewheel.wheelPrecision;
  12963. },
  12964. set: function (value) {
  12965. var mousewheel = this.inputs.attached["mousewheel"];
  12966. if (mousewheel)
  12967. mousewheel.wheelPrecision = value;
  12968. },
  12969. enumerable: true,
  12970. configurable: true
  12971. });
  12972. // Cache
  12973. ArcRotateCamera.prototype._initCache = function () {
  12974. _super.prototype._initCache.call(this);
  12975. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12976. this._cache.alpha = undefined;
  12977. this._cache.beta = undefined;
  12978. this._cache.radius = undefined;
  12979. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  12980. };
  12981. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  12982. if (!ignoreParentClass) {
  12983. _super.prototype._updateCache.call(this);
  12984. }
  12985. this._cache.target.copyFrom(this._getTargetPosition());
  12986. this._cache.alpha = this.alpha;
  12987. this._cache.beta = this.beta;
  12988. this._cache.radius = this.radius;
  12989. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  12990. };
  12991. ArcRotateCamera.prototype._getTargetPosition = function () {
  12992. if (this.target.getAbsolutePosition) {
  12993. return this.target.getAbsolutePosition();
  12994. }
  12995. return this.target;
  12996. };
  12997. // Synchronized
  12998. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  12999. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13000. return false;
  13001. return this._cache.target.equals(this.target)
  13002. && this._cache.alpha === this.alpha
  13003. && this._cache.beta === this.beta
  13004. && this._cache.radius === this.radius
  13005. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13006. };
  13007. // Methods
  13008. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13009. var _this = this;
  13010. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13011. if (this._attachedElement) {
  13012. return;
  13013. }
  13014. this._attachedElement = element;
  13015. this._noPreventDefault = noPreventDefault;
  13016. this._useCtrlForPanning = useCtrlForPanning;
  13017. this.inputs.attachElement(element, noPreventDefault);
  13018. this._reset = function () {
  13019. _this.inertialAlphaOffset = 0;
  13020. _this.inertialBetaOffset = 0;
  13021. _this.inertialRadiusOffset = 0;
  13022. };
  13023. };
  13024. ArcRotateCamera.prototype.detachControl = function (element) {
  13025. if (this._attachedElement !== element) {
  13026. return;
  13027. }
  13028. this.inputs.detachElement(this._attachedElement);
  13029. this._attachedElement = null;
  13030. if (this._reset) {
  13031. this._reset();
  13032. }
  13033. };
  13034. ArcRotateCamera.prototype._checkInputs = function () {
  13035. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13036. if (this._collisionTriggered) {
  13037. return;
  13038. }
  13039. this.inputs.checkInputs();
  13040. // Inertia
  13041. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13042. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13043. this.beta += this.inertialBetaOffset;
  13044. this.radius -= this.inertialRadiusOffset;
  13045. this.inertialAlphaOffset *= this.inertia;
  13046. this.inertialBetaOffset *= this.inertia;
  13047. this.inertialRadiusOffset *= this.inertia;
  13048. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13049. this.inertialAlphaOffset = 0;
  13050. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13051. this.inertialBetaOffset = 0;
  13052. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13053. this.inertialRadiusOffset = 0;
  13054. }
  13055. // Panning inertia
  13056. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13057. if (!this._localDirection) {
  13058. this._localDirection = BABYLON.Vector3.Zero();
  13059. this._transformedDirection = BABYLON.Vector3.Zero();
  13060. }
  13061. this.inertialPanningX *= this.inertia;
  13062. this.inertialPanningY *= this.inertia;
  13063. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13064. this.inertialPanningX = 0;
  13065. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13066. this.inertialPanningY = 0;
  13067. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13068. this._localDirection.multiplyInPlace(this.panningAxis);
  13069. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13070. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13071. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13072. if (!this.panningAxis.y) {
  13073. this._transformedDirection.y = 0;
  13074. }
  13075. this.target.addInPlace(this._transformedDirection);
  13076. }
  13077. // Limits
  13078. this._checkLimits();
  13079. _super.prototype._checkInputs.call(this);
  13080. };
  13081. ArcRotateCamera.prototype._checkLimits = function () {
  13082. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13083. if (this.allowUpsideDown && this.beta > Math.PI) {
  13084. this.beta = this.beta - (2 * Math.PI);
  13085. }
  13086. }
  13087. else {
  13088. if (this.beta < this.lowerBetaLimit) {
  13089. this.beta = this.lowerBetaLimit;
  13090. }
  13091. }
  13092. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13093. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13094. this.beta = this.beta + (2 * Math.PI);
  13095. }
  13096. }
  13097. else {
  13098. if (this.beta > this.upperBetaLimit) {
  13099. this.beta = this.upperBetaLimit;
  13100. }
  13101. }
  13102. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13103. this.alpha = this.lowerAlphaLimit;
  13104. }
  13105. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13106. this.alpha = this.upperAlphaLimit;
  13107. }
  13108. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13109. this.radius = this.lowerRadiusLimit;
  13110. }
  13111. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13112. this.radius = this.upperRadiusLimit;
  13113. }
  13114. };
  13115. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13116. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13117. this.radius = radiusv3.length();
  13118. // Alpha
  13119. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13120. if (radiusv3.z < 0) {
  13121. this.alpha = 2 * Math.PI - this.alpha;
  13122. }
  13123. // Beta
  13124. this.beta = Math.acos(radiusv3.y / this.radius);
  13125. this._checkLimits();
  13126. };
  13127. ArcRotateCamera.prototype.setPosition = function (position) {
  13128. if (this.position.equals(position)) {
  13129. return;
  13130. }
  13131. this.position = position;
  13132. this.rebuildAnglesAndRadius();
  13133. };
  13134. ArcRotateCamera.prototype.setTarget = function (target) {
  13135. if (this._getTargetPosition().equals(target)) {
  13136. return;
  13137. }
  13138. this.target = target;
  13139. this.rebuildAnglesAndRadius();
  13140. };
  13141. ArcRotateCamera.prototype._getViewMatrix = function () {
  13142. // Compute
  13143. var cosa = Math.cos(this.alpha);
  13144. var sina = Math.sin(this.alpha);
  13145. var cosb = Math.cos(this.beta);
  13146. var sinb = Math.sin(this.beta);
  13147. if (sinb === 0) {
  13148. sinb = 0.0001;
  13149. }
  13150. var target = this._getTargetPosition();
  13151. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13152. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13153. this._collider.radius = this.collisionRadius;
  13154. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13155. this._collisionTriggered = true;
  13156. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13157. }
  13158. else {
  13159. this.position.copyFrom(this._newPosition);
  13160. var up = this.upVector;
  13161. if (this.allowUpsideDown && this.beta < 0) {
  13162. up = up.clone();
  13163. up = up.negate();
  13164. }
  13165. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13166. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13167. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13168. }
  13169. return this._viewMatrix;
  13170. };
  13171. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13172. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13173. meshes = meshes || this.getScene().meshes;
  13174. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13175. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13176. this.radius = distance * this.zoomOnFactor;
  13177. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13178. };
  13179. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13180. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13181. var meshesOrMinMaxVector;
  13182. var distance;
  13183. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13184. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13185. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13186. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13187. }
  13188. else {
  13189. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13190. distance = meshesOrMinMaxVectorAndDistance.distance;
  13191. }
  13192. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13193. if (!doNotUpdateMaxZ) {
  13194. this.maxZ = distance * 2;
  13195. }
  13196. };
  13197. /**
  13198. * @override
  13199. * Override Camera.createRigCamera
  13200. */
  13201. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13202. switch (this.cameraRigMode) {
  13203. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13204. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13205. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13206. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13207. case BABYLON.Camera.RIG_MODE_VR:
  13208. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13209. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13210. }
  13211. return null;
  13212. };
  13213. /**
  13214. * @override
  13215. * Override Camera._updateRigCameras
  13216. */
  13217. ArcRotateCamera.prototype._updateRigCameras = function () {
  13218. switch (this.cameraRigMode) {
  13219. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13220. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13221. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13222. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13223. case BABYLON.Camera.RIG_MODE_VR:
  13224. var camLeft = this._rigCameras[0];
  13225. var camRight = this._rigCameras[1];
  13226. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13227. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13228. camLeft.beta = camRight.beta = this.beta;
  13229. camLeft.radius = camRight.radius = this.radius;
  13230. break;
  13231. }
  13232. _super.prototype._updateRigCameras.call(this);
  13233. };
  13234. ArcRotateCamera.prototype.dispose = function () {
  13235. this.inputs.clear();
  13236. _super.prototype.dispose.call(this);
  13237. };
  13238. ArcRotateCamera.prototype.getTypeName = function () {
  13239. return "ArcRotateCamera";
  13240. };
  13241. __decorate([
  13242. BABYLON.serialize()
  13243. ], ArcRotateCamera.prototype, "alpha", void 0);
  13244. __decorate([
  13245. BABYLON.serialize()
  13246. ], ArcRotateCamera.prototype, "beta", void 0);
  13247. __decorate([
  13248. BABYLON.serialize()
  13249. ], ArcRotateCamera.prototype, "radius", void 0);
  13250. __decorate([
  13251. BABYLON.serializeAsVector3()
  13252. ], ArcRotateCamera.prototype, "target", void 0);
  13253. __decorate([
  13254. BABYLON.serialize()
  13255. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13256. __decorate([
  13257. BABYLON.serialize()
  13258. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13259. __decorate([
  13260. BABYLON.serialize()
  13261. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13262. __decorate([
  13263. BABYLON.serialize()
  13264. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13265. __decorate([
  13266. BABYLON.serialize()
  13267. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13268. __decorate([
  13269. BABYLON.serialize()
  13270. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13271. __decorate([
  13272. BABYLON.serialize()
  13273. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13274. __decorate([
  13275. BABYLON.serialize()
  13276. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13277. __decorate([
  13278. BABYLON.serialize()
  13279. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13280. __decorate([
  13281. BABYLON.serialize()
  13282. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13283. __decorate([
  13284. BABYLON.serialize()
  13285. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13286. __decorate([
  13287. BABYLON.serialize()
  13288. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13289. __decorate([
  13290. BABYLON.serialize()
  13291. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13292. return ArcRotateCamera;
  13293. })(BABYLON.TargetCamera);
  13294. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13295. })(BABYLON || (BABYLON = {}));
  13296. var BABYLON;
  13297. (function (BABYLON) {
  13298. var ArcRotateCameraInputsManager = (function (_super) {
  13299. __extends(ArcRotateCameraInputsManager, _super);
  13300. function ArcRotateCameraInputsManager(camera) {
  13301. _super.call(this, camera);
  13302. }
  13303. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13304. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13305. return this;
  13306. };
  13307. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13308. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13309. return this;
  13310. };
  13311. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13312. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13313. return this;
  13314. };
  13315. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13316. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13317. return this;
  13318. };
  13319. return ArcRotateCameraInputsManager;
  13320. })(BABYLON.CameraInputsManager);
  13321. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13322. })(BABYLON || (BABYLON = {}));
  13323. var BABYLON;
  13324. (function (BABYLON) {
  13325. var RenderingManager = (function () {
  13326. function RenderingManager(scene) {
  13327. this._renderingGroups = new Array();
  13328. this._scene = scene;
  13329. }
  13330. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13331. if (this._scene._activeParticleSystems.length === 0) {
  13332. return;
  13333. }
  13334. // Particles
  13335. var activeCamera = this._scene.activeCamera;
  13336. var beforeParticlesDate = BABYLON.Tools.Now;
  13337. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13338. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13339. if (particleSystem.renderingGroupId !== index) {
  13340. continue;
  13341. }
  13342. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13343. continue;
  13344. }
  13345. this._clearDepthBuffer();
  13346. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13347. this._scene._activeParticles += particleSystem.render();
  13348. }
  13349. }
  13350. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13351. };
  13352. RenderingManager.prototype._renderSprites = function (index) {
  13353. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13354. return;
  13355. }
  13356. // Sprites
  13357. var activeCamera = this._scene.activeCamera;
  13358. var beforeSpritessDate = BABYLON.Tools.Now;
  13359. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13360. var spriteManager = this._scene.spriteManagers[id];
  13361. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13362. this._clearDepthBuffer();
  13363. spriteManager.render();
  13364. }
  13365. }
  13366. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13367. };
  13368. RenderingManager.prototype._clearDepthBuffer = function () {
  13369. if (this._depthBufferAlreadyCleaned) {
  13370. return;
  13371. }
  13372. this._scene.getEngine().clear(0, false, true);
  13373. this._depthBufferAlreadyCleaned = true;
  13374. };
  13375. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13376. if (this._currentRenderSprites) {
  13377. this._renderSprites(this._currentIndex);
  13378. }
  13379. if (this._currentRenderParticles) {
  13380. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13381. }
  13382. };
  13383. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13384. this._currentActiveMeshes = activeMeshes;
  13385. this._currentRenderParticles = renderParticles;
  13386. this._currentRenderSprites = renderSprites;
  13387. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13388. this._depthBufferAlreadyCleaned = index == 0;
  13389. var renderingGroup = this._renderingGroups[index];
  13390. var needToStepBack = false;
  13391. this._currentIndex = index;
  13392. if (renderingGroup) {
  13393. this._clearDepthBuffer();
  13394. if (!renderingGroup.onBeforeTransparentRendering) {
  13395. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13396. }
  13397. if (!renderingGroup.render(customRenderFunction)) {
  13398. this._renderingGroups.splice(index, 1);
  13399. needToStepBack = true;
  13400. this._renderSpritesAndParticles();
  13401. }
  13402. }
  13403. else {
  13404. this._renderSpritesAndParticles();
  13405. }
  13406. if (needToStepBack) {
  13407. index--;
  13408. }
  13409. }
  13410. };
  13411. RenderingManager.prototype.reset = function () {
  13412. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13413. if (renderingGroup) {
  13414. renderingGroup.prepare();
  13415. }
  13416. });
  13417. };
  13418. RenderingManager.prototype.dispatch = function (subMesh) {
  13419. var mesh = subMesh.getMesh();
  13420. var renderingGroupId = mesh.renderingGroupId || 0;
  13421. if (!this._renderingGroups[renderingGroupId]) {
  13422. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13423. }
  13424. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13425. };
  13426. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13427. return RenderingManager;
  13428. })();
  13429. BABYLON.RenderingManager = RenderingManager;
  13430. })(BABYLON || (BABYLON = {}));
  13431. var BABYLON;
  13432. (function (BABYLON) {
  13433. var RenderingGroup = (function () {
  13434. function RenderingGroup(index, scene) {
  13435. this.index = index;
  13436. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13437. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13438. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13439. this._scene = scene;
  13440. }
  13441. RenderingGroup.prototype.render = function (customRenderFunction) {
  13442. if (customRenderFunction) {
  13443. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13444. return true;
  13445. }
  13446. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13447. if (this.onBeforeTransparentRendering) {
  13448. this.onBeforeTransparentRendering();
  13449. }
  13450. return false;
  13451. }
  13452. var engine = this._scene.getEngine();
  13453. // Opaque
  13454. var subIndex;
  13455. var submesh;
  13456. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13457. submesh = this._opaqueSubMeshes.data[subIndex];
  13458. submesh.render(false);
  13459. }
  13460. // Alpha test
  13461. engine.setAlphaTesting(true);
  13462. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13463. submesh = this._alphaTestSubMeshes.data[subIndex];
  13464. submesh.render(false);
  13465. }
  13466. engine.setAlphaTesting(false);
  13467. if (this.onBeforeTransparentRendering) {
  13468. this.onBeforeTransparentRendering();
  13469. }
  13470. // Transparent
  13471. if (this._transparentSubMeshes.length) {
  13472. // Sorting
  13473. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13474. submesh = this._transparentSubMeshes.data[subIndex];
  13475. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13476. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13477. }
  13478. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13479. sortedArray.sort(function (a, b) {
  13480. // Alpha index first
  13481. if (a._alphaIndex > b._alphaIndex) {
  13482. return 1;
  13483. }
  13484. if (a._alphaIndex < b._alphaIndex) {
  13485. return -1;
  13486. }
  13487. // Then distance to camera
  13488. if (a._distanceToCamera < b._distanceToCamera) {
  13489. return 1;
  13490. }
  13491. if (a._distanceToCamera > b._distanceToCamera) {
  13492. return -1;
  13493. }
  13494. return 0;
  13495. });
  13496. // Rendering
  13497. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13498. submesh = sortedArray[subIndex];
  13499. submesh.render(true);
  13500. }
  13501. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13502. }
  13503. return true;
  13504. };
  13505. RenderingGroup.prototype.prepare = function () {
  13506. this._opaqueSubMeshes.reset();
  13507. this._transparentSubMeshes.reset();
  13508. this._alphaTestSubMeshes.reset();
  13509. };
  13510. RenderingGroup.prototype.dispatch = function (subMesh) {
  13511. var material = subMesh.getMaterial();
  13512. var mesh = subMesh.getMesh();
  13513. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13514. this._transparentSubMeshes.push(subMesh);
  13515. }
  13516. else if (material.needAlphaTesting()) {
  13517. this._alphaTestSubMeshes.push(subMesh);
  13518. }
  13519. else {
  13520. this._opaqueSubMeshes.push(subMesh); // Opaque
  13521. }
  13522. };
  13523. return RenderingGroup;
  13524. })();
  13525. BABYLON.RenderingGroup = RenderingGroup;
  13526. })(BABYLON || (BABYLON = {}));
  13527. var BABYLON;
  13528. (function (BABYLON) {
  13529. /**
  13530. * Represents a scene to be rendered by the engine.
  13531. * @see http://doc.babylonjs.com/page.php?p=21911
  13532. */
  13533. var Scene = (function () {
  13534. /**
  13535. * @constructor
  13536. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  13537. */
  13538. function Scene(engine) {
  13539. // Members
  13540. this.autoClear = true;
  13541. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13542. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13543. this.forceWireframe = false;
  13544. this.forcePointsCloud = false;
  13545. this.forceShowBoundingBoxes = false;
  13546. this.animationsEnabled = true;
  13547. this.constantlyUpdateMeshUnderPointer = false;
  13548. // Animations
  13549. this.animations = [];
  13550. 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
  13551. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  13552. this._startingPointerTime = 0;
  13553. // Fog
  13554. /**
  13555. * is fog enabled on this scene.
  13556. * @type {boolean}
  13557. */
  13558. this.fogEnabled = true;
  13559. this.fogMode = Scene.FOGMODE_NONE;
  13560. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13561. this.fogDensity = 0.1;
  13562. this.fogStart = 0;
  13563. this.fogEnd = 1000.0;
  13564. // Lights
  13565. /**
  13566. * is shadow enabled on this scene.
  13567. * @type {boolean}
  13568. */
  13569. this.shadowsEnabled = true;
  13570. /**
  13571. * is light enabled on this scene.
  13572. * @type {boolean}
  13573. */
  13574. this.lightsEnabled = true;
  13575. /**
  13576. * All of the lights added to this scene.
  13577. * @see BABYLON.Light
  13578. * @type {BABYLON.Light[]}
  13579. */
  13580. this.lights = new Array();
  13581. // Cameras
  13582. /**
  13583. * All of the cameras added to this scene.
  13584. * @see BABYLON.Camera
  13585. * @type {BABYLON.Camera[]}
  13586. */
  13587. this.cameras = new Array();
  13588. this.activeCameras = new Array();
  13589. // Meshes
  13590. /**
  13591. * All of the (abstract) meshes added to this scene.
  13592. * @see BABYLON.AbstractMesh
  13593. * @type {BABYLON.AbstractMesh[]}
  13594. */
  13595. this.meshes = new Array();
  13596. // Geometries
  13597. this._geometries = new Array();
  13598. this.materials = new Array();
  13599. this.multiMaterials = new Array();
  13600. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  13601. // Textures
  13602. this.texturesEnabled = true;
  13603. this.textures = new Array();
  13604. // Particles
  13605. this.particlesEnabled = true;
  13606. this.particleSystems = new Array();
  13607. // Sprites
  13608. this.spritesEnabled = true;
  13609. this.spriteManagers = new Array();
  13610. // Layers
  13611. this.layers = new Array();
  13612. // Skeletons
  13613. this.skeletonsEnabled = true;
  13614. this.skeletons = new Array();
  13615. // Lens flares
  13616. this.lensFlaresEnabled = true;
  13617. this.lensFlareSystems = new Array();
  13618. // Collisions
  13619. this.collisionsEnabled = true;
  13620. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  13621. // Postprocesses
  13622. this.postProcessesEnabled = true;
  13623. // Customs render targets
  13624. this.renderTargetsEnabled = true;
  13625. this.dumpNextRenderTargets = false;
  13626. this.customRenderTargets = new Array();
  13627. // Imported meshes
  13628. this.importedMeshesFiles = new Array();
  13629. // Probes
  13630. this.probesEnabled = true;
  13631. this.reflectionProbes = new Array();
  13632. this._actionManagers = new Array();
  13633. this._meshesForIntersections = new BABYLON.SmartArray(256);
  13634. // Procedural textures
  13635. this.proceduralTexturesEnabled = true;
  13636. this._proceduralTextures = new Array();
  13637. this.soundTracks = new Array();
  13638. this._audioEnabled = true;
  13639. this._headphone = false;
  13640. this._totalVertices = 0;
  13641. this._activeIndices = 0;
  13642. this._activeParticles = 0;
  13643. this._lastFrameDuration = 0;
  13644. this._evaluateActiveMeshesDuration = 0;
  13645. this._renderTargetsDuration = 0;
  13646. this._particlesDuration = 0;
  13647. this._renderDuration = 0;
  13648. this._spritesDuration = 0;
  13649. this._animationRatio = 0;
  13650. this._renderId = 0;
  13651. this._executeWhenReadyTimeoutId = -1;
  13652. this._toBeDisposed = new BABYLON.SmartArray(256);
  13653. this._onReadyCallbacks = new Array();
  13654. this._pendingData = []; //ANY
  13655. this._onBeforeRenderCallbacks = new Array();
  13656. this._onAfterRenderCallbacks = new Array();
  13657. this._activeMeshes = new BABYLON.SmartArray(256);
  13658. this._processedMaterials = new BABYLON.SmartArray(256);
  13659. this._renderTargets = new BABYLON.SmartArray(256);
  13660. this._activeParticleSystems = new BABYLON.SmartArray(256);
  13661. this._activeSkeletons = new BABYLON.SmartArray(32);
  13662. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  13663. this._activeBones = 0;
  13664. this._activeAnimatables = new Array();
  13665. this._transformMatrix = BABYLON.Matrix.Zero();
  13666. this._edgesRenderers = new BABYLON.SmartArray(16);
  13667. this._uniqueIdCounter = 0;
  13668. this._engine = engine;
  13669. engine.scenes.push(this);
  13670. this._renderingManager = new BABYLON.RenderingManager(this);
  13671. this.postProcessManager = new BABYLON.PostProcessManager(this);
  13672. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  13673. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  13674. if (BABYLON.OutlineRenderer) {
  13675. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  13676. }
  13677. this.attachControl();
  13678. this._debugLayer = new BABYLON.DebugLayer(this);
  13679. if (BABYLON.SoundTrack) {
  13680. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  13681. }
  13682. //simplification queue
  13683. if (BABYLON.SimplificationQueue) {
  13684. this.simplificationQueue = new BABYLON.SimplificationQueue();
  13685. }
  13686. //collision coordinator initialization. For now legacy per default.
  13687. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  13688. }
  13689. Object.defineProperty(Scene, "FOGMODE_NONE", {
  13690. get: function () {
  13691. return Scene._FOGMODE_NONE;
  13692. },
  13693. enumerable: true,
  13694. configurable: true
  13695. });
  13696. Object.defineProperty(Scene, "FOGMODE_EXP", {
  13697. get: function () {
  13698. return Scene._FOGMODE_EXP;
  13699. },
  13700. enumerable: true,
  13701. configurable: true
  13702. });
  13703. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  13704. get: function () {
  13705. return Scene._FOGMODE_EXP2;
  13706. },
  13707. enumerable: true,
  13708. configurable: true
  13709. });
  13710. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  13711. get: function () {
  13712. return Scene._FOGMODE_LINEAR;
  13713. },
  13714. enumerable: true,
  13715. configurable: true
  13716. });
  13717. Object.defineProperty(Scene.prototype, "debugLayer", {
  13718. // Properties
  13719. get: function () {
  13720. return this._debugLayer;
  13721. },
  13722. enumerable: true,
  13723. configurable: true
  13724. });
  13725. Object.defineProperty(Scene.prototype, "workerCollisions", {
  13726. get: function () {
  13727. return this._workerCollisions;
  13728. },
  13729. set: function (enabled) {
  13730. enabled = (enabled && !!Worker);
  13731. this._workerCollisions = enabled;
  13732. if (this.collisionCoordinator) {
  13733. this.collisionCoordinator.destroy();
  13734. }
  13735. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  13736. this.collisionCoordinator.init(this);
  13737. },
  13738. enumerable: true,
  13739. configurable: true
  13740. });
  13741. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  13742. get: function () {
  13743. return this._selectionOctree;
  13744. },
  13745. enumerable: true,
  13746. configurable: true
  13747. });
  13748. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  13749. /**
  13750. * The mesh that is currently under the pointer.
  13751. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  13752. */
  13753. get: function () {
  13754. return this._pointerOverMesh;
  13755. },
  13756. enumerable: true,
  13757. configurable: true
  13758. });
  13759. Object.defineProperty(Scene.prototype, "pointerX", {
  13760. /**
  13761. * Current on-screen X position of the pointer
  13762. * @return {number} X position of the pointer
  13763. */
  13764. get: function () {
  13765. return this._pointerX;
  13766. },
  13767. enumerable: true,
  13768. configurable: true
  13769. });
  13770. Object.defineProperty(Scene.prototype, "pointerY", {
  13771. /**
  13772. * Current on-screen Y position of the pointer
  13773. * @return {number} Y position of the pointer
  13774. */
  13775. get: function () {
  13776. return this._pointerY;
  13777. },
  13778. enumerable: true,
  13779. configurable: true
  13780. });
  13781. Scene.prototype.getCachedMaterial = function () {
  13782. return this._cachedMaterial;
  13783. };
  13784. Scene.prototype.getBoundingBoxRenderer = function () {
  13785. return this._boundingBoxRenderer;
  13786. };
  13787. Scene.prototype.getOutlineRenderer = function () {
  13788. return this._outlineRenderer;
  13789. };
  13790. Scene.prototype.getEngine = function () {
  13791. return this._engine;
  13792. };
  13793. Scene.prototype.getTotalVertices = function () {
  13794. return this._totalVertices;
  13795. };
  13796. Scene.prototype.getActiveIndices = function () {
  13797. return this._activeIndices;
  13798. };
  13799. Scene.prototype.getActiveParticles = function () {
  13800. return this._activeParticles;
  13801. };
  13802. Scene.prototype.getActiveBones = function () {
  13803. return this._activeBones;
  13804. };
  13805. // Stats
  13806. Scene.prototype.getLastFrameDuration = function () {
  13807. return this._lastFrameDuration;
  13808. };
  13809. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  13810. return this._evaluateActiveMeshesDuration;
  13811. };
  13812. Scene.prototype.getActiveMeshes = function () {
  13813. return this._activeMeshes;
  13814. };
  13815. Scene.prototype.getRenderTargetsDuration = function () {
  13816. return this._renderTargetsDuration;
  13817. };
  13818. Scene.prototype.getRenderDuration = function () {
  13819. return this._renderDuration;
  13820. };
  13821. Scene.prototype.getParticlesDuration = function () {
  13822. return this._particlesDuration;
  13823. };
  13824. Scene.prototype.getSpritesDuration = function () {
  13825. return this._spritesDuration;
  13826. };
  13827. Scene.prototype.getAnimationRatio = function () {
  13828. return this._animationRatio;
  13829. };
  13830. Scene.prototype.getRenderId = function () {
  13831. return this._renderId;
  13832. };
  13833. Scene.prototype.incrementRenderId = function () {
  13834. this._renderId++;
  13835. };
  13836. Scene.prototype._updatePointerPosition = function (evt) {
  13837. var canvasRect = this._engine.getRenderingCanvasClientRect();
  13838. this._pointerX = evt.clientX - canvasRect.left;
  13839. this._pointerY = evt.clientY - canvasRect.top;
  13840. this._unTranslatedPointerX = this._pointerX;
  13841. this._unTranslatedPointerY = this._pointerY;
  13842. if (this.cameraToUseForPointers) {
  13843. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  13844. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  13845. }
  13846. };
  13847. // Pointers handling
  13848. Scene.prototype.attachControl = function () {
  13849. var _this = this;
  13850. var spritePredicate = function (sprite) {
  13851. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  13852. };
  13853. this._onPointerMove = function (evt) {
  13854. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13855. return;
  13856. }
  13857. var canvas = _this._engine.getRenderingCanvas();
  13858. _this._updatePointerPosition(evt);
  13859. if (!_this.pointerMovePredicate) {
  13860. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  13861. }
  13862. // Meshes
  13863. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  13864. if (pickResult.hit && pickResult.pickedMesh) {
  13865. _this.setPointerOverSprite(null);
  13866. _this.setPointerOverMesh(pickResult.pickedMesh);
  13867. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  13868. canvas.style.cursor = "pointer";
  13869. }
  13870. else {
  13871. canvas.style.cursor = "";
  13872. }
  13873. }
  13874. else {
  13875. _this.setPointerOverMesh(null);
  13876. // Sprites
  13877. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13878. if (pickResult.hit && pickResult.pickedSprite) {
  13879. canvas.style.cursor = "pointer";
  13880. _this.setPointerOverSprite(pickResult.pickedSprite);
  13881. }
  13882. else {
  13883. _this.setPointerOverSprite(null);
  13884. // Restore pointer
  13885. canvas.style.cursor = "";
  13886. }
  13887. }
  13888. if (_this.onPointerMove) {
  13889. _this.onPointerMove(evt, pickResult);
  13890. }
  13891. };
  13892. this._onPointerDown = function (evt) {
  13893. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13894. return;
  13895. }
  13896. _this._updatePointerPosition(evt);
  13897. _this._startingPointerPosition.x = _this._pointerX;
  13898. _this._startingPointerPosition.y = _this._pointerY;
  13899. _this._startingPointerTime = new Date().getTime();
  13900. if (!_this.pointerDownPredicate) {
  13901. _this.pointerDownPredicate = function (mesh) {
  13902. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  13903. };
  13904. }
  13905. // Meshes
  13906. _this._pickedDownMesh = null;
  13907. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  13908. if (pickResult.hit && pickResult.pickedMesh) {
  13909. if (pickResult.pickedMesh.actionManager) {
  13910. _this._pickedDownMesh = pickResult.pickedMesh;
  13911. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  13912. switch (evt.button) {
  13913. case 0:
  13914. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13915. break;
  13916. case 1:
  13917. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13918. break;
  13919. case 2:
  13920. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13921. break;
  13922. }
  13923. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13924. }
  13925. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  13926. var that = _this;
  13927. window.setTimeout(function () {
  13928. 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);
  13929. if (pickResult.hit && pickResult.pickedMesh) {
  13930. if (pickResult.pickedMesh.actionManager) {
  13931. 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)) {
  13932. that._startingPointerTime = 0;
  13933. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13934. }
  13935. }
  13936. }
  13937. }, BABYLON.ActionManager.LongPressDelay);
  13938. }
  13939. }
  13940. }
  13941. if (_this.onPointerDown) {
  13942. _this.onPointerDown(evt, pickResult);
  13943. }
  13944. // Sprites
  13945. _this._pickedDownSprite = null;
  13946. if (_this.spriteManagers.length > 0) {
  13947. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13948. if (pickResult.hit && pickResult.pickedSprite) {
  13949. if (pickResult.pickedSprite.actionManager) {
  13950. _this._pickedDownSprite = pickResult.pickedSprite;
  13951. switch (evt.button) {
  13952. case 0:
  13953. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13954. break;
  13955. case 1:
  13956. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13957. break;
  13958. case 2:
  13959. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13960. break;
  13961. }
  13962. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13963. }
  13964. }
  13965. }
  13966. };
  13967. this._onPointerUp = function (evt) {
  13968. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13969. return;
  13970. }
  13971. _this._updatePointerPosition(evt);
  13972. if (!_this.pointerUpPredicate) {
  13973. _this.pointerUpPredicate = function (mesh) {
  13974. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  13975. };
  13976. }
  13977. // Meshes
  13978. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  13979. if (pickResult.hit && pickResult.pickedMesh) {
  13980. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13981. _this.onPointerPick(evt, pickResult);
  13982. }
  13983. if (pickResult.pickedMesh.actionManager) {
  13984. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13985. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13986. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13987. }
  13988. }
  13989. }
  13990. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13991. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13992. }
  13993. if (_this.onPointerUp) {
  13994. _this.onPointerUp(evt, pickResult);
  13995. }
  13996. _this._startingPointerTime = 0;
  13997. // Sprites
  13998. if (_this.spriteManagers.length > 0) {
  13999. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14000. if (pickResult.hit && pickResult.pickedSprite) {
  14001. if (pickResult.pickedSprite.actionManager) {
  14002. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14003. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14004. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14005. }
  14006. }
  14007. }
  14008. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14009. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14010. }
  14011. }
  14012. };
  14013. this._onKeyDown = function (evt) {
  14014. if (_this.actionManager) {
  14015. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14016. }
  14017. };
  14018. this._onKeyUp = function (evt) {
  14019. if (_this.actionManager) {
  14020. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14021. }
  14022. };
  14023. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14024. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14025. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14026. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14027. // Wheel
  14028. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14029. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14030. BABYLON.Tools.RegisterTopRootEvents([
  14031. { name: "keydown", handler: this._onKeyDown },
  14032. { name: "keyup", handler: this._onKeyUp }
  14033. ]);
  14034. };
  14035. Scene.prototype.detachControl = function () {
  14036. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14037. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14038. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14039. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14040. // Wheel
  14041. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14042. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14043. BABYLON.Tools.UnregisterTopRootEvents([
  14044. { name: "keydown", handler: this._onKeyDown },
  14045. { name: "keyup", handler: this._onKeyUp }
  14046. ]);
  14047. };
  14048. // Ready
  14049. Scene.prototype.isReady = function () {
  14050. if (this._pendingData.length > 0) {
  14051. return false;
  14052. }
  14053. var index;
  14054. for (index = 0; index < this._geometries.length; index++) {
  14055. var geometry = this._geometries[index];
  14056. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14057. return false;
  14058. }
  14059. }
  14060. for (index = 0; index < this.meshes.length; index++) {
  14061. var mesh = this.meshes[index];
  14062. if (!mesh.isReady()) {
  14063. return false;
  14064. }
  14065. var mat = mesh.material;
  14066. if (mat) {
  14067. if (!mat.isReady(mesh)) {
  14068. return false;
  14069. }
  14070. }
  14071. }
  14072. return true;
  14073. };
  14074. Scene.prototype.resetCachedMaterial = function () {
  14075. this._cachedMaterial = null;
  14076. };
  14077. Scene.prototype.registerBeforeRender = function (func) {
  14078. this._onBeforeRenderCallbacks.push(func);
  14079. };
  14080. Scene.prototype.unregisterBeforeRender = function (func) {
  14081. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14082. if (index > -1) {
  14083. this._onBeforeRenderCallbacks.splice(index, 1);
  14084. }
  14085. };
  14086. Scene.prototype.registerAfterRender = function (func) {
  14087. this._onAfterRenderCallbacks.push(func);
  14088. };
  14089. Scene.prototype.unregisterAfterRender = function (func) {
  14090. var index = this._onAfterRenderCallbacks.indexOf(func);
  14091. if (index > -1) {
  14092. this._onAfterRenderCallbacks.splice(index, 1);
  14093. }
  14094. };
  14095. Scene.prototype._addPendingData = function (data) {
  14096. this._pendingData.push(data);
  14097. };
  14098. Scene.prototype._removePendingData = function (data) {
  14099. var index = this._pendingData.indexOf(data);
  14100. if (index !== -1) {
  14101. this._pendingData.splice(index, 1);
  14102. }
  14103. };
  14104. Scene.prototype.getWaitingItemsCount = function () {
  14105. return this._pendingData.length;
  14106. };
  14107. /**
  14108. * Registers a function to be executed when the scene is ready.
  14109. * @param {Function} func - the function to be executed.
  14110. */
  14111. Scene.prototype.executeWhenReady = function (func) {
  14112. var _this = this;
  14113. this._onReadyCallbacks.push(func);
  14114. if (this._executeWhenReadyTimeoutId !== -1) {
  14115. return;
  14116. }
  14117. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14118. _this._checkIsReady();
  14119. }, 150);
  14120. };
  14121. Scene.prototype._checkIsReady = function () {
  14122. var _this = this;
  14123. if (this.isReady()) {
  14124. this._onReadyCallbacks.forEach(function (func) {
  14125. func();
  14126. });
  14127. this._onReadyCallbacks = [];
  14128. this._executeWhenReadyTimeoutId = -1;
  14129. return;
  14130. }
  14131. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14132. _this._checkIsReady();
  14133. }, 150);
  14134. };
  14135. // Animations
  14136. /**
  14137. * Will start the animation sequence of a given target
  14138. * @param target - the target
  14139. * @param {number} from - from which frame should animation start
  14140. * @param {number} to - till which frame should animation run.
  14141. * @param {boolean} [loop] - should the animation loop
  14142. * @param {number} [speedRatio] - the speed in which to run the animation
  14143. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14144. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14145. * @return {BABYLON.Animatable} the animatable object created for this animation
  14146. * @see BABYLON.Animatable
  14147. * @see http://doc.babylonjs.com/page.php?p=22081
  14148. */
  14149. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14150. if (speedRatio === void 0) { speedRatio = 1.0; }
  14151. this.stopAnimation(target);
  14152. if (!animatable) {
  14153. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14154. }
  14155. // Local animations
  14156. if (target.animations) {
  14157. animatable.appendAnimations(target, target.animations);
  14158. }
  14159. // Children animations
  14160. if (target.getAnimatables) {
  14161. var animatables = target.getAnimatables();
  14162. for (var index = 0; index < animatables.length; index++) {
  14163. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14164. }
  14165. }
  14166. animatable.reset();
  14167. return animatable;
  14168. };
  14169. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14170. if (speedRatio === undefined) {
  14171. speedRatio = 1.0;
  14172. }
  14173. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14174. return animatable;
  14175. };
  14176. Scene.prototype.getAnimatableByTarget = function (target) {
  14177. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14178. if (this._activeAnimatables[index].target === target) {
  14179. return this._activeAnimatables[index];
  14180. }
  14181. }
  14182. return null;
  14183. };
  14184. Object.defineProperty(Scene.prototype, "Animatables", {
  14185. get: function () {
  14186. return this._activeAnimatables;
  14187. },
  14188. enumerable: true,
  14189. configurable: true
  14190. });
  14191. /**
  14192. * Will stop the animation of the given target
  14193. * @param target - the target
  14194. * @see beginAnimation
  14195. */
  14196. Scene.prototype.stopAnimation = function (target) {
  14197. var animatable = this.getAnimatableByTarget(target);
  14198. if (animatable) {
  14199. animatable.stop();
  14200. }
  14201. };
  14202. Scene.prototype._animate = function () {
  14203. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14204. return;
  14205. }
  14206. if (!this._animationStartDate) {
  14207. if (this._pendingData.length > 0) {
  14208. return;
  14209. }
  14210. this._animationStartDate = BABYLON.Tools.Now;
  14211. }
  14212. // Getting time
  14213. var now = BABYLON.Tools.Now;
  14214. var delay = now - this._animationStartDate;
  14215. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14216. this._activeAnimatables[index]._animate(delay);
  14217. }
  14218. };
  14219. // Matrix
  14220. Scene.prototype.getViewMatrix = function () {
  14221. return this._viewMatrix;
  14222. };
  14223. Scene.prototype.getProjectionMatrix = function () {
  14224. return this._projectionMatrix;
  14225. };
  14226. Scene.prototype.getTransformMatrix = function () {
  14227. return this._transformMatrix;
  14228. };
  14229. Scene.prototype.setTransformMatrix = function (view, projection) {
  14230. this._viewMatrix = view;
  14231. this._projectionMatrix = projection;
  14232. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14233. };
  14234. // Methods
  14235. Scene.prototype.addMesh = function (newMesh) {
  14236. newMesh.uniqueId = this._uniqueIdCounter++;
  14237. var position = this.meshes.push(newMesh);
  14238. //notify the collision coordinator
  14239. this.collisionCoordinator.onMeshAdded(newMesh);
  14240. if (this.onNewMeshAdded) {
  14241. this.onNewMeshAdded(newMesh, position, this);
  14242. }
  14243. };
  14244. Scene.prototype.removeMesh = function (toRemove) {
  14245. var index = this.meshes.indexOf(toRemove);
  14246. if (index !== -1) {
  14247. // Remove from the scene if mesh found
  14248. this.meshes.splice(index, 1);
  14249. }
  14250. //notify the collision coordinator
  14251. this.collisionCoordinator.onMeshRemoved(toRemove);
  14252. if (this.onMeshRemoved) {
  14253. this.onMeshRemoved(toRemove);
  14254. }
  14255. return index;
  14256. };
  14257. Scene.prototype.removeSkeleton = function (toRemove) {
  14258. var index = this.skeletons.indexOf(toRemove);
  14259. if (index !== -1) {
  14260. // Remove from the scene if mesh found
  14261. this.skeletons.splice(index, 1);
  14262. }
  14263. return index;
  14264. };
  14265. Scene.prototype.removeLight = function (toRemove) {
  14266. var index = this.lights.indexOf(toRemove);
  14267. if (index !== -1) {
  14268. // Remove from the scene if mesh found
  14269. this.lights.splice(index, 1);
  14270. }
  14271. if (this.onLightRemoved) {
  14272. this.onLightRemoved(toRemove);
  14273. }
  14274. return index;
  14275. };
  14276. Scene.prototype.removeCamera = function (toRemove) {
  14277. var index = this.cameras.indexOf(toRemove);
  14278. if (index !== -1) {
  14279. // Remove from the scene if mesh found
  14280. this.cameras.splice(index, 1);
  14281. }
  14282. // Remove from activeCameras
  14283. var index2 = this.activeCameras.indexOf(toRemove);
  14284. if (index2 !== -1) {
  14285. // Remove from the scene if mesh found
  14286. this.activeCameras.splice(index2, 1);
  14287. }
  14288. // Reset the activeCamera
  14289. if (this.activeCamera === toRemove) {
  14290. if (this.cameras.length > 0) {
  14291. this.activeCamera = this.cameras[0];
  14292. }
  14293. else {
  14294. this.activeCamera = null;
  14295. }
  14296. }
  14297. if (this.onCameraRemoved) {
  14298. this.onCameraRemoved(toRemove);
  14299. }
  14300. return index;
  14301. };
  14302. Scene.prototype.addLight = function (newLight) {
  14303. newLight.uniqueId = this._uniqueIdCounter++;
  14304. var position = this.lights.push(newLight);
  14305. if (this.onNewLightAdded) {
  14306. this.onNewLightAdded(newLight, position, this);
  14307. }
  14308. };
  14309. Scene.prototype.addCamera = function (newCamera) {
  14310. newCamera.uniqueId = this._uniqueIdCounter++;
  14311. var position = this.cameras.push(newCamera);
  14312. if (this.onNewCameraAdded) {
  14313. this.onNewCameraAdded(newCamera, position, this);
  14314. }
  14315. };
  14316. /**
  14317. * Switch active camera
  14318. * @param {Camera} newCamera - new active camera
  14319. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14320. */
  14321. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14322. if (attachControl === void 0) { attachControl = true; }
  14323. var canvas = this._engine.getRenderingCanvas();
  14324. this.activeCamera.detachControl(canvas);
  14325. this.activeCamera = newCamera;
  14326. if (attachControl) {
  14327. newCamera.attachControl(canvas);
  14328. }
  14329. };
  14330. /**
  14331. * sets the active camera of the scene using its ID
  14332. * @param {string} id - the camera's ID
  14333. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14334. * @see activeCamera
  14335. */
  14336. Scene.prototype.setActiveCameraByID = function (id) {
  14337. var camera = this.getCameraByID(id);
  14338. if (camera) {
  14339. this.activeCamera = camera;
  14340. return camera;
  14341. }
  14342. return null;
  14343. };
  14344. /**
  14345. * sets the active camera of the scene using its name
  14346. * @param {string} name - the camera's name
  14347. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14348. * @see activeCamera
  14349. */
  14350. Scene.prototype.setActiveCameraByName = function (name) {
  14351. var camera = this.getCameraByName(name);
  14352. if (camera) {
  14353. this.activeCamera = camera;
  14354. return camera;
  14355. }
  14356. return null;
  14357. };
  14358. /**
  14359. * get a material using its id
  14360. * @param {string} the material's ID
  14361. * @return {BABYLON.Material|null} the material or null if none found.
  14362. */
  14363. Scene.prototype.getMaterialByID = function (id) {
  14364. for (var index = 0; index < this.materials.length; index++) {
  14365. if (this.materials[index].id === id) {
  14366. return this.materials[index];
  14367. }
  14368. }
  14369. return null;
  14370. };
  14371. /**
  14372. * get a material using its name
  14373. * @param {string} the material's name
  14374. * @return {BABYLON.Material|null} the material or null if none found.
  14375. */
  14376. Scene.prototype.getMaterialByName = function (name) {
  14377. for (var index = 0; index < this.materials.length; index++) {
  14378. if (this.materials[index].name === name) {
  14379. return this.materials[index];
  14380. }
  14381. }
  14382. return null;
  14383. };
  14384. Scene.prototype.getLensFlareSystemByName = function (name) {
  14385. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  14386. if (this.lensFlareSystems[index].name === name) {
  14387. return this.lensFlareSystems[index];
  14388. }
  14389. }
  14390. return null;
  14391. };
  14392. Scene.prototype.getCameraByID = function (id) {
  14393. for (var index = 0; index < this.cameras.length; index++) {
  14394. if (this.cameras[index].id === id) {
  14395. return this.cameras[index];
  14396. }
  14397. }
  14398. return null;
  14399. };
  14400. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  14401. for (var index = 0; index < this.cameras.length; index++) {
  14402. if (this.cameras[index].uniqueId === uniqueId) {
  14403. return this.cameras[index];
  14404. }
  14405. }
  14406. return null;
  14407. };
  14408. /**
  14409. * get a camera using its name
  14410. * @param {string} the camera's name
  14411. * @return {BABYLON.Camera|null} the camera or null if none found.
  14412. */
  14413. Scene.prototype.getCameraByName = function (name) {
  14414. for (var index = 0; index < this.cameras.length; index++) {
  14415. if (this.cameras[index].name === name) {
  14416. return this.cameras[index];
  14417. }
  14418. }
  14419. return null;
  14420. };
  14421. /**
  14422. * get a bone using its id
  14423. * @param {string} the bone's id
  14424. * @return {BABYLON.Bone|null} the bone or null if not found
  14425. */
  14426. Scene.prototype.getBoneByID = function (id) {
  14427. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14428. var skeleton = this.skeletons[skeletonIndex];
  14429. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14430. if (skeleton.bones[boneIndex].id === id) {
  14431. return skeleton.bones[boneIndex];
  14432. }
  14433. }
  14434. }
  14435. return null;
  14436. };
  14437. /**
  14438. * get a bone using its id
  14439. * @param {string} the bone's name
  14440. * @return {BABYLON.Bone|null} the bone or null if not found
  14441. */
  14442. Scene.prototype.getBoneByName = function (name) {
  14443. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14444. var skeleton = this.skeletons[skeletonIndex];
  14445. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14446. if (skeleton.bones[boneIndex].name === name) {
  14447. return skeleton.bones[boneIndex];
  14448. }
  14449. }
  14450. }
  14451. return null;
  14452. };
  14453. /**
  14454. * get a light node using its name
  14455. * @param {string} the light's name
  14456. * @return {BABYLON.Light|null} the light or null if none found.
  14457. */
  14458. Scene.prototype.getLightByName = function (name) {
  14459. for (var index = 0; index < this.lights.length; index++) {
  14460. if (this.lights[index].name === name) {
  14461. return this.lights[index];
  14462. }
  14463. }
  14464. return null;
  14465. };
  14466. /**
  14467. * get a light node using its ID
  14468. * @param {string} the light's id
  14469. * @return {BABYLON.Light|null} the light or null if none found.
  14470. */
  14471. Scene.prototype.getLightByID = function (id) {
  14472. for (var index = 0; index < this.lights.length; index++) {
  14473. if (this.lights[index].id === id) {
  14474. return this.lights[index];
  14475. }
  14476. }
  14477. return null;
  14478. };
  14479. /**
  14480. * get a light node using its scene-generated unique ID
  14481. * @param {number} the light's unique id
  14482. * @return {BABYLON.Light|null} the light or null if none found.
  14483. */
  14484. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  14485. for (var index = 0; index < this.lights.length; index++) {
  14486. if (this.lights[index].uniqueId === uniqueId) {
  14487. return this.lights[index];
  14488. }
  14489. }
  14490. return null;
  14491. };
  14492. /**
  14493. * get a particle system by id
  14494. * @param id {number} the particle system id
  14495. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  14496. */
  14497. Scene.prototype.getParticleSystemByID = function (id) {
  14498. for (var index = 0; index < this.particleSystems.length; index++) {
  14499. if (this.particleSystems[index].id === id) {
  14500. return this.particleSystems[index];
  14501. }
  14502. }
  14503. return null;
  14504. };
  14505. /**
  14506. * get a geometry using its ID
  14507. * @param {string} the geometry's id
  14508. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  14509. */
  14510. Scene.prototype.getGeometryByID = function (id) {
  14511. for (var index = 0; index < this._geometries.length; index++) {
  14512. if (this._geometries[index].id === id) {
  14513. return this._geometries[index];
  14514. }
  14515. }
  14516. return null;
  14517. };
  14518. /**
  14519. * add a new geometry to this scene.
  14520. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  14521. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  14522. * @return {boolean} was the geometry added or not
  14523. */
  14524. Scene.prototype.pushGeometry = function (geometry, force) {
  14525. if (!force && this.getGeometryByID(geometry.id)) {
  14526. return false;
  14527. }
  14528. this._geometries.push(geometry);
  14529. //notify the collision coordinator
  14530. this.collisionCoordinator.onGeometryAdded(geometry);
  14531. if (this.onGeometryAdded) {
  14532. this.onGeometryAdded(geometry);
  14533. }
  14534. return true;
  14535. };
  14536. /**
  14537. * Removes an existing geometry
  14538. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  14539. * @return {boolean} was the geometry removed or not
  14540. */
  14541. Scene.prototype.removeGeometry = function (geometry) {
  14542. var index = this._geometries.indexOf(geometry);
  14543. if (index > -1) {
  14544. this._geometries.splice(index, 1);
  14545. //notify the collision coordinator
  14546. this.collisionCoordinator.onGeometryDeleted(geometry);
  14547. if (this.onGeometryRemoved) {
  14548. this.onGeometryRemoved(geometry);
  14549. }
  14550. return true;
  14551. }
  14552. return false;
  14553. };
  14554. Scene.prototype.getGeometries = function () {
  14555. return this._geometries;
  14556. };
  14557. /**
  14558. * Get the first added mesh found of a given ID
  14559. * @param {string} id - the id to search for
  14560. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14561. */
  14562. Scene.prototype.getMeshByID = function (id) {
  14563. for (var index = 0; index < this.meshes.length; index++) {
  14564. if (this.meshes[index].id === id) {
  14565. return this.meshes[index];
  14566. }
  14567. }
  14568. return null;
  14569. };
  14570. /**
  14571. * Get a mesh with its auto-generated unique id
  14572. * @param {number} uniqueId - the unique id to search for
  14573. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14574. */
  14575. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  14576. for (var index = 0; index < this.meshes.length; index++) {
  14577. if (this.meshes[index].uniqueId === uniqueId) {
  14578. return this.meshes[index];
  14579. }
  14580. }
  14581. return null;
  14582. };
  14583. /**
  14584. * Get a the last added mesh found of a given ID
  14585. * @param {string} id - the id to search for
  14586. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14587. */
  14588. Scene.prototype.getLastMeshByID = function (id) {
  14589. for (var index = this.meshes.length - 1; index >= 0; index--) {
  14590. if (this.meshes[index].id === id) {
  14591. return this.meshes[index];
  14592. }
  14593. }
  14594. return null;
  14595. };
  14596. /**
  14597. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  14598. * @param {string} id - the id to search for
  14599. * @return {BABYLON.Node|null} the node found or null if not found at all.
  14600. */
  14601. Scene.prototype.getLastEntryByID = function (id) {
  14602. var index;
  14603. for (index = this.meshes.length - 1; index >= 0; index--) {
  14604. if (this.meshes[index].id === id) {
  14605. return this.meshes[index];
  14606. }
  14607. }
  14608. for (index = this.cameras.length - 1; index >= 0; index--) {
  14609. if (this.cameras[index].id === id) {
  14610. return this.cameras[index];
  14611. }
  14612. }
  14613. for (index = this.lights.length - 1; index >= 0; index--) {
  14614. if (this.lights[index].id === id) {
  14615. return this.lights[index];
  14616. }
  14617. }
  14618. return null;
  14619. };
  14620. Scene.prototype.getNodeByID = function (id) {
  14621. var mesh = this.getMeshByID(id);
  14622. if (mesh) {
  14623. return mesh;
  14624. }
  14625. var light = this.getLightByID(id);
  14626. if (light) {
  14627. return light;
  14628. }
  14629. var camera = this.getCameraByID(id);
  14630. if (camera) {
  14631. return camera;
  14632. }
  14633. var bone = this.getBoneByID(id);
  14634. return bone;
  14635. };
  14636. Scene.prototype.getNodeByName = function (name) {
  14637. var mesh = this.getMeshByName(name);
  14638. if (mesh) {
  14639. return mesh;
  14640. }
  14641. var light = this.getLightByName(name);
  14642. if (light) {
  14643. return light;
  14644. }
  14645. var camera = this.getCameraByName(name);
  14646. if (camera) {
  14647. return camera;
  14648. }
  14649. var bone = this.getBoneByName(name);
  14650. return bone;
  14651. };
  14652. Scene.prototype.getMeshByName = function (name) {
  14653. for (var index = 0; index < this.meshes.length; index++) {
  14654. if (this.meshes[index].name === name) {
  14655. return this.meshes[index];
  14656. }
  14657. }
  14658. return null;
  14659. };
  14660. Scene.prototype.getSoundByName = function (name) {
  14661. var index;
  14662. if (BABYLON.AudioEngine) {
  14663. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  14664. if (this.mainSoundTrack.soundCollection[index].name === name) {
  14665. return this.mainSoundTrack.soundCollection[index];
  14666. }
  14667. }
  14668. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  14669. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  14670. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  14671. return this.soundTracks[sdIndex].soundCollection[index];
  14672. }
  14673. }
  14674. }
  14675. }
  14676. return null;
  14677. };
  14678. Scene.prototype.getLastSkeletonByID = function (id) {
  14679. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  14680. if (this.skeletons[index].id === id) {
  14681. return this.skeletons[index];
  14682. }
  14683. }
  14684. return null;
  14685. };
  14686. Scene.prototype.getSkeletonById = function (id) {
  14687. for (var index = 0; index < this.skeletons.length; index++) {
  14688. if (this.skeletons[index].id === id) {
  14689. return this.skeletons[index];
  14690. }
  14691. }
  14692. return null;
  14693. };
  14694. Scene.prototype.getSkeletonByName = function (name) {
  14695. for (var index = 0; index < this.skeletons.length; index++) {
  14696. if (this.skeletons[index].name === name) {
  14697. return this.skeletons[index];
  14698. }
  14699. }
  14700. return null;
  14701. };
  14702. Scene.prototype.isActiveMesh = function (mesh) {
  14703. return (this._activeMeshes.indexOf(mesh) !== -1);
  14704. };
  14705. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  14706. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  14707. var material = subMesh.getMaterial();
  14708. if (mesh.showSubMeshesBoundingBox) {
  14709. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  14710. }
  14711. if (material) {
  14712. // Render targets
  14713. if (material.getRenderTargetTextures) {
  14714. if (this._processedMaterials.indexOf(material) === -1) {
  14715. this._processedMaterials.push(material);
  14716. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  14717. }
  14718. }
  14719. // Dispatch
  14720. this._activeIndices += subMesh.indexCount;
  14721. this._renderingManager.dispatch(subMesh);
  14722. }
  14723. }
  14724. };
  14725. Scene.prototype._evaluateActiveMeshes = function () {
  14726. this.activeCamera._activeMeshes.reset();
  14727. this._activeMeshes.reset();
  14728. this._renderingManager.reset();
  14729. this._processedMaterials.reset();
  14730. this._activeParticleSystems.reset();
  14731. this._activeSkeletons.reset();
  14732. this._softwareSkinnedMeshes.reset();
  14733. this._boundingBoxRenderer.reset();
  14734. this._edgesRenderers.reset();
  14735. if (!this._frustumPlanes) {
  14736. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14737. }
  14738. else {
  14739. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14740. }
  14741. // Meshes
  14742. var meshes;
  14743. var len;
  14744. if (this._selectionOctree) {
  14745. var selection = this._selectionOctree.select(this._frustumPlanes);
  14746. meshes = selection.data;
  14747. len = selection.length;
  14748. }
  14749. else {
  14750. len = this.meshes.length;
  14751. meshes = this.meshes;
  14752. }
  14753. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  14754. var mesh = meshes[meshIndex];
  14755. if (mesh.isBlocked) {
  14756. continue;
  14757. }
  14758. this._totalVertices += mesh.getTotalVertices();
  14759. if (!mesh.isReady() || !mesh.isEnabled()) {
  14760. continue;
  14761. }
  14762. mesh.computeWorldMatrix();
  14763. // Intersections
  14764. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  14765. this._meshesForIntersections.pushNoDuplicate(mesh);
  14766. }
  14767. // Switch to current LOD
  14768. var meshLOD = mesh.getLOD(this.activeCamera);
  14769. if (!meshLOD) {
  14770. continue;
  14771. }
  14772. mesh._preActivate();
  14773. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  14774. this._activeMeshes.push(mesh);
  14775. this.activeCamera._activeMeshes.push(mesh);
  14776. mesh._activate(this._renderId);
  14777. this._activeMesh(meshLOD);
  14778. }
  14779. }
  14780. // Particle systems
  14781. var beforeParticlesDate = BABYLON.Tools.Now;
  14782. if (this.particlesEnabled) {
  14783. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  14784. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  14785. var particleSystem = this.particleSystems[particleIndex];
  14786. if (!particleSystem.isStarted()) {
  14787. continue;
  14788. }
  14789. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  14790. this._activeParticleSystems.push(particleSystem);
  14791. particleSystem.animate();
  14792. }
  14793. }
  14794. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  14795. }
  14796. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14797. };
  14798. Scene.prototype._activeMesh = function (mesh) {
  14799. if (mesh.skeleton && this.skeletonsEnabled) {
  14800. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  14801. if (!mesh.computeBonesUsingShaders) {
  14802. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  14803. }
  14804. }
  14805. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  14806. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  14807. }
  14808. if (mesh._edgesRenderer) {
  14809. this._edgesRenderers.push(mesh._edgesRenderer);
  14810. }
  14811. if (mesh && mesh.subMeshes) {
  14812. // Submeshes Octrees
  14813. var len;
  14814. var subMeshes;
  14815. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  14816. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  14817. len = intersections.length;
  14818. subMeshes = intersections.data;
  14819. }
  14820. else {
  14821. subMeshes = mesh.subMeshes;
  14822. len = subMeshes.length;
  14823. }
  14824. for (var subIndex = 0; subIndex < len; subIndex++) {
  14825. var subMesh = subMeshes[subIndex];
  14826. this._evaluateSubMesh(subMesh, mesh);
  14827. }
  14828. }
  14829. };
  14830. Scene.prototype.updateTransformMatrix = function (force) {
  14831. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  14832. };
  14833. Scene.prototype._renderForCamera = function (camera) {
  14834. var engine = this._engine;
  14835. this.activeCamera = camera;
  14836. if (!this.activeCamera)
  14837. throw new Error("Active camera not set");
  14838. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14839. // Viewport
  14840. engine.setViewport(this.activeCamera.viewport);
  14841. // Camera
  14842. this.resetCachedMaterial();
  14843. this._renderId++;
  14844. this.updateTransformMatrix();
  14845. if (this.beforeCameraRender) {
  14846. this.beforeCameraRender(this.activeCamera);
  14847. }
  14848. // Meshes
  14849. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  14850. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  14851. this._evaluateActiveMeshes();
  14852. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  14853. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  14854. // Skeletons
  14855. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  14856. var skeleton = this._activeSkeletons.data[skeletonIndex];
  14857. skeleton.prepare();
  14858. }
  14859. // Software skinning
  14860. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  14861. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  14862. mesh.applySkeleton(mesh.skeleton);
  14863. }
  14864. // Render targets
  14865. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14866. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  14867. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  14868. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  14869. var renderTarget = this._renderTargets.data[renderIndex];
  14870. if (renderTarget._shouldRender()) {
  14871. this._renderId++;
  14872. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  14873. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  14874. }
  14875. }
  14876. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  14877. this._renderId++;
  14878. engine.restoreDefaultFramebuffer(); // Restore back buffer
  14879. }
  14880. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14881. // Prepare Frame
  14882. this.postProcessManager._prepareFrame();
  14883. var beforeRenderDate = BABYLON.Tools.Now;
  14884. // Backgrounds
  14885. var layerIndex;
  14886. var layer;
  14887. if (this.layers.length) {
  14888. engine.setDepthBuffer(false);
  14889. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14890. layer = this.layers[layerIndex];
  14891. if (layer.isBackground) {
  14892. layer.render();
  14893. }
  14894. }
  14895. engine.setDepthBuffer(true);
  14896. }
  14897. // Render
  14898. BABYLON.Tools.StartPerformanceCounter("Main render");
  14899. this._renderingManager.render(null, null, true, true);
  14900. BABYLON.Tools.EndPerformanceCounter("Main render");
  14901. // Bounding boxes
  14902. this._boundingBoxRenderer.render();
  14903. // Edges
  14904. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14905. this._edgesRenderers.data[edgesRendererIndex].render();
  14906. }
  14907. // Lens flares
  14908. if (this.lensFlaresEnabled) {
  14909. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14910. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  14911. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  14912. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  14913. lensFlareSystem.render();
  14914. }
  14915. }
  14916. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14917. }
  14918. // Foregrounds
  14919. if (this.layers.length) {
  14920. engine.setDepthBuffer(false);
  14921. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14922. layer = this.layers[layerIndex];
  14923. if (!layer.isBackground) {
  14924. layer.render();
  14925. }
  14926. }
  14927. engine.setDepthBuffer(true);
  14928. }
  14929. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  14930. // Finalize frame
  14931. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  14932. // Update camera
  14933. this.activeCamera._updateFromScene();
  14934. // Reset some special arrays
  14935. this._renderTargets.reset();
  14936. if (this.afterCameraRender) {
  14937. this.afterCameraRender(this.activeCamera);
  14938. }
  14939. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14940. };
  14941. Scene.prototype._processSubCameras = function (camera) {
  14942. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  14943. this._renderForCamera(camera);
  14944. return;
  14945. }
  14946. // rig cameras
  14947. for (var index = 0; index < camera._rigCameras.length; index++) {
  14948. this._renderForCamera(camera._rigCameras[index]);
  14949. }
  14950. this.activeCamera = camera;
  14951. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  14952. // Update camera
  14953. this.activeCamera._updateFromScene();
  14954. };
  14955. Scene.prototype._checkIntersections = function () {
  14956. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14957. var sourceMesh = this._meshesForIntersections.data[index];
  14958. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14959. var action = sourceMesh.actionManager.actions[actionIndex];
  14960. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14961. var parameters = action.getTriggerParameter();
  14962. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  14963. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  14964. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  14965. if (areIntersecting && currentIntersectionInProgress === -1) {
  14966. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  14967. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14968. sourceMesh._intersectionsInProgress.push(otherMesh);
  14969. }
  14970. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14971. sourceMesh._intersectionsInProgress.push(otherMesh);
  14972. }
  14973. }
  14974. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  14975. //They intersected, and now they don't.
  14976. //is this trigger an exit trigger? execute an event.
  14977. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14978. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14979. }
  14980. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  14981. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14982. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  14983. }
  14984. }
  14985. }
  14986. }
  14987. }
  14988. };
  14989. Scene.prototype.render = function () {
  14990. var startDate = BABYLON.Tools.Now;
  14991. this._particlesDuration = 0;
  14992. this._spritesDuration = 0;
  14993. this._activeParticles = 0;
  14994. this._renderDuration = 0;
  14995. this._renderTargetsDuration = 0;
  14996. this._evaluateActiveMeshesDuration = 0;
  14997. this._totalVertices = 0;
  14998. this._activeIndices = 0;
  14999. this._activeBones = 0;
  15000. this.getEngine().resetDrawCalls();
  15001. this._meshesForIntersections.reset();
  15002. this.resetCachedMaterial();
  15003. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15004. // Actions
  15005. if (this.actionManager) {
  15006. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15007. }
  15008. //Simplification Queue
  15009. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15010. this.simplificationQueue.executeNext();
  15011. }
  15012. // Animations
  15013. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15014. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15015. this._animate();
  15016. // Physics
  15017. if (this._physicsEngine) {
  15018. BABYLON.Tools.StartPerformanceCounter("Physics");
  15019. this._physicsEngine._step(deltaTime / 1000.0);
  15020. BABYLON.Tools.EndPerformanceCounter("Physics");
  15021. }
  15022. // Before render
  15023. if (this.beforeRender) {
  15024. this.beforeRender();
  15025. }
  15026. var callbackIndex;
  15027. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15028. this._onBeforeRenderCallbacks[callbackIndex]();
  15029. }
  15030. // Customs render targets
  15031. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15032. var engine = this.getEngine();
  15033. var currentActiveCamera = this.activeCamera;
  15034. if (this.renderTargetsEnabled) {
  15035. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15036. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15037. var renderTarget = this.customRenderTargets[customIndex];
  15038. if (renderTarget._shouldRender()) {
  15039. this._renderId++;
  15040. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15041. if (!this.activeCamera)
  15042. throw new Error("Active camera not set");
  15043. // Viewport
  15044. engine.setViewport(this.activeCamera.viewport);
  15045. // Camera
  15046. this.updateTransformMatrix();
  15047. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15048. }
  15049. }
  15050. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15051. this._renderId++;
  15052. }
  15053. if (this.customRenderTargets.length > 0) {
  15054. engine.restoreDefaultFramebuffer();
  15055. }
  15056. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15057. this.activeCamera = currentActiveCamera;
  15058. // Procedural textures
  15059. if (this.proceduralTexturesEnabled) {
  15060. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15061. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15062. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15063. if (proceduralTexture._shouldRender()) {
  15064. proceduralTexture.render();
  15065. }
  15066. }
  15067. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15068. }
  15069. // Clear
  15070. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15071. // Shadows
  15072. if (this.shadowsEnabled) {
  15073. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15074. var light = this.lights[lightIndex];
  15075. var shadowGenerator = light.getShadowGenerator();
  15076. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15077. this._renderTargets.push(shadowGenerator.getShadowMap());
  15078. }
  15079. }
  15080. }
  15081. // Depth renderer
  15082. if (this._depthRenderer) {
  15083. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15084. }
  15085. // RenderPipeline
  15086. this.postProcessRenderPipelineManager.update();
  15087. // Multi-cameras?
  15088. if (this.activeCameras.length > 0) {
  15089. var currentRenderId = this._renderId;
  15090. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15091. this._renderId = currentRenderId;
  15092. if (cameraIndex > 0) {
  15093. this._engine.clear(0, false, true);
  15094. }
  15095. this._processSubCameras(this.activeCameras[cameraIndex]);
  15096. }
  15097. }
  15098. else {
  15099. if (!this.activeCamera) {
  15100. throw new Error("No camera defined");
  15101. }
  15102. this._processSubCameras(this.activeCamera);
  15103. }
  15104. // Intersection checks
  15105. this._checkIntersections();
  15106. // Update the audio listener attached to the camera
  15107. if (BABYLON.AudioEngine) {
  15108. this._updateAudioParameters();
  15109. }
  15110. // After render
  15111. if (this.afterRender) {
  15112. this.afterRender();
  15113. }
  15114. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15115. this._onAfterRenderCallbacks[callbackIndex]();
  15116. }
  15117. // Cleaning
  15118. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15119. this._toBeDisposed.data[index].dispose();
  15120. this._toBeDisposed[index] = null;
  15121. }
  15122. this._toBeDisposed.reset();
  15123. if (this.dumpNextRenderTargets) {
  15124. this.dumpNextRenderTargets = false;
  15125. }
  15126. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15127. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15128. };
  15129. Scene.prototype._updateAudioParameters = function () {
  15130. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15131. return;
  15132. }
  15133. var listeningCamera;
  15134. var audioEngine = BABYLON.Engine.audioEngine;
  15135. if (this.activeCameras.length > 0) {
  15136. listeningCamera = this.activeCameras[0];
  15137. }
  15138. else {
  15139. listeningCamera = this.activeCamera;
  15140. }
  15141. if (listeningCamera && audioEngine.canUseWebAudio) {
  15142. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15143. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15144. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15145. cameraDirection.normalize();
  15146. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15147. var i;
  15148. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15149. var sound = this.mainSoundTrack.soundCollection[i];
  15150. if (sound.useCustomAttenuation) {
  15151. sound.updateDistanceFromListener();
  15152. }
  15153. }
  15154. for (i = 0; i < this.soundTracks.length; i++) {
  15155. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15156. sound = this.soundTracks[i].soundCollection[j];
  15157. if (sound.useCustomAttenuation) {
  15158. sound.updateDistanceFromListener();
  15159. }
  15160. }
  15161. }
  15162. }
  15163. };
  15164. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15165. // Audio
  15166. get: function () {
  15167. return this._audioEnabled;
  15168. },
  15169. set: function (value) {
  15170. this._audioEnabled = value;
  15171. if (BABYLON.AudioEngine) {
  15172. if (this._audioEnabled) {
  15173. this._enableAudio();
  15174. }
  15175. else {
  15176. this._disableAudio();
  15177. }
  15178. }
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. Scene.prototype._disableAudio = function () {
  15184. var i;
  15185. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15186. this.mainSoundTrack.soundCollection[i].pause();
  15187. }
  15188. for (i = 0; i < this.soundTracks.length; i++) {
  15189. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15190. this.soundTracks[i].soundCollection[j].pause();
  15191. }
  15192. }
  15193. };
  15194. Scene.prototype._enableAudio = function () {
  15195. var i;
  15196. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15197. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15198. this.mainSoundTrack.soundCollection[i].play();
  15199. }
  15200. }
  15201. for (i = 0; i < this.soundTracks.length; i++) {
  15202. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15203. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15204. this.soundTracks[i].soundCollection[j].play();
  15205. }
  15206. }
  15207. }
  15208. };
  15209. Object.defineProperty(Scene.prototype, "headphone", {
  15210. get: function () {
  15211. return this._headphone;
  15212. },
  15213. set: function (value) {
  15214. this._headphone = value;
  15215. if (BABYLON.AudioEngine) {
  15216. if (this._headphone) {
  15217. this._switchAudioModeForHeadphones();
  15218. }
  15219. else {
  15220. this._switchAudioModeForNormalSpeakers();
  15221. }
  15222. }
  15223. },
  15224. enumerable: true,
  15225. configurable: true
  15226. });
  15227. Scene.prototype._switchAudioModeForHeadphones = function () {
  15228. this.mainSoundTrack.switchPanningModelToHRTF();
  15229. for (var i = 0; i < this.soundTracks.length; i++) {
  15230. this.soundTracks[i].switchPanningModelToHRTF();
  15231. }
  15232. };
  15233. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15234. this.mainSoundTrack.switchPanningModelToEqualPower();
  15235. for (var i = 0; i < this.soundTracks.length; i++) {
  15236. this.soundTracks[i].switchPanningModelToEqualPower();
  15237. }
  15238. };
  15239. Scene.prototype.enableDepthRenderer = function () {
  15240. if (this._depthRenderer) {
  15241. return this._depthRenderer;
  15242. }
  15243. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15244. return this._depthRenderer;
  15245. };
  15246. Scene.prototype.disableDepthRenderer = function () {
  15247. if (!this._depthRenderer) {
  15248. return;
  15249. }
  15250. this._depthRenderer.dispose();
  15251. this._depthRenderer = null;
  15252. };
  15253. Scene.prototype.freezeMaterials = function () {
  15254. for (var i = 0; i < this.materials.length; i++) {
  15255. this.materials[i].freeze();
  15256. }
  15257. };
  15258. Scene.prototype.unfreezeMaterials = function () {
  15259. for (var i = 0; i < this.materials.length; i++) {
  15260. this.materials[i].unfreeze();
  15261. }
  15262. };
  15263. Scene.prototype.dispose = function () {
  15264. this.beforeRender = null;
  15265. this.afterRender = null;
  15266. this.skeletons = [];
  15267. this._boundingBoxRenderer.dispose();
  15268. if (this._depthRenderer) {
  15269. this._depthRenderer.dispose();
  15270. }
  15271. // Debug layer
  15272. this.debugLayer.hide();
  15273. // Events
  15274. if (this.onDispose) {
  15275. this.onDispose();
  15276. }
  15277. this._onBeforeRenderCallbacks = [];
  15278. this._onAfterRenderCallbacks = [];
  15279. this.detachControl();
  15280. // Release sounds & sounds tracks
  15281. if (BABYLON.AudioEngine) {
  15282. this.disposeSounds();
  15283. }
  15284. // Detach cameras
  15285. var canvas = this._engine.getRenderingCanvas();
  15286. var index;
  15287. for (index = 0; index < this.cameras.length; index++) {
  15288. this.cameras[index].detachControl(canvas);
  15289. }
  15290. // Release lights
  15291. while (this.lights.length) {
  15292. this.lights[0].dispose();
  15293. }
  15294. // Release meshes
  15295. while (this.meshes.length) {
  15296. this.meshes[0].dispose(true);
  15297. }
  15298. // Release cameras
  15299. while (this.cameras.length) {
  15300. this.cameras[0].dispose();
  15301. }
  15302. // Release materials
  15303. while (this.materials.length) {
  15304. this.materials[0].dispose();
  15305. }
  15306. // Release particles
  15307. while (this.particleSystems.length) {
  15308. this.particleSystems[0].dispose();
  15309. }
  15310. // Release sprites
  15311. while (this.spriteManagers.length) {
  15312. this.spriteManagers[0].dispose();
  15313. }
  15314. // Release layers
  15315. while (this.layers.length) {
  15316. this.layers[0].dispose();
  15317. }
  15318. // Release textures
  15319. while (this.textures.length) {
  15320. this.textures[0].dispose();
  15321. }
  15322. // Post-processes
  15323. this.postProcessManager.dispose();
  15324. // Physics
  15325. if (this._physicsEngine) {
  15326. this.disablePhysicsEngine();
  15327. }
  15328. // Remove from engine
  15329. index = this._engine.scenes.indexOf(this);
  15330. if (index > -1) {
  15331. this._engine.scenes.splice(index, 1);
  15332. }
  15333. this._engine.wipeCaches();
  15334. };
  15335. // Release sounds & sounds tracks
  15336. Scene.prototype.disposeSounds = function () {
  15337. this.mainSoundTrack.dispose();
  15338. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15339. this.soundTracks[scIndex].dispose();
  15340. }
  15341. };
  15342. // Octrees
  15343. Scene.prototype.getWorldExtends = function () {
  15344. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15345. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15346. for (var index = 0; index < this.meshes.length; index++) {
  15347. var mesh = this.meshes[index];
  15348. mesh.computeWorldMatrix(true);
  15349. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  15350. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  15351. BABYLON.Tools.CheckExtends(minBox, min, max);
  15352. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15353. }
  15354. return {
  15355. min: min,
  15356. max: max
  15357. };
  15358. };
  15359. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  15360. if (maxCapacity === void 0) { maxCapacity = 64; }
  15361. if (maxDepth === void 0) { maxDepth = 2; }
  15362. if (!this._selectionOctree) {
  15363. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  15364. }
  15365. var worldExtends = this.getWorldExtends();
  15366. // Update octree
  15367. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  15368. return this._selectionOctree;
  15369. };
  15370. // Picking
  15371. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  15372. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  15373. var engine = this._engine;
  15374. if (!camera) {
  15375. if (!this.activeCamera)
  15376. throw new Error("Active camera not set");
  15377. camera = this.activeCamera;
  15378. }
  15379. var cameraViewport = camera.viewport;
  15380. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15381. // Moving coordinates to local viewport world
  15382. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15383. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15384. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  15385. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  15386. };
  15387. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  15388. var engine = this._engine;
  15389. if (!camera) {
  15390. if (!this.activeCamera)
  15391. throw new Error("Active camera not set");
  15392. camera = this.activeCamera;
  15393. }
  15394. var cameraViewport = camera.viewport;
  15395. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15396. var identity = BABYLON.Matrix.Identity();
  15397. // Moving coordinates to local viewport world
  15398. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15399. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15400. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  15401. };
  15402. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  15403. var pickingInfo = null;
  15404. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  15405. var mesh = this.meshes[meshIndex];
  15406. if (predicate) {
  15407. if (!predicate(mesh)) {
  15408. continue;
  15409. }
  15410. }
  15411. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  15412. continue;
  15413. }
  15414. var world = mesh.getWorldMatrix();
  15415. var ray = rayFunction(world);
  15416. var result = mesh.intersects(ray, fastCheck);
  15417. if (!result || !result.hit)
  15418. continue;
  15419. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15420. continue;
  15421. pickingInfo = result;
  15422. if (fastCheck) {
  15423. break;
  15424. }
  15425. }
  15426. return pickingInfo || new BABYLON.PickingInfo();
  15427. };
  15428. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  15429. var pickingInfo = null;
  15430. camera = camera || this.activeCamera;
  15431. if (this.spriteManagers.length > 0) {
  15432. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  15433. var spriteManager = this.spriteManagers[spriteIndex];
  15434. if (!spriteManager.isPickable) {
  15435. continue;
  15436. }
  15437. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  15438. if (!result || !result.hit)
  15439. continue;
  15440. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15441. continue;
  15442. pickingInfo = result;
  15443. if (fastCheck) {
  15444. break;
  15445. }
  15446. }
  15447. }
  15448. return pickingInfo || new BABYLON.PickingInfo();
  15449. };
  15450. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  15451. var _this = this;
  15452. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15453. /// <param name="x">X position on screen</param>
  15454. /// <param name="y">Y position on screen</param>
  15455. /// <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>
  15456. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15457. /// <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>
  15458. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  15459. };
  15460. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  15461. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15462. /// <param name="x">X position on screen</param>
  15463. /// <param name="y">Y position on screen</param>
  15464. /// <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>
  15465. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15466. /// <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>
  15467. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  15468. };
  15469. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  15470. var _this = this;
  15471. return this._internalPick(function (world) {
  15472. if (!_this._pickWithRayInverseMatrix) {
  15473. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  15474. }
  15475. world.invertToRef(_this._pickWithRayInverseMatrix);
  15476. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  15477. }, predicate, fastCheck);
  15478. };
  15479. Scene.prototype.setPointerOverMesh = function (mesh) {
  15480. if (this._pointerOverMesh === mesh) {
  15481. return;
  15482. }
  15483. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15484. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15485. }
  15486. this._pointerOverMesh = mesh;
  15487. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15488. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15489. }
  15490. };
  15491. Scene.prototype.getPointerOverMesh = function () {
  15492. return this._pointerOverMesh;
  15493. };
  15494. Scene.prototype.setPointerOverSprite = function (sprite) {
  15495. if (this._pointerOverSprite === sprite) {
  15496. return;
  15497. }
  15498. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15499. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15500. }
  15501. this._pointerOverSprite = sprite;
  15502. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15503. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15504. }
  15505. };
  15506. Scene.prototype.getPointerOverSprite = function () {
  15507. return this._pointerOverSprite;
  15508. };
  15509. // Physics
  15510. Scene.prototype.getPhysicsEngine = function () {
  15511. return this._physicsEngine;
  15512. };
  15513. /**
  15514. * Enables physics to the current scene
  15515. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  15516. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  15517. * @return {boolean} was the physics engine initialized
  15518. */
  15519. Scene.prototype.enablePhysics = function (gravity, plugin) {
  15520. if (this._physicsEngine) {
  15521. return true;
  15522. }
  15523. try {
  15524. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  15525. return true;
  15526. }
  15527. catch (e) {
  15528. BABYLON.Tools.Error(e.message);
  15529. return false;
  15530. }
  15531. };
  15532. Scene.prototype.disablePhysicsEngine = function () {
  15533. if (!this._physicsEngine) {
  15534. return;
  15535. }
  15536. this._physicsEngine.dispose();
  15537. this._physicsEngine = undefined;
  15538. };
  15539. Scene.prototype.isPhysicsEnabled = function () {
  15540. return this._physicsEngine !== undefined;
  15541. };
  15542. /**
  15543. *
  15544. * Sets the gravity of the physics engine (and NOT of the scene)
  15545. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  15546. */
  15547. Scene.prototype.setGravity = function (gravity) {
  15548. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  15549. if (!this._physicsEngine) {
  15550. return;
  15551. }
  15552. this._physicsEngine.setGravity(gravity);
  15553. };
  15554. /**
  15555. * Legacy support, using the new API
  15556. * @Deprecated
  15557. */
  15558. Scene.prototype.createCompoundImpostor = function (parts, options) {
  15559. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  15560. if (parts.parts) {
  15561. options = parts;
  15562. parts = parts.parts;
  15563. }
  15564. var mainMesh = parts[0].mesh;
  15565. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  15566. for (var index = 1; index < parts.length; index++) {
  15567. var mesh = parts[index].mesh;
  15568. if (mesh.parent !== mainMesh) {
  15569. mesh.position = mesh.position.subtract(mainMesh.position);
  15570. mesh.parent = mainMesh;
  15571. }
  15572. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  15573. }
  15574. mainMesh.physicsImpostor.forceUpdate();
  15575. };
  15576. Scene.prototype.deleteCompoundImpostor = function (compound) {
  15577. var mesh = compound.parts[0].mesh;
  15578. mesh.physicsImpostor.dispose(true);
  15579. mesh.physicsImpostor = null;
  15580. };
  15581. // Misc.
  15582. Scene.prototype.createDefaultCameraOrLight = function () {
  15583. // Light
  15584. if (this.lights.length === 0) {
  15585. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  15586. }
  15587. // Camera
  15588. if (!this.activeCamera) {
  15589. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  15590. // Compute position
  15591. var worldExtends = this.getWorldExtends();
  15592. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  15593. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  15594. camera.setTarget(worldCenter);
  15595. this.activeCamera = camera;
  15596. }
  15597. };
  15598. // Tags
  15599. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  15600. if (tagsQuery === undefined) {
  15601. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  15602. return list;
  15603. }
  15604. var listByTags = [];
  15605. forEach = forEach || (function (item) { return; });
  15606. for (var i in list) {
  15607. var item = list[i];
  15608. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  15609. listByTags.push(item);
  15610. forEach(item);
  15611. }
  15612. }
  15613. return listByTags;
  15614. };
  15615. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  15616. return this._getByTags(this.meshes, tagsQuery, forEach);
  15617. };
  15618. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  15619. return this._getByTags(this.cameras, tagsQuery, forEach);
  15620. };
  15621. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  15622. return this._getByTags(this.lights, tagsQuery, forEach);
  15623. };
  15624. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  15625. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  15626. };
  15627. // Statics
  15628. Scene._FOGMODE_NONE = 0;
  15629. Scene._FOGMODE_EXP = 1;
  15630. Scene._FOGMODE_EXP2 = 2;
  15631. Scene._FOGMODE_LINEAR = 3;
  15632. Scene.MinDeltaTime = 1.0;
  15633. Scene.MaxDeltaTime = 1000.0;
  15634. return Scene;
  15635. })();
  15636. BABYLON.Scene = Scene;
  15637. })(BABYLON || (BABYLON = {}));
  15638. var BABYLON;
  15639. (function (BABYLON) {
  15640. var VertexBuffer = (function () {
  15641. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  15642. if (engine instanceof BABYLON.Mesh) {
  15643. this._engine = engine.getScene().getEngine();
  15644. }
  15645. else {
  15646. this._engine = engine;
  15647. }
  15648. this._updatable = updatable;
  15649. this._data = data;
  15650. if (!postponeInternalCreation) {
  15651. this.create();
  15652. }
  15653. this._kind = kind;
  15654. if (stride) {
  15655. this._strideSize = stride;
  15656. return;
  15657. }
  15658. // Deduce stride from kind
  15659. switch (kind) {
  15660. case VertexBuffer.PositionKind:
  15661. this._strideSize = 3;
  15662. break;
  15663. case VertexBuffer.NormalKind:
  15664. this._strideSize = 3;
  15665. break;
  15666. case VertexBuffer.UVKind:
  15667. case VertexBuffer.UV2Kind:
  15668. case VertexBuffer.UV3Kind:
  15669. case VertexBuffer.UV4Kind:
  15670. case VertexBuffer.UV5Kind:
  15671. case VertexBuffer.UV6Kind:
  15672. this._strideSize = 2;
  15673. break;
  15674. case VertexBuffer.ColorKind:
  15675. this._strideSize = 4;
  15676. break;
  15677. case VertexBuffer.MatricesIndicesKind:
  15678. case VertexBuffer.MatricesIndicesExtraKind:
  15679. this._strideSize = 4;
  15680. break;
  15681. case VertexBuffer.MatricesWeightsKind:
  15682. case VertexBuffer.MatricesWeightsExtraKind:
  15683. this._strideSize = 4;
  15684. break;
  15685. }
  15686. }
  15687. // Properties
  15688. VertexBuffer.prototype.isUpdatable = function () {
  15689. return this._updatable;
  15690. };
  15691. VertexBuffer.prototype.getData = function () {
  15692. return this._data;
  15693. };
  15694. VertexBuffer.prototype.getBuffer = function () {
  15695. return this._buffer;
  15696. };
  15697. VertexBuffer.prototype.getStrideSize = function () {
  15698. return this._strideSize;
  15699. };
  15700. // Methods
  15701. VertexBuffer.prototype.create = function (data) {
  15702. if (!data && this._buffer) {
  15703. return; // nothing to do
  15704. }
  15705. data = data || this._data;
  15706. if (!this._buffer) {
  15707. if (this._updatable) {
  15708. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  15709. }
  15710. else {
  15711. this._buffer = this._engine.createVertexBuffer(data);
  15712. }
  15713. }
  15714. if (this._updatable) {
  15715. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  15716. this._data = data;
  15717. }
  15718. };
  15719. VertexBuffer.prototype.update = function (data) {
  15720. this.create(data);
  15721. };
  15722. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  15723. if (!this._buffer) {
  15724. return;
  15725. }
  15726. if (this._updatable) {
  15727. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  15728. this._data = null;
  15729. }
  15730. };
  15731. VertexBuffer.prototype.dispose = function () {
  15732. if (!this._buffer) {
  15733. return;
  15734. }
  15735. if (this._engine._releaseBuffer(this._buffer)) {
  15736. this._buffer = null;
  15737. }
  15738. };
  15739. Object.defineProperty(VertexBuffer, "PositionKind", {
  15740. get: function () {
  15741. return VertexBuffer._PositionKind;
  15742. },
  15743. enumerable: true,
  15744. configurable: true
  15745. });
  15746. Object.defineProperty(VertexBuffer, "NormalKind", {
  15747. get: function () {
  15748. return VertexBuffer._NormalKind;
  15749. },
  15750. enumerable: true,
  15751. configurable: true
  15752. });
  15753. Object.defineProperty(VertexBuffer, "UVKind", {
  15754. get: function () {
  15755. return VertexBuffer._UVKind;
  15756. },
  15757. enumerable: true,
  15758. configurable: true
  15759. });
  15760. Object.defineProperty(VertexBuffer, "UV2Kind", {
  15761. get: function () {
  15762. return VertexBuffer._UV2Kind;
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. Object.defineProperty(VertexBuffer, "UV3Kind", {
  15768. get: function () {
  15769. return VertexBuffer._UV3Kind;
  15770. },
  15771. enumerable: true,
  15772. configurable: true
  15773. });
  15774. Object.defineProperty(VertexBuffer, "UV4Kind", {
  15775. get: function () {
  15776. return VertexBuffer._UV4Kind;
  15777. },
  15778. enumerable: true,
  15779. configurable: true
  15780. });
  15781. Object.defineProperty(VertexBuffer, "UV5Kind", {
  15782. get: function () {
  15783. return VertexBuffer._UV5Kind;
  15784. },
  15785. enumerable: true,
  15786. configurable: true
  15787. });
  15788. Object.defineProperty(VertexBuffer, "UV6Kind", {
  15789. get: function () {
  15790. return VertexBuffer._UV6Kind;
  15791. },
  15792. enumerable: true,
  15793. configurable: true
  15794. });
  15795. Object.defineProperty(VertexBuffer, "ColorKind", {
  15796. get: function () {
  15797. return VertexBuffer._ColorKind;
  15798. },
  15799. enumerable: true,
  15800. configurable: true
  15801. });
  15802. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  15803. get: function () {
  15804. return VertexBuffer._MatricesIndicesKind;
  15805. },
  15806. enumerable: true,
  15807. configurable: true
  15808. });
  15809. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  15810. get: function () {
  15811. return VertexBuffer._MatricesWeightsKind;
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  15817. get: function () {
  15818. return VertexBuffer._MatricesIndicesExtraKind;
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  15824. get: function () {
  15825. return VertexBuffer._MatricesWeightsExtraKind;
  15826. },
  15827. enumerable: true,
  15828. configurable: true
  15829. });
  15830. // Enums
  15831. VertexBuffer._PositionKind = "position";
  15832. VertexBuffer._NormalKind = "normal";
  15833. VertexBuffer._UVKind = "uv";
  15834. VertexBuffer._UV2Kind = "uv2";
  15835. VertexBuffer._UV3Kind = "uv3";
  15836. VertexBuffer._UV4Kind = "uv4";
  15837. VertexBuffer._UV5Kind = "uv5";
  15838. VertexBuffer._UV6Kind = "uv6";
  15839. VertexBuffer._ColorKind = "color";
  15840. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  15841. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  15842. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  15843. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  15844. return VertexBuffer;
  15845. })();
  15846. BABYLON.VertexBuffer = VertexBuffer;
  15847. })(BABYLON || (BABYLON = {}));
  15848. var BABYLON;
  15849. (function (BABYLON) {
  15850. /**
  15851. * Creates an instance based on a source mesh.
  15852. */
  15853. var InstancedMesh = (function (_super) {
  15854. __extends(InstancedMesh, _super);
  15855. function InstancedMesh(name, source) {
  15856. _super.call(this, name, source.getScene());
  15857. source.instances.push(this);
  15858. this._sourceMesh = source;
  15859. this.position.copyFrom(source.position);
  15860. this.rotation.copyFrom(source.rotation);
  15861. this.scaling.copyFrom(source.scaling);
  15862. if (source.rotationQuaternion) {
  15863. this.rotationQuaternion = source.rotationQuaternion.clone();
  15864. }
  15865. this.infiniteDistance = source.infiniteDistance;
  15866. this.setPivotMatrix(source.getPivotMatrix());
  15867. this.refreshBoundingInfo();
  15868. this._syncSubMeshes();
  15869. }
  15870. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  15871. // Methods
  15872. get: function () {
  15873. return this._sourceMesh.receiveShadows;
  15874. },
  15875. enumerable: true,
  15876. configurable: true
  15877. });
  15878. Object.defineProperty(InstancedMesh.prototype, "material", {
  15879. get: function () {
  15880. return this._sourceMesh.material;
  15881. },
  15882. enumerable: true,
  15883. configurable: true
  15884. });
  15885. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  15886. get: function () {
  15887. return this._sourceMesh.visibility;
  15888. },
  15889. enumerable: true,
  15890. configurable: true
  15891. });
  15892. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  15893. get: function () {
  15894. return this._sourceMesh.skeleton;
  15895. },
  15896. enumerable: true,
  15897. configurable: true
  15898. });
  15899. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  15900. get: function () {
  15901. return this._sourceMesh.renderingGroupId;
  15902. },
  15903. enumerable: true,
  15904. configurable: true
  15905. });
  15906. InstancedMesh.prototype.getTotalVertices = function () {
  15907. return this._sourceMesh.getTotalVertices();
  15908. };
  15909. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  15910. get: function () {
  15911. return this._sourceMesh;
  15912. },
  15913. enumerable: true,
  15914. configurable: true
  15915. });
  15916. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15917. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  15918. };
  15919. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  15920. return this._sourceMesh.isVerticesDataPresent(kind);
  15921. };
  15922. InstancedMesh.prototype.getIndices = function () {
  15923. return this._sourceMesh.getIndices();
  15924. };
  15925. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  15926. get: function () {
  15927. return this._sourceMesh._positions;
  15928. },
  15929. enumerable: true,
  15930. configurable: true
  15931. });
  15932. InstancedMesh.prototype.refreshBoundingInfo = function () {
  15933. var meshBB = this._sourceMesh.getBoundingInfo();
  15934. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  15935. this._updateBoundingInfo();
  15936. };
  15937. InstancedMesh.prototype._preActivate = function () {
  15938. if (this._currentLOD) {
  15939. this._currentLOD._preActivate();
  15940. }
  15941. };
  15942. InstancedMesh.prototype._activate = function (renderId) {
  15943. if (this._currentLOD) {
  15944. this._currentLOD._registerInstanceForRenderId(this, renderId);
  15945. }
  15946. };
  15947. InstancedMesh.prototype.getLOD = function (camera) {
  15948. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  15949. if (this._currentLOD === this.sourceMesh) {
  15950. return this;
  15951. }
  15952. return this._currentLOD;
  15953. };
  15954. InstancedMesh.prototype._syncSubMeshes = function () {
  15955. this.releaseSubMeshes();
  15956. if (this._sourceMesh.subMeshes) {
  15957. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15958. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15959. }
  15960. }
  15961. };
  15962. InstancedMesh.prototype._generatePointsArray = function () {
  15963. return this._sourceMesh._generatePointsArray();
  15964. };
  15965. // Clone
  15966. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15967. var result = this._sourceMesh.createInstance(name);
  15968. // Deep copy
  15969. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  15970. // Bounding info
  15971. this.refreshBoundingInfo();
  15972. // Parent
  15973. if (newParent) {
  15974. result.parent = newParent;
  15975. }
  15976. if (!doNotCloneChildren) {
  15977. // Children
  15978. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15979. var mesh = this.getScene().meshes[index];
  15980. if (mesh.parent === this) {
  15981. mesh.clone(mesh.name, result);
  15982. }
  15983. }
  15984. }
  15985. result.computeWorldMatrix(true);
  15986. return result;
  15987. };
  15988. // Dispoe
  15989. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  15990. // Remove from mesh
  15991. var index = this._sourceMesh.instances.indexOf(this);
  15992. this._sourceMesh.instances.splice(index, 1);
  15993. _super.prototype.dispose.call(this, doNotRecurse);
  15994. };
  15995. return InstancedMesh;
  15996. })(BABYLON.AbstractMesh);
  15997. BABYLON.InstancedMesh = InstancedMesh;
  15998. })(BABYLON || (BABYLON = {}));
  15999. var BABYLON;
  16000. (function (BABYLON) {
  16001. var _InstancesBatch = (function () {
  16002. function _InstancesBatch() {
  16003. this.mustReturn = false;
  16004. this.visibleInstances = new Array();
  16005. this.renderSelf = new Array();
  16006. }
  16007. return _InstancesBatch;
  16008. })();
  16009. BABYLON._InstancesBatch = _InstancesBatch;
  16010. var Mesh = (function (_super) {
  16011. __extends(Mesh, _super);
  16012. /**
  16013. * @constructor
  16014. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16015. * @param {Scene} scene - The scene to add this mesh to.
  16016. * @param {Node} parent - The parent of this mesh, if it has one
  16017. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16018. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16019. * When false, achieved by calling a clone(), also passing False.
  16020. * This will make creation of children, recursive.
  16021. */
  16022. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  16023. if (parent === void 0) { parent = null; }
  16024. _super.call(this, name, scene);
  16025. // Members
  16026. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16027. this.instances = new Array();
  16028. this._LODLevels = new Array();
  16029. this._onBeforeRenderCallbacks = new Array();
  16030. this._onAfterRenderCallbacks = new Array();
  16031. this._visibleInstances = {};
  16032. this._renderIdForInstances = new Array();
  16033. this._batchCache = new _InstancesBatch();
  16034. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16035. this._sideOrientation = Mesh._DEFAULTSIDE;
  16036. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16037. if (source) {
  16038. // Geometry
  16039. if (source._geometry) {
  16040. source._geometry.applyToMesh(this);
  16041. }
  16042. // Deep copy
  16043. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16044. // Pivot
  16045. this.setPivotMatrix(source.getPivotMatrix());
  16046. this.id = name + "." + source.id;
  16047. // Material
  16048. this.material = source.material;
  16049. var index;
  16050. if (!doNotCloneChildren) {
  16051. // Children
  16052. for (index = 0; index < scene.meshes.length; index++) {
  16053. var mesh = scene.meshes[index];
  16054. if (mesh.parent === source) {
  16055. // doNotCloneChildren is always going to be False
  16056. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16057. }
  16058. }
  16059. }
  16060. // Particles
  16061. for (index = 0; index < scene.particleSystems.length; index++) {
  16062. var system = scene.particleSystems[index];
  16063. if (system.emitter === source) {
  16064. system.clone(system.name, this);
  16065. }
  16066. }
  16067. this.computeWorldMatrix(true);
  16068. }
  16069. // Parent
  16070. if (parent !== null) {
  16071. this.parent = parent;
  16072. }
  16073. }
  16074. Object.defineProperty(Mesh, "FRONTSIDE", {
  16075. get: function () {
  16076. return Mesh._FRONTSIDE;
  16077. },
  16078. enumerable: true,
  16079. configurable: true
  16080. });
  16081. Object.defineProperty(Mesh, "BACKSIDE", {
  16082. get: function () {
  16083. return Mesh._BACKSIDE;
  16084. },
  16085. enumerable: true,
  16086. configurable: true
  16087. });
  16088. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16089. get: function () {
  16090. return Mesh._DOUBLESIDE;
  16091. },
  16092. enumerable: true,
  16093. configurable: true
  16094. });
  16095. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16096. get: function () {
  16097. return Mesh._DEFAULTSIDE;
  16098. },
  16099. enumerable: true,
  16100. configurable: true
  16101. });
  16102. Object.defineProperty(Mesh, "NO_CAP", {
  16103. get: function () {
  16104. return Mesh._NO_CAP;
  16105. },
  16106. enumerable: true,
  16107. configurable: true
  16108. });
  16109. Object.defineProperty(Mesh, "CAP_START", {
  16110. get: function () {
  16111. return Mesh._CAP_START;
  16112. },
  16113. enumerable: true,
  16114. configurable: true
  16115. });
  16116. Object.defineProperty(Mesh, "CAP_END", {
  16117. get: function () {
  16118. return Mesh._CAP_END;
  16119. },
  16120. enumerable: true,
  16121. configurable: true
  16122. });
  16123. Object.defineProperty(Mesh, "CAP_ALL", {
  16124. get: function () {
  16125. return Mesh._CAP_ALL;
  16126. },
  16127. enumerable: true,
  16128. configurable: true
  16129. });
  16130. // Methods
  16131. /**
  16132. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16133. */
  16134. Mesh.prototype.toString = function (fullDetails) {
  16135. var ret = _super.prototype.toString.call(this, fullDetails);
  16136. ret += ", n vertices: " + this.getTotalVertices();
  16137. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16138. if (this.animations) {
  16139. for (var i = 0; i < this.animations.length; i++) {
  16140. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16141. }
  16142. }
  16143. if (fullDetails) {
  16144. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16145. }
  16146. return ret;
  16147. };
  16148. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16149. get: function () {
  16150. return this._LODLevels.length > 0;
  16151. },
  16152. enumerable: true,
  16153. configurable: true
  16154. });
  16155. Mesh.prototype._sortLODLevels = function () {
  16156. this._LODLevels.sort(function (a, b) {
  16157. if (a.distance < b.distance) {
  16158. return 1;
  16159. }
  16160. if (a.distance > b.distance) {
  16161. return -1;
  16162. }
  16163. return 0;
  16164. });
  16165. };
  16166. /**
  16167. * Add a mesh as LOD level triggered at the given distance.
  16168. * @param {number} distance - the distance from the center of the object to show this level
  16169. * @param {Mesh} mesh - the mesh to be added as LOD level
  16170. * @return {Mesh} this mesh (for chaining)
  16171. */
  16172. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16173. if (mesh && mesh._masterMesh) {
  16174. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16175. return this;
  16176. }
  16177. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16178. this._LODLevels.push(level);
  16179. if (mesh) {
  16180. mesh._masterMesh = this;
  16181. }
  16182. this._sortLODLevels();
  16183. return this;
  16184. };
  16185. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16186. for (var index = 0; index < this._LODLevels.length; index++) {
  16187. var level = this._LODLevels[index];
  16188. if (level.distance === distance) {
  16189. return level.mesh;
  16190. }
  16191. }
  16192. return null;
  16193. };
  16194. /**
  16195. * Remove a mesh from the LOD array
  16196. * @param {Mesh} mesh - the mesh to be removed.
  16197. * @return {Mesh} this mesh (for chaining)
  16198. */
  16199. Mesh.prototype.removeLODLevel = function (mesh) {
  16200. for (var index = 0; index < this._LODLevels.length; index++) {
  16201. if (this._LODLevels[index].mesh === mesh) {
  16202. this._LODLevels.splice(index, 1);
  16203. if (mesh) {
  16204. mesh._masterMesh = null;
  16205. }
  16206. }
  16207. }
  16208. this._sortLODLevels();
  16209. return this;
  16210. };
  16211. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16212. if (!this._LODLevels || this._LODLevels.length === 0) {
  16213. return this;
  16214. }
  16215. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  16216. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16217. if (this.onLODLevelSelection) {
  16218. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16219. }
  16220. return this;
  16221. }
  16222. for (var index = 0; index < this._LODLevels.length; index++) {
  16223. var level = this._LODLevels[index];
  16224. if (level.distance < distanceToCamera) {
  16225. if (level.mesh) {
  16226. level.mesh._preActivate();
  16227. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16228. }
  16229. if (this.onLODLevelSelection) {
  16230. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16231. }
  16232. return level.mesh;
  16233. }
  16234. }
  16235. if (this.onLODLevelSelection) {
  16236. this.onLODLevelSelection(distanceToCamera, this, this);
  16237. }
  16238. return this;
  16239. };
  16240. Object.defineProperty(Mesh.prototype, "geometry", {
  16241. get: function () {
  16242. return this._geometry;
  16243. },
  16244. enumerable: true,
  16245. configurable: true
  16246. });
  16247. Mesh.prototype.getTotalVertices = function () {
  16248. if (!this._geometry) {
  16249. return 0;
  16250. }
  16251. return this._geometry.getTotalVertices();
  16252. };
  16253. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16254. if (!this._geometry) {
  16255. return null;
  16256. }
  16257. return this._geometry.getVerticesData(kind, copyWhenShared);
  16258. };
  16259. Mesh.prototype.getVertexBuffer = function (kind) {
  16260. if (!this._geometry) {
  16261. return undefined;
  16262. }
  16263. return this._geometry.getVertexBuffer(kind);
  16264. };
  16265. Mesh.prototype.isVerticesDataPresent = function (kind) {
  16266. if (!this._geometry) {
  16267. if (this._delayInfo) {
  16268. return this._delayInfo.indexOf(kind) !== -1;
  16269. }
  16270. return false;
  16271. }
  16272. return this._geometry.isVerticesDataPresent(kind);
  16273. };
  16274. Mesh.prototype.getVerticesDataKinds = function () {
  16275. if (!this._geometry) {
  16276. var result = [];
  16277. if (this._delayInfo) {
  16278. for (var kind in this._delayInfo) {
  16279. result.push(kind);
  16280. }
  16281. }
  16282. return result;
  16283. }
  16284. return this._geometry.getVerticesDataKinds();
  16285. };
  16286. Mesh.prototype.getTotalIndices = function () {
  16287. if (!this._geometry) {
  16288. return 0;
  16289. }
  16290. return this._geometry.getTotalIndices();
  16291. };
  16292. Mesh.prototype.getIndices = function (copyWhenShared) {
  16293. if (!this._geometry) {
  16294. return [];
  16295. }
  16296. return this._geometry.getIndices(copyWhenShared);
  16297. };
  16298. Object.defineProperty(Mesh.prototype, "isBlocked", {
  16299. get: function () {
  16300. return this._masterMesh !== null && this._masterMesh !== undefined;
  16301. },
  16302. enumerable: true,
  16303. configurable: true
  16304. });
  16305. Mesh.prototype.isReady = function () {
  16306. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16307. return false;
  16308. }
  16309. return _super.prototype.isReady.call(this);
  16310. };
  16311. Mesh.prototype.isDisposed = function () {
  16312. return this._isDisposed;
  16313. };
  16314. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  16315. get: function () {
  16316. return this._sideOrientation;
  16317. },
  16318. set: function (sideO) {
  16319. this._sideOrientation = sideO;
  16320. },
  16321. enumerable: true,
  16322. configurable: true
  16323. });
  16324. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  16325. get: function () {
  16326. return this._areNormalsFrozen;
  16327. },
  16328. enumerable: true,
  16329. configurable: true
  16330. });
  16331. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  16332. Mesh.prototype.freezeNormals = function () {
  16333. this._areNormalsFrozen = true;
  16334. };
  16335. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  16336. Mesh.prototype.unfreezeNormals = function () {
  16337. this._areNormalsFrozen = false;
  16338. };
  16339. // Methods
  16340. Mesh.prototype._preActivate = function () {
  16341. var sceneRenderId = this.getScene().getRenderId();
  16342. if (this._preActivateId === sceneRenderId) {
  16343. return;
  16344. }
  16345. this._preActivateId = sceneRenderId;
  16346. this._visibleInstances = null;
  16347. };
  16348. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  16349. if (!this._visibleInstances) {
  16350. this._visibleInstances = {};
  16351. this._visibleInstances.defaultRenderId = renderId;
  16352. this._visibleInstances.selfDefaultRenderId = this._renderId;
  16353. }
  16354. if (!this._visibleInstances[renderId]) {
  16355. this._visibleInstances[renderId] = new Array();
  16356. }
  16357. this._visibleInstances[renderId].push(instance);
  16358. };
  16359. Mesh.prototype.refreshBoundingInfo = function () {
  16360. if (this._boundingInfo.isLocked) {
  16361. return;
  16362. }
  16363. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16364. if (data) {
  16365. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  16366. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16367. }
  16368. if (this.subMeshes) {
  16369. for (var index = 0; index < this.subMeshes.length; index++) {
  16370. this.subMeshes[index].refreshBoundingInfo();
  16371. }
  16372. }
  16373. this._updateBoundingInfo();
  16374. };
  16375. Mesh.prototype._createGlobalSubMesh = function () {
  16376. var totalVertices = this.getTotalVertices();
  16377. if (!totalVertices || !this.getIndices()) {
  16378. return null;
  16379. }
  16380. this.releaseSubMeshes();
  16381. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  16382. };
  16383. Mesh.prototype.subdivide = function (count) {
  16384. if (count < 1) {
  16385. return;
  16386. }
  16387. var totalIndices = this.getTotalIndices();
  16388. var subdivisionSize = (totalIndices / count) | 0;
  16389. var offset = 0;
  16390. // Ensure that subdivisionSize is a multiple of 3
  16391. while (subdivisionSize % 3 !== 0) {
  16392. subdivisionSize++;
  16393. }
  16394. this.releaseSubMeshes();
  16395. for (var index = 0; index < count; index++) {
  16396. if (offset >= totalIndices) {
  16397. break;
  16398. }
  16399. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  16400. offset += subdivisionSize;
  16401. }
  16402. this.synchronizeInstances();
  16403. };
  16404. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16405. if (!this._geometry) {
  16406. var vertexData = new BABYLON.VertexData();
  16407. vertexData.set(data, kind);
  16408. var scene = this.getScene();
  16409. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  16410. }
  16411. else {
  16412. this._geometry.setVerticesData(kind, data, updatable, stride);
  16413. }
  16414. };
  16415. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16416. if (!this._geometry) {
  16417. return;
  16418. }
  16419. if (!makeItUnique) {
  16420. this._geometry.updateVerticesData(kind, data, updateExtends);
  16421. }
  16422. else {
  16423. this.makeGeometryUnique();
  16424. this.updateVerticesData(kind, data, updateExtends, false);
  16425. }
  16426. };
  16427. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  16428. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  16429. if (!this._geometry) {
  16430. return;
  16431. }
  16432. if (!makeItUnique) {
  16433. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  16434. }
  16435. else {
  16436. this.makeGeometryUnique();
  16437. this.updateVerticesDataDirectly(kind, data, offset, false);
  16438. }
  16439. };
  16440. // Mesh positions update function :
  16441. // updates the mesh positions according to the positionFunction returned values.
  16442. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  16443. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  16444. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  16445. if (computeNormals === void 0) { computeNormals = true; }
  16446. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16447. positionFunction(positions);
  16448. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16449. if (computeNormals) {
  16450. var indices = this.getIndices();
  16451. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16452. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16453. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16454. }
  16455. };
  16456. Mesh.prototype.makeGeometryUnique = function () {
  16457. if (!this._geometry) {
  16458. return;
  16459. }
  16460. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  16461. geometry.applyToMesh(this);
  16462. };
  16463. Mesh.prototype.setIndices = function (indices, totalVertices) {
  16464. if (!this._geometry) {
  16465. var vertexData = new BABYLON.VertexData();
  16466. vertexData.indices = indices;
  16467. var scene = this.getScene();
  16468. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  16469. }
  16470. else {
  16471. this._geometry.setIndices(indices, totalVertices);
  16472. }
  16473. };
  16474. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  16475. var engine = this.getScene().getEngine();
  16476. // Wireframe
  16477. var indexToBind;
  16478. if (this._unIndexed) {
  16479. indexToBind = null;
  16480. }
  16481. else {
  16482. switch (fillMode) {
  16483. case BABYLON.Material.PointFillMode:
  16484. indexToBind = null;
  16485. break;
  16486. case BABYLON.Material.WireFrameFillMode:
  16487. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  16488. break;
  16489. default:
  16490. case BABYLON.Material.TriangleFillMode:
  16491. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  16492. break;
  16493. }
  16494. }
  16495. // VBOs
  16496. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  16497. };
  16498. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  16499. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16500. return;
  16501. }
  16502. if (this.onBeforeDraw) {
  16503. this.onBeforeDraw();
  16504. }
  16505. var engine = this.getScene().getEngine();
  16506. // Draw order
  16507. switch (fillMode) {
  16508. case BABYLON.Material.PointFillMode:
  16509. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16510. break;
  16511. case BABYLON.Material.WireFrameFillMode:
  16512. if (this._unIndexed) {
  16513. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16514. }
  16515. else {
  16516. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  16517. }
  16518. break;
  16519. default:
  16520. if (this._unIndexed) {
  16521. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16522. }
  16523. else {
  16524. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  16525. }
  16526. }
  16527. };
  16528. Mesh.prototype.registerBeforeRender = function (func) {
  16529. this._onBeforeRenderCallbacks.push(func);
  16530. };
  16531. Mesh.prototype.unregisterBeforeRender = function (func) {
  16532. var index = this._onBeforeRenderCallbacks.indexOf(func);
  16533. if (index > -1) {
  16534. this._onBeforeRenderCallbacks.splice(index, 1);
  16535. }
  16536. };
  16537. Mesh.prototype.registerAfterRender = function (func) {
  16538. this._onAfterRenderCallbacks.push(func);
  16539. };
  16540. Mesh.prototype.unregisterAfterRender = function (func) {
  16541. var index = this._onAfterRenderCallbacks.indexOf(func);
  16542. if (index > -1) {
  16543. this._onAfterRenderCallbacks.splice(index, 1);
  16544. }
  16545. };
  16546. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  16547. var scene = this.getScene();
  16548. this._batchCache.mustReturn = false;
  16549. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  16550. this._batchCache.visibleInstances[subMeshId] = null;
  16551. if (this._visibleInstances) {
  16552. var currentRenderId = scene.getRenderId();
  16553. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  16554. var selfRenderId = this._renderId;
  16555. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  16556. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  16557. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  16558. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  16559. }
  16560. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  16561. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  16562. this._batchCache.mustReturn = true;
  16563. return this._batchCache;
  16564. }
  16565. if (currentRenderId !== selfRenderId) {
  16566. this._batchCache.renderSelf[subMeshId] = false;
  16567. }
  16568. }
  16569. this._renderIdForInstances[subMeshId] = currentRenderId;
  16570. }
  16571. return this._batchCache;
  16572. };
  16573. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  16574. var visibleInstances = batch.visibleInstances[subMesh._id];
  16575. var matricesCount = visibleInstances.length + 1;
  16576. var bufferSize = matricesCount * 16 * 4;
  16577. while (this._instancesBufferSize < bufferSize) {
  16578. this._instancesBufferSize *= 2;
  16579. }
  16580. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  16581. if (this._worldMatricesInstancesBuffer) {
  16582. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  16583. }
  16584. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  16585. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  16586. }
  16587. var offset = 0;
  16588. var instancesCount = 0;
  16589. var world = this.getWorldMatrix();
  16590. if (batch.renderSelf[subMesh._id]) {
  16591. world.copyToArray(this._worldMatricesInstancesArray, offset);
  16592. offset += 16;
  16593. instancesCount++;
  16594. }
  16595. if (visibleInstances) {
  16596. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  16597. var instance = visibleInstances[instanceIndex];
  16598. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  16599. offset += 16;
  16600. instancesCount++;
  16601. }
  16602. }
  16603. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  16604. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  16605. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  16606. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  16607. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  16608. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  16609. this._draw(subMesh, fillMode, instancesCount);
  16610. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  16611. };
  16612. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  16613. var scene = this.getScene();
  16614. var engine = scene.getEngine();
  16615. if (hardwareInstancedRendering) {
  16616. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  16617. }
  16618. else {
  16619. if (batch.renderSelf[subMesh._id]) {
  16620. // Draw
  16621. if (onBeforeDraw) {
  16622. onBeforeDraw(false, this.getWorldMatrix());
  16623. }
  16624. this._draw(subMesh, fillMode);
  16625. }
  16626. if (batch.visibleInstances[subMesh._id]) {
  16627. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  16628. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  16629. // World
  16630. var world = instance.getWorldMatrix();
  16631. if (onBeforeDraw) {
  16632. onBeforeDraw(true, world);
  16633. }
  16634. // Draw
  16635. this._draw(subMesh, fillMode);
  16636. }
  16637. }
  16638. }
  16639. };
  16640. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  16641. var scene = this.getScene();
  16642. // Managing instances
  16643. var batch = this._getInstancesRenderList(subMesh._id);
  16644. if (batch.mustReturn) {
  16645. return;
  16646. }
  16647. // Checking geometry state
  16648. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16649. return;
  16650. }
  16651. var callbackIndex;
  16652. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  16653. this._onBeforeRenderCallbacks[callbackIndex](this);
  16654. }
  16655. var engine = scene.getEngine();
  16656. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  16657. // Material
  16658. var effectiveMaterial = subMesh.getMaterial();
  16659. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  16660. return;
  16661. }
  16662. // Outline - step 1
  16663. var savedDepthWrite = engine.getDepthWrite();
  16664. if (this.renderOutline) {
  16665. engine.setDepthWrite(false);
  16666. scene.getOutlineRenderer().render(subMesh, batch);
  16667. engine.setDepthWrite(savedDepthWrite);
  16668. }
  16669. effectiveMaterial._preBind();
  16670. var effect = effectiveMaterial.getEffect();
  16671. // Bind
  16672. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  16673. this._bind(subMesh, effect, fillMode);
  16674. var world = this.getWorldMatrix();
  16675. effectiveMaterial.bind(world, this);
  16676. // Alpha mode
  16677. if (enableAlphaMode) {
  16678. engine.setAlphaMode(effectiveMaterial.alphaMode);
  16679. }
  16680. // Draw
  16681. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  16682. if (isInstance) {
  16683. effectiveMaterial.bindOnlyWorldMatrix(world);
  16684. }
  16685. });
  16686. // Unbind
  16687. effectiveMaterial.unbind();
  16688. // Outline - step 2
  16689. if (this.renderOutline && savedDepthWrite) {
  16690. engine.setDepthWrite(true);
  16691. engine.setColorWrite(false);
  16692. scene.getOutlineRenderer().render(subMesh, batch);
  16693. engine.setColorWrite(true);
  16694. }
  16695. // Overlay
  16696. if (this.renderOverlay) {
  16697. var currentMode = engine.getAlphaMode();
  16698. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16699. scene.getOutlineRenderer().render(subMesh, batch, true);
  16700. engine.setAlphaMode(currentMode);
  16701. }
  16702. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  16703. this._onAfterRenderCallbacks[callbackIndex](this);
  16704. }
  16705. };
  16706. Mesh.prototype.getEmittedParticleSystems = function () {
  16707. var results = new Array();
  16708. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  16709. var particleSystem = this.getScene().particleSystems[index];
  16710. if (particleSystem.emitter === this) {
  16711. results.push(particleSystem);
  16712. }
  16713. }
  16714. return results;
  16715. };
  16716. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  16717. var results = new Array();
  16718. var descendants = this.getDescendants();
  16719. descendants.push(this);
  16720. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  16721. var particleSystem = this.getScene().particleSystems[index];
  16722. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  16723. results.push(particleSystem);
  16724. }
  16725. }
  16726. return results;
  16727. };
  16728. Mesh.prototype._checkDelayState = function () {
  16729. var _this = this;
  16730. var that = this;
  16731. var scene = this.getScene();
  16732. if (this._geometry) {
  16733. this._geometry.load(scene);
  16734. }
  16735. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16736. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  16737. scene._addPendingData(that);
  16738. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  16739. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  16740. if (data instanceof ArrayBuffer) {
  16741. _this._delayLoadingFunction(data, _this);
  16742. }
  16743. else {
  16744. _this._delayLoadingFunction(JSON.parse(data), _this);
  16745. }
  16746. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16747. scene._removePendingData(_this);
  16748. }, function () { }, scene.database, getBinaryData);
  16749. }
  16750. };
  16751. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  16752. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16753. return false;
  16754. }
  16755. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  16756. return false;
  16757. }
  16758. this._checkDelayState();
  16759. return true;
  16760. };
  16761. Mesh.prototype.setMaterialByID = function (id) {
  16762. var materials = this.getScene().materials;
  16763. var index;
  16764. for (index = 0; index < materials.length; index++) {
  16765. if (materials[index].id === id) {
  16766. this.material = materials[index];
  16767. return;
  16768. }
  16769. }
  16770. // Multi
  16771. var multiMaterials = this.getScene().multiMaterials;
  16772. for (index = 0; index < multiMaterials.length; index++) {
  16773. if (multiMaterials[index].id === id) {
  16774. this.material = multiMaterials[index];
  16775. return;
  16776. }
  16777. }
  16778. };
  16779. Mesh.prototype.getAnimatables = function () {
  16780. var results = [];
  16781. if (this.material) {
  16782. results.push(this.material);
  16783. }
  16784. if (this.skeleton) {
  16785. results.push(this.skeleton);
  16786. }
  16787. return results;
  16788. };
  16789. // Geometry
  16790. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  16791. // Position
  16792. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16793. return;
  16794. }
  16795. this._resetPointsArrayCache();
  16796. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16797. var temp = [];
  16798. var index;
  16799. for (index = 0; index < data.length; index += 3) {
  16800. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  16801. }
  16802. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  16803. // Normals
  16804. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16805. return;
  16806. }
  16807. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16808. temp = [];
  16809. for (index = 0; index < data.length; index += 3) {
  16810. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  16811. }
  16812. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  16813. // flip faces?
  16814. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  16815. this.flipFaces();
  16816. }
  16817. };
  16818. // Will apply current transform to mesh and reset world matrix
  16819. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  16820. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  16821. this.scaling.copyFromFloats(1, 1, 1);
  16822. this.position.copyFromFloats(0, 0, 0);
  16823. this.rotation.copyFromFloats(0, 0, 0);
  16824. //only if quaternion is already set
  16825. if (this.rotationQuaternion) {
  16826. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  16827. }
  16828. this._worldMatrix = BABYLON.Matrix.Identity();
  16829. };
  16830. // Cache
  16831. Mesh.prototype._resetPointsArrayCache = function () {
  16832. this._positions = null;
  16833. };
  16834. Mesh.prototype._generatePointsArray = function () {
  16835. if (this._positions)
  16836. return true;
  16837. this._positions = [];
  16838. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16839. if (!data) {
  16840. return false;
  16841. }
  16842. for (var index = 0; index < data.length; index += 3) {
  16843. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  16844. }
  16845. return true;
  16846. };
  16847. // Clone
  16848. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16849. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  16850. };
  16851. // Dispose
  16852. Mesh.prototype.dispose = function (doNotRecurse) {
  16853. if (this._geometry) {
  16854. this._geometry.releaseForMesh(this, true);
  16855. }
  16856. // Instances
  16857. if (this._worldMatricesInstancesBuffer) {
  16858. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  16859. this._worldMatricesInstancesBuffer = null;
  16860. }
  16861. while (this.instances.length) {
  16862. this.instances[0].dispose();
  16863. }
  16864. _super.prototype.dispose.call(this, doNotRecurse);
  16865. };
  16866. // Geometric tools
  16867. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  16868. var _this = this;
  16869. var scene = this.getScene();
  16870. var onload = function (img) {
  16871. // Getting height map data
  16872. var canvas = document.createElement("canvas");
  16873. var context = canvas.getContext("2d");
  16874. var heightMapWidth = img.width;
  16875. var heightMapHeight = img.height;
  16876. canvas.width = heightMapWidth;
  16877. canvas.height = heightMapHeight;
  16878. context.drawImage(img, 0, 0);
  16879. // Create VertexData from map data
  16880. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16881. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  16882. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  16883. //execute success callback, if set
  16884. if (onSuccess) {
  16885. onSuccess(_this);
  16886. }
  16887. };
  16888. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16889. };
  16890. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  16891. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  16892. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  16893. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16894. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  16895. return;
  16896. }
  16897. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16898. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16899. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16900. var position = BABYLON.Vector3.Zero();
  16901. var normal = BABYLON.Vector3.Zero();
  16902. var uv = BABYLON.Vector2.Zero();
  16903. for (var index = 0; index < positions.length; index += 3) {
  16904. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  16905. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  16906. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  16907. // Compute height
  16908. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  16909. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  16910. var pos = (u + v * heightMapWidth) * 4;
  16911. var r = buffer[pos] / 255.0;
  16912. var g = buffer[pos + 1] / 255.0;
  16913. var b = buffer[pos + 2] / 255.0;
  16914. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16915. normal.normalize();
  16916. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  16917. position = position.add(normal);
  16918. position.toArray(positions, index);
  16919. }
  16920. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  16921. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  16922. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16923. };
  16924. Mesh.prototype.convertToFlatShadedMesh = function () {
  16925. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  16926. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16927. var kinds = this.getVerticesDataKinds();
  16928. var vbs = [];
  16929. var data = [];
  16930. var newdata = [];
  16931. var updatableNormals = false;
  16932. var kindIndex;
  16933. var kind;
  16934. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16935. kind = kinds[kindIndex];
  16936. var vertexBuffer = this.getVertexBuffer(kind);
  16937. if (kind === BABYLON.VertexBuffer.NormalKind) {
  16938. updatableNormals = vertexBuffer.isUpdatable();
  16939. kinds.splice(kindIndex, 1);
  16940. kindIndex--;
  16941. continue;
  16942. }
  16943. vbs[kind] = vertexBuffer;
  16944. data[kind] = vbs[kind].getData();
  16945. newdata[kind] = [];
  16946. }
  16947. // Save previous submeshes
  16948. var previousSubmeshes = this.subMeshes.slice(0);
  16949. var indices = this.getIndices();
  16950. var totalIndices = this.getTotalIndices();
  16951. // Generating unique vertices per face
  16952. var index;
  16953. for (index = 0; index < totalIndices; index++) {
  16954. var vertexIndex = indices[index];
  16955. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16956. kind = kinds[kindIndex];
  16957. var stride = vbs[kind].getStrideSize();
  16958. for (var offset = 0; offset < stride; offset++) {
  16959. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16960. }
  16961. }
  16962. }
  16963. // Updating faces & normal
  16964. var normals = [];
  16965. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  16966. for (index = 0; index < totalIndices; index += 3) {
  16967. indices[index] = index;
  16968. indices[index + 1] = index + 1;
  16969. indices[index + 2] = index + 2;
  16970. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  16971. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  16972. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  16973. var p1p2 = p1.subtract(p2);
  16974. var p3p2 = p3.subtract(p2);
  16975. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16976. // Store same normals for every vertex
  16977. for (var localIndex = 0; localIndex < 3; localIndex++) {
  16978. normals.push(normal.x);
  16979. normals.push(normal.y);
  16980. normals.push(normal.z);
  16981. }
  16982. }
  16983. this.setIndices(indices);
  16984. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  16985. // Updating vertex buffers
  16986. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16987. kind = kinds[kindIndex];
  16988. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16989. }
  16990. // Updating submeshes
  16991. this.releaseSubMeshes();
  16992. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16993. var previousOne = previousSubmeshes[submeshIndex];
  16994. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16995. }
  16996. this.synchronizeInstances();
  16997. };
  16998. Mesh.prototype.convertToUnIndexedMesh = function () {
  16999. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17000. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17001. var kinds = this.getVerticesDataKinds();
  17002. var vbs = [];
  17003. var data = [];
  17004. var newdata = [];
  17005. var updatableNormals = false;
  17006. var kindIndex;
  17007. var kind;
  17008. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17009. kind = kinds[kindIndex];
  17010. var vertexBuffer = this.getVertexBuffer(kind);
  17011. vbs[kind] = vertexBuffer;
  17012. data[kind] = vbs[kind].getData();
  17013. newdata[kind] = [];
  17014. }
  17015. // Save previous submeshes
  17016. var previousSubmeshes = this.subMeshes.slice(0);
  17017. var indices = this.getIndices();
  17018. var totalIndices = this.getTotalIndices();
  17019. // Generating unique vertices per face
  17020. var index;
  17021. for (index = 0; index < totalIndices; index++) {
  17022. var vertexIndex = indices[index];
  17023. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17024. kind = kinds[kindIndex];
  17025. var stride = vbs[kind].getStrideSize();
  17026. for (var offset = 0; offset < stride; offset++) {
  17027. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17028. }
  17029. }
  17030. }
  17031. // Updating indices
  17032. for (index = 0; index < totalIndices; index += 3) {
  17033. indices[index] = index;
  17034. indices[index + 1] = index + 1;
  17035. indices[index + 2] = index + 2;
  17036. }
  17037. this.setIndices(indices);
  17038. // Updating vertex buffers
  17039. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17040. kind = kinds[kindIndex];
  17041. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17042. }
  17043. // Updating submeshes
  17044. this.releaseSubMeshes();
  17045. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17046. var previousOne = previousSubmeshes[submeshIndex];
  17047. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17048. }
  17049. this._unIndexed = true;
  17050. this.synchronizeInstances();
  17051. };
  17052. // will inverse faces orientations, and invert normals too if specified
  17053. Mesh.prototype.flipFaces = function (flipNormals) {
  17054. if (flipNormals === void 0) { flipNormals = false; }
  17055. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17056. var i;
  17057. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17058. for (i = 0; i < vertex_data.normals.length; i++) {
  17059. vertex_data.normals[i] *= -1;
  17060. }
  17061. }
  17062. var temp;
  17063. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17064. // reassign indices
  17065. temp = vertex_data.indices[i + 1];
  17066. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17067. vertex_data.indices[i + 2] = temp;
  17068. }
  17069. vertex_data.applyToMesh(this);
  17070. };
  17071. // Instances
  17072. Mesh.prototype.createInstance = function (name) {
  17073. return new BABYLON.InstancedMesh(name, this);
  17074. };
  17075. Mesh.prototype.synchronizeInstances = function () {
  17076. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17077. var instance = this.instances[instanceIndex];
  17078. instance._syncSubMeshes();
  17079. }
  17080. };
  17081. /**
  17082. * Simplify the mesh according to the given array of settings.
  17083. * Function will return immediately and will simplify async.
  17084. * @param settings a collection of simplification settings.
  17085. * @param parallelProcessing should all levels calculate parallel or one after the other.
  17086. * @param type the type of simplification to run.
  17087. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  17088. */
  17089. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  17090. if (parallelProcessing === void 0) { parallelProcessing = true; }
  17091. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  17092. this.getScene().simplificationQueue.addTask({
  17093. settings: settings,
  17094. parallelProcessing: parallelProcessing,
  17095. mesh: this,
  17096. simplificationType: simplificationType,
  17097. successCallback: successCallback
  17098. });
  17099. };
  17100. /**
  17101. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  17102. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  17103. * This should be used together with the simplification to avoid disappearing triangles.
  17104. * @param successCallback an optional success callback to be called after the optimization finished.
  17105. */
  17106. Mesh.prototype.optimizeIndices = function (successCallback) {
  17107. var _this = this;
  17108. var indices = this.getIndices();
  17109. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17110. var vectorPositions = [];
  17111. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  17112. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  17113. }
  17114. var dupes = [];
  17115. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  17116. var realPos = vectorPositions.length - 1 - iteration;
  17117. var testedPosition = vectorPositions[realPos];
  17118. for (var j = 0; j < realPos; ++j) {
  17119. var againstPosition = vectorPositions[j];
  17120. if (testedPosition.equals(againstPosition)) {
  17121. dupes[realPos] = j;
  17122. break;
  17123. }
  17124. }
  17125. }, function () {
  17126. for (var i = 0; i < indices.length; ++i) {
  17127. indices[i] = dupes[indices[i]] || indices[i];
  17128. }
  17129. //indices are now reordered
  17130. var originalSubMeshes = _this.subMeshes.slice(0);
  17131. _this.setIndices(indices);
  17132. _this.subMeshes = originalSubMeshes;
  17133. if (successCallback) {
  17134. successCallback(_this);
  17135. }
  17136. });
  17137. };
  17138. // Statics
  17139. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  17140. var mesh = new Mesh(parsedMesh.name, scene);
  17141. mesh.id = parsedMesh.id;
  17142. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17143. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17144. if (parsedMesh.rotationQuaternion) {
  17145. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17146. }
  17147. else if (parsedMesh.rotation) {
  17148. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17149. }
  17150. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17151. if (parsedMesh.localMatrix) {
  17152. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17153. }
  17154. else if (parsedMesh.pivotMatrix) {
  17155. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17156. }
  17157. mesh.setEnabled(parsedMesh.isEnabled);
  17158. mesh.isVisible = parsedMesh.isVisible;
  17159. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17160. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17161. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17162. if (parsedMesh.applyFog !== undefined) {
  17163. mesh.applyFog = parsedMesh.applyFog;
  17164. }
  17165. if (parsedMesh.pickable !== undefined) {
  17166. mesh.isPickable = parsedMesh.pickable;
  17167. }
  17168. if (parsedMesh.alphaIndex !== undefined) {
  17169. mesh.alphaIndex = parsedMesh.alphaIndex;
  17170. }
  17171. mesh.receiveShadows = parsedMesh.receiveShadows;
  17172. mesh.billboardMode = parsedMesh.billboardMode;
  17173. if (parsedMesh.visibility !== undefined) {
  17174. mesh.visibility = parsedMesh.visibility;
  17175. }
  17176. mesh.checkCollisions = parsedMesh.checkCollisions;
  17177. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17178. // freezeWorldMatrix
  17179. if (parsedMesh.freezeWorldMatrix) {
  17180. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  17181. }
  17182. // Parent
  17183. if (parsedMesh.parentId) {
  17184. mesh._waitingParentId = parsedMesh.parentId;
  17185. }
  17186. // Actions
  17187. if (parsedMesh.actions !== undefined) {
  17188. mesh._waitingActions = parsedMesh.actions;
  17189. }
  17190. // Geometry
  17191. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17192. if (parsedMesh.delayLoadingFile) {
  17193. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17194. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17195. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17196. if (parsedMesh._binaryInfo) {
  17197. mesh._binaryInfo = parsedMesh._binaryInfo;
  17198. }
  17199. mesh._delayInfo = [];
  17200. if (parsedMesh.hasUVs) {
  17201. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17202. }
  17203. if (parsedMesh.hasUVs2) {
  17204. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17205. }
  17206. if (parsedMesh.hasUVs3) {
  17207. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  17208. }
  17209. if (parsedMesh.hasUVs4) {
  17210. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  17211. }
  17212. if (parsedMesh.hasUVs5) {
  17213. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  17214. }
  17215. if (parsedMesh.hasUVs6) {
  17216. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  17217. }
  17218. if (parsedMesh.hasColors) {
  17219. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17220. }
  17221. if (parsedMesh.hasMatricesIndices) {
  17222. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17223. }
  17224. if (parsedMesh.hasMatricesWeights) {
  17225. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17226. }
  17227. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  17228. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17229. mesh._checkDelayState();
  17230. }
  17231. }
  17232. else {
  17233. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  17234. }
  17235. // Material
  17236. if (parsedMesh.materialId) {
  17237. mesh.setMaterialByID(parsedMesh.materialId);
  17238. }
  17239. else {
  17240. mesh.material = null;
  17241. }
  17242. // Skeleton
  17243. if (parsedMesh.skeletonId > -1) {
  17244. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17245. if (parsedMesh.numBoneInfluencers) {
  17246. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  17247. }
  17248. }
  17249. // Animations
  17250. if (parsedMesh.animations) {
  17251. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17252. var parsedAnimation = parsedMesh.animations[animationIndex];
  17253. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17254. }
  17255. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  17256. }
  17257. if (parsedMesh.autoAnimate) {
  17258. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  17259. }
  17260. // Layer Mask
  17261. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17262. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17263. }
  17264. else {
  17265. mesh.layerMask = 0x0FFFFFFF;
  17266. }
  17267. // Instances
  17268. if (parsedMesh.instances) {
  17269. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17270. var parsedInstance = parsedMesh.instances[index];
  17271. var instance = mesh.createInstance(parsedInstance.name);
  17272. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17273. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17274. if (parsedInstance.rotationQuaternion) {
  17275. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17276. }
  17277. else if (parsedInstance.rotation) {
  17278. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17279. }
  17280. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17281. instance.checkCollisions = mesh.checkCollisions;
  17282. if (parsedMesh.animations) {
  17283. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17284. parsedAnimation = parsedMesh.animations[animationIndex];
  17285. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17286. }
  17287. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  17288. }
  17289. }
  17290. }
  17291. return mesh;
  17292. };
  17293. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  17294. return BABYLON.MeshBuilder.CreateRibbon(name, {
  17295. pathArray: pathArray,
  17296. closeArray: closeArray,
  17297. closePath: closePath,
  17298. offset: offset,
  17299. updatable: updatable,
  17300. sideOrientation: sideOrientation,
  17301. instance: instance
  17302. }, scene);
  17303. };
  17304. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  17305. var options = {
  17306. radius: radius,
  17307. tessellation: tessellation,
  17308. sideOrientation: sideOrientation,
  17309. updatable: updatable
  17310. };
  17311. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  17312. };
  17313. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  17314. var options = {
  17315. size: size,
  17316. sideOrientation: sideOrientation,
  17317. updatable: updatable
  17318. };
  17319. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  17320. };
  17321. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  17322. var options = {
  17323. segments: segments,
  17324. diameterX: diameter,
  17325. diameterY: diameter,
  17326. diameterZ: diameter,
  17327. sideOrientation: sideOrientation,
  17328. updatable: updatable
  17329. };
  17330. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  17331. };
  17332. // Cylinder and cone
  17333. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  17334. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  17335. if (scene !== undefined) {
  17336. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  17337. updatable = scene;
  17338. }
  17339. scene = subdivisions;
  17340. subdivisions = 1;
  17341. }
  17342. var options = {
  17343. height: height,
  17344. diameterTop: diameterTop,
  17345. diameterBottom: diameterBottom,
  17346. tessellation: tessellation,
  17347. subdivisions: subdivisions,
  17348. sideOrientation: sideOrientation,
  17349. updatable: updatable
  17350. };
  17351. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  17352. };
  17353. // Torus (Code from SharpDX.org)
  17354. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  17355. var options = {
  17356. diameter: diameter,
  17357. thickness: thickness,
  17358. tessellation: tessellation,
  17359. sideOrientation: sideOrientation,
  17360. updatable: updatable
  17361. };
  17362. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  17363. };
  17364. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  17365. var options = {
  17366. radius: radius,
  17367. tube: tube,
  17368. radialSegments: radialSegments,
  17369. tubularSegments: tubularSegments,
  17370. p: p,
  17371. q: q,
  17372. sideOrientation: sideOrientation,
  17373. updatable: updatable
  17374. };
  17375. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  17376. };
  17377. // Lines
  17378. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  17379. var options = {
  17380. points: points,
  17381. updatable: updatable,
  17382. instance: instance
  17383. };
  17384. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  17385. };
  17386. // Dashed Lines
  17387. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  17388. var options = {
  17389. points: points,
  17390. dashSize: dashSize,
  17391. gapSize: gapSize,
  17392. dashNb: dashNb,
  17393. updatable: updatable
  17394. };
  17395. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  17396. };
  17397. // Extrusion
  17398. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  17399. var options = {
  17400. shape: shape,
  17401. path: path,
  17402. scale: scale,
  17403. rotation: rotation,
  17404. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17405. sideOrientation: sideOrientation,
  17406. instance: instance,
  17407. updatable: updatable
  17408. };
  17409. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  17410. };
  17411. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  17412. var options = {
  17413. shape: shape,
  17414. path: path,
  17415. scaleFunction: scaleFunction,
  17416. rotationFunction: rotationFunction,
  17417. ribbonCloseArray: ribbonCloseArray,
  17418. ribbonClosePath: ribbonClosePath,
  17419. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17420. sideOrientation: sideOrientation,
  17421. instance: instance,
  17422. updatable: updatable
  17423. };
  17424. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  17425. };
  17426. // Lathe
  17427. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  17428. var options = {
  17429. shape: shape,
  17430. radius: radius,
  17431. tessellation: tessellation,
  17432. sideOrientation: sideOrientation,
  17433. updatable: updatable
  17434. };
  17435. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  17436. };
  17437. // Plane & ground
  17438. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  17439. var options = {
  17440. size: size,
  17441. width: size,
  17442. height: size,
  17443. sideOrientation: sideOrientation,
  17444. updatable: updatable
  17445. };
  17446. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  17447. };
  17448. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  17449. var options = {
  17450. width: width,
  17451. height: height,
  17452. subdivisions: subdivisions,
  17453. updatable: updatable
  17454. };
  17455. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  17456. };
  17457. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  17458. var options = {
  17459. xmin: xmin,
  17460. zmin: zmin,
  17461. xmax: xmax,
  17462. zmax: zmax,
  17463. subdivisions: subdivisions,
  17464. precision: precision,
  17465. updatable: updatable
  17466. };
  17467. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  17468. };
  17469. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  17470. var options = {
  17471. width: width,
  17472. height: height,
  17473. subdivisions: subdivisions,
  17474. minHeight: minHeight,
  17475. maxHeight: maxHeight,
  17476. updatable: updatable,
  17477. onReady: onReady
  17478. };
  17479. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  17480. };
  17481. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  17482. var options = {
  17483. path: path,
  17484. radius: radius,
  17485. tessellation: tessellation,
  17486. radiusFunction: radiusFunction,
  17487. arc: 1,
  17488. cap: cap,
  17489. updatable: updatable,
  17490. sideOrientation: sideOrientation,
  17491. instance: instance
  17492. };
  17493. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  17494. };
  17495. Mesh.CreatePolyhedron = function (name, options, scene) {
  17496. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  17497. };
  17498. Mesh.CreateIcoSphere = function (name, options, scene) {
  17499. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  17500. };
  17501. // Decals
  17502. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  17503. var options = {
  17504. position: position,
  17505. normal: normal,
  17506. size: size,
  17507. angle: angle
  17508. };
  17509. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  17510. };
  17511. // Skeletons
  17512. /**
  17513. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  17514. */
  17515. Mesh.prototype.setPositionsForCPUSkinning = function () {
  17516. var source;
  17517. if (!this._sourcePositions) {
  17518. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17519. this._sourcePositions = new Float32Array(source);
  17520. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  17521. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  17522. }
  17523. }
  17524. return this._sourcePositions;
  17525. };
  17526. /**
  17527. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  17528. */
  17529. Mesh.prototype.setNormalsForCPUSkinning = function () {
  17530. var source;
  17531. if (!this._sourceNormals) {
  17532. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17533. this._sourceNormals = new Float32Array(source);
  17534. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  17535. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  17536. }
  17537. }
  17538. return this._sourceNormals;
  17539. };
  17540. /**
  17541. * Update the vertex buffers by applying transformation from the bones
  17542. * @param {skeleton} skeleton to apply
  17543. */
  17544. Mesh.prototype.applySkeleton = function (skeleton) {
  17545. if (!this.geometry) {
  17546. return;
  17547. }
  17548. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  17549. return;
  17550. }
  17551. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  17552. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17553. return this;
  17554. }
  17555. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17556. return this;
  17557. }
  17558. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17559. return this;
  17560. }
  17561. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17562. return this;
  17563. }
  17564. if (!this._sourcePositions) {
  17565. this.setPositionsForCPUSkinning();
  17566. }
  17567. if (!this._sourceNormals) {
  17568. this.setNormalsForCPUSkinning();
  17569. }
  17570. // positionsData checks for not being Float32Array will only pass at most once
  17571. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17572. if (!(positionsData instanceof Float32Array)) {
  17573. positionsData = new Float32Array(positionsData);
  17574. }
  17575. // normalsData checks for not being Float32Array will only pass at most once
  17576. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17577. if (!(normalsData instanceof Float32Array)) {
  17578. normalsData = new Float32Array(normalsData);
  17579. }
  17580. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17581. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17582. var needExtras = this.numBoneInfluencers > 4;
  17583. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  17584. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  17585. var skeletonMatrices = skeleton.getTransformMatrices(this);
  17586. var tempVector3 = BABYLON.Vector3.Zero();
  17587. var finalMatrix = new BABYLON.Matrix();
  17588. var tempMatrix = new BABYLON.Matrix();
  17589. var matWeightIdx = 0;
  17590. var inf;
  17591. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  17592. var weight;
  17593. for (inf = 0; inf < 4; inf++) {
  17594. weight = matricesWeightsData[matWeightIdx + inf];
  17595. if (weight > 0) {
  17596. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  17597. finalMatrix.addToSelf(tempMatrix);
  17598. }
  17599. else
  17600. break;
  17601. }
  17602. if (needExtras) {
  17603. for (inf = 0; inf < 4; inf++) {
  17604. weight = matricesWeightsExtraData[matWeightIdx + inf];
  17605. if (weight > 0) {
  17606. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  17607. finalMatrix.addToSelf(tempMatrix);
  17608. }
  17609. else
  17610. break;
  17611. }
  17612. }
  17613. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  17614. tempVector3.toArray(positionsData, index);
  17615. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  17616. tempVector3.toArray(normalsData, index);
  17617. finalMatrix.reset();
  17618. }
  17619. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  17620. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  17621. return this;
  17622. };
  17623. // Tools
  17624. Mesh.MinMax = function (meshes) {
  17625. var minVector = null;
  17626. var maxVector = null;
  17627. for (var i in meshes) {
  17628. var mesh = meshes[i];
  17629. var boundingBox = mesh.getBoundingInfo().boundingBox;
  17630. if (!minVector) {
  17631. minVector = boundingBox.minimumWorld;
  17632. maxVector = boundingBox.maximumWorld;
  17633. continue;
  17634. }
  17635. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  17636. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  17637. }
  17638. return {
  17639. min: minVector,
  17640. max: maxVector
  17641. };
  17642. };
  17643. Mesh.Center = function (meshesOrMinMaxVector) {
  17644. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  17645. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  17646. };
  17647. /**
  17648. * Merge the array of meshes into a single mesh for performance reasons.
  17649. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  17650. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  17651. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  17652. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  17653. */
  17654. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  17655. if (disposeSource === void 0) { disposeSource = true; }
  17656. var index;
  17657. if (!allow32BitsIndices) {
  17658. var totalVertices = 0;
  17659. // Counting vertices
  17660. for (index = 0; index < meshes.length; index++) {
  17661. if (meshes[index]) {
  17662. totalVertices += meshes[index].getTotalVertices();
  17663. if (totalVertices > 65536) {
  17664. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  17665. return null;
  17666. }
  17667. }
  17668. }
  17669. }
  17670. // Merge
  17671. var vertexData;
  17672. var otherVertexData;
  17673. var source;
  17674. for (index = 0; index < meshes.length; index++) {
  17675. if (meshes[index]) {
  17676. meshes[index].computeWorldMatrix(true);
  17677. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  17678. otherVertexData.transform(meshes[index].getWorldMatrix());
  17679. if (vertexData) {
  17680. vertexData.merge(otherVertexData);
  17681. }
  17682. else {
  17683. vertexData = otherVertexData;
  17684. source = meshes[index];
  17685. }
  17686. }
  17687. }
  17688. if (!meshSubclass) {
  17689. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  17690. }
  17691. vertexData.applyToMesh(meshSubclass);
  17692. // Setting properties
  17693. meshSubclass.material = source.material;
  17694. meshSubclass.checkCollisions = source.checkCollisions;
  17695. // Cleaning
  17696. if (disposeSource) {
  17697. for (index = 0; index < meshes.length; index++) {
  17698. if (meshes[index]) {
  17699. meshes[index].dispose();
  17700. }
  17701. }
  17702. }
  17703. return meshSubclass;
  17704. };
  17705. // Consts
  17706. Mesh._FRONTSIDE = 0;
  17707. Mesh._BACKSIDE = 1;
  17708. Mesh._DOUBLESIDE = 2;
  17709. Mesh._DEFAULTSIDE = 0;
  17710. Mesh._NO_CAP = 0;
  17711. Mesh._CAP_START = 1;
  17712. Mesh._CAP_END = 2;
  17713. Mesh._CAP_ALL = 3;
  17714. return Mesh;
  17715. })(BABYLON.AbstractMesh);
  17716. BABYLON.Mesh = Mesh;
  17717. })(BABYLON || (BABYLON = {}));
  17718. var BABYLON;
  17719. (function (BABYLON) {
  17720. var SubMesh = (function () {
  17721. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  17722. if (createBoundingBox === void 0) { createBoundingBox = true; }
  17723. this.materialIndex = materialIndex;
  17724. this.verticesStart = verticesStart;
  17725. this.verticesCount = verticesCount;
  17726. this.indexStart = indexStart;
  17727. this.indexCount = indexCount;
  17728. this._renderId = 0;
  17729. this._mesh = mesh;
  17730. this._renderingMesh = renderingMesh || mesh;
  17731. mesh.subMeshes.push(this);
  17732. this._trianglePlanes = [];
  17733. this._id = mesh.subMeshes.length - 1;
  17734. if (createBoundingBox) {
  17735. this.refreshBoundingInfo();
  17736. mesh.computeWorldMatrix(true);
  17737. }
  17738. }
  17739. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  17740. get: function () {
  17741. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. SubMesh.prototype.getBoundingInfo = function () {
  17747. if (this.IsGlobal) {
  17748. return this._mesh.getBoundingInfo();
  17749. }
  17750. return this._boundingInfo;
  17751. };
  17752. SubMesh.prototype.getMesh = function () {
  17753. return this._mesh;
  17754. };
  17755. SubMesh.prototype.getRenderingMesh = function () {
  17756. return this._renderingMesh;
  17757. };
  17758. SubMesh.prototype.getMaterial = function () {
  17759. var rootMaterial = this._renderingMesh.material;
  17760. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  17761. var multiMaterial = rootMaterial;
  17762. return multiMaterial.getSubMaterial(this.materialIndex);
  17763. }
  17764. if (!rootMaterial) {
  17765. return this._mesh.getScene().defaultMaterial;
  17766. }
  17767. return rootMaterial;
  17768. };
  17769. // Methods
  17770. SubMesh.prototype.refreshBoundingInfo = function () {
  17771. this._lastColliderWorldVertices = null;
  17772. if (this.IsGlobal) {
  17773. return;
  17774. }
  17775. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17776. if (!data) {
  17777. this._boundingInfo = this._mesh._boundingInfo;
  17778. return;
  17779. }
  17780. var indices = this._renderingMesh.getIndices();
  17781. var extend;
  17782. //is this the only submesh?
  17783. if (this.indexStart === 0 && this.indexCount === indices.length) {
  17784. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  17785. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  17786. }
  17787. else {
  17788. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  17789. }
  17790. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17791. };
  17792. SubMesh.prototype._checkCollision = function (collider) {
  17793. return this.getBoundingInfo()._checkCollision(collider);
  17794. };
  17795. SubMesh.prototype.updateBoundingInfo = function (world) {
  17796. if (!this.getBoundingInfo()) {
  17797. this.refreshBoundingInfo();
  17798. }
  17799. this.getBoundingInfo().update(world);
  17800. };
  17801. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  17802. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  17803. };
  17804. SubMesh.prototype.render = function (enableAlphaMode) {
  17805. this._renderingMesh.render(this, enableAlphaMode);
  17806. };
  17807. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  17808. if (!this._linesIndexBuffer) {
  17809. var linesIndices = [];
  17810. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  17811. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  17812. }
  17813. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  17814. this.linesIndexCount = linesIndices.length;
  17815. }
  17816. return this._linesIndexBuffer;
  17817. };
  17818. SubMesh.prototype.canIntersects = function (ray) {
  17819. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  17820. };
  17821. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  17822. var intersectInfo = null;
  17823. // Triangles test
  17824. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  17825. var p0 = positions[indices[index]];
  17826. var p1 = positions[indices[index + 1]];
  17827. var p2 = positions[indices[index + 2]];
  17828. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  17829. if (currentIntersectInfo) {
  17830. if (currentIntersectInfo.distance < 0) {
  17831. continue;
  17832. }
  17833. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17834. intersectInfo = currentIntersectInfo;
  17835. intersectInfo.faceId = index / 3;
  17836. if (fastCheck) {
  17837. break;
  17838. }
  17839. }
  17840. }
  17841. }
  17842. return intersectInfo;
  17843. };
  17844. // Clone
  17845. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  17846. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  17847. if (!this.IsGlobal) {
  17848. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  17849. }
  17850. return result;
  17851. };
  17852. // Dispose
  17853. SubMesh.prototype.dispose = function () {
  17854. if (this._linesIndexBuffer) {
  17855. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  17856. this._linesIndexBuffer = null;
  17857. }
  17858. // Remove from mesh
  17859. var index = this._mesh.subMeshes.indexOf(this);
  17860. this._mesh.subMeshes.splice(index, 1);
  17861. };
  17862. // Statics
  17863. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  17864. var minVertexIndex = Number.MAX_VALUE;
  17865. var maxVertexIndex = -Number.MAX_VALUE;
  17866. renderingMesh = renderingMesh || mesh;
  17867. var indices = renderingMesh.getIndices();
  17868. for (var index = startIndex; index < startIndex + indexCount; index++) {
  17869. var vertexIndex = indices[index];
  17870. if (vertexIndex < minVertexIndex)
  17871. minVertexIndex = vertexIndex;
  17872. if (vertexIndex > maxVertexIndex)
  17873. maxVertexIndex = vertexIndex;
  17874. }
  17875. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  17876. };
  17877. return SubMesh;
  17878. })();
  17879. BABYLON.SubMesh = SubMesh;
  17880. })(BABYLON || (BABYLON = {}));
  17881. var BABYLON;
  17882. (function (BABYLON) {
  17883. var MeshBuilder = (function () {
  17884. function MeshBuilder() {
  17885. }
  17886. /**
  17887. * Creates a box mesh.
  17888. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  17889. * The parameter "size" sets the size (float) of each box side (default 1).
  17890. * You can set some different box dimensions by using the parameters "width", "height" and "depth" (all by default have the same value than "size").
  17891. * 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).
  17892. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  17893. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17894. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17895. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17896. */
  17897. MeshBuilder.CreateBox = function (name, options, scene) {
  17898. var box = new BABYLON.Mesh(name, scene);
  17899. var vertexData = BABYLON.VertexData.CreateBox(options);
  17900. vertexData.applyToMesh(box, options.updatable);
  17901. return box;
  17902. };
  17903. /**
  17904. * Creates a sphere mesh.
  17905. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  17906. * The parameter "diameter" sets the diameter size (float) of the sphere (default 1).
  17907. * 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").
  17908. * The parameter "segments" sets the sphere number of horizontal stripes (positive integer, default 32).
  17909. * 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
  17910. * 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).
  17911. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17912. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17913. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17914. */
  17915. MeshBuilder.CreateSphere = function (name, options, scene) {
  17916. var sphere = new BABYLON.Mesh(name, scene);
  17917. var vertexData = BABYLON.VertexData.CreateSphere(options);
  17918. vertexData.applyToMesh(sphere, options.updatable);
  17919. return sphere;
  17920. };
  17921. /**
  17922. * Creates a plane polygonal mesh. By default, this is a disc.
  17923. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  17924. * The parameter "radius" sets the radius size (float) of the polygon (default 0.5).
  17925. * 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.
  17926. * 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
  17927. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17929. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17930. */
  17931. MeshBuilder.CreateDisc = function (name, options, scene) {
  17932. var disc = new BABYLON.Mesh(name, scene);
  17933. var vertexData = BABYLON.VertexData.CreateDisc(options);
  17934. vertexData.applyToMesh(disc, options.updatable);
  17935. return disc;
  17936. };
  17937. /**
  17938. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  17939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  17940. * The parameter "radius" sets the radius size (float) of the icosphere (default 1).
  17941. * 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").
  17942. * The parameter "subdivisions" sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  17943. * 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.
  17944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17945. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17946. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17947. */
  17948. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  17949. var sphere = new BABYLON.Mesh(name, scene);
  17950. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  17951. vertexData.applyToMesh(sphere, options.updatable);
  17952. return sphere;
  17953. };
  17954. ;
  17955. /**
  17956. * Creates a ribbon mesh.
  17957. * 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.
  17958. *
  17959. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  17960. * The parameter "pathArray" is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  17961. * The parameter "closeArray" (boolean, default false) creates a seam between the first and the last paths of the path array.
  17962. * The parameter "closePath" (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  17963. * The optional parameter "instance" is an instance of an existing Ribbon object to be updated with the passed "pathArray" parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  17964. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17965. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17966. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17967. */
  17968. MeshBuilder.CreateRibbon = function (name, options, scene) {
  17969. var pathArray = options.pathArray;
  17970. var closeArray = options.closeArray;
  17971. var closePath = options.closePath;
  17972. var offset = options.offset;
  17973. var sideOrientation = options.sideOrientation;
  17974. var instance = options.instance;
  17975. var updatable = options.updatable;
  17976. if (instance) {
  17977. // positionFunction : ribbon case
  17978. // only pathArray and sideOrientation parameters are taken into account for positions update
  17979. var positionFunction = function (positions) {
  17980. var minlg = pathArray[0].length;
  17981. var i = 0;
  17982. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  17983. for (var si = 1; si <= ns; si++) {
  17984. for (var p = 0; p < pathArray.length; p++) {
  17985. var path = pathArray[p];
  17986. var l = path.length;
  17987. minlg = (minlg < l) ? minlg : l;
  17988. var j = 0;
  17989. while (j < minlg) {
  17990. positions[i] = path[j].x;
  17991. positions[i + 1] = path[j].y;
  17992. positions[i + 2] = path[j].z;
  17993. j++;
  17994. i += 3;
  17995. }
  17996. if (instance._closePath) {
  17997. positions[i] = path[0].x;
  17998. positions[i + 1] = path[0].y;
  17999. positions[i + 2] = path[0].z;
  18000. i += 3;
  18001. }
  18002. }
  18003. }
  18004. };
  18005. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18006. positionFunction(positions);
  18007. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18008. if (!(instance.areNormalsFrozen)) {
  18009. var indices = instance.getIndices();
  18010. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18011. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18012. if (instance._closePath) {
  18013. var indexFirst = 0;
  18014. var indexLast = 0;
  18015. for (var p = 0; p < pathArray.length; p++) {
  18016. indexFirst = instance._idx[p] * 3;
  18017. if (p + 1 < pathArray.length) {
  18018. indexLast = (instance._idx[p + 1] - 1) * 3;
  18019. }
  18020. else {
  18021. indexLast = normals.length - 3;
  18022. }
  18023. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  18024. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  18025. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  18026. normals[indexLast] = normals[indexFirst];
  18027. normals[indexLast + 1] = normals[indexFirst + 1];
  18028. normals[indexLast + 2] = normals[indexFirst + 2];
  18029. }
  18030. }
  18031. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18032. }
  18033. return instance;
  18034. }
  18035. else {
  18036. var ribbon = new BABYLON.Mesh(name, scene);
  18037. ribbon.sideOrientation = sideOrientation;
  18038. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  18039. if (closePath) {
  18040. ribbon._idx = vertexData._idx;
  18041. }
  18042. ribbon._closePath = closePath;
  18043. ribbon._closeArray = closeArray;
  18044. vertexData.applyToMesh(ribbon, updatable);
  18045. return ribbon;
  18046. }
  18047. };
  18048. /**
  18049. * Creates a cylinder or a cone mesh.
  18050. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  18051. * The parameter "height" sets the height size (float) of the cylinder/cone (float, default 2).
  18052. * The parameter "diameter" sets the diameter of the top and bottom cap at once (float, default 1).
  18053. * 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.
  18054. * The parameter "tessellation" sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18055. * The parameter "subdivisions" sets the number of rings along the cylinder height (positive integer, default 1).
  18056. * The parameter "hasRings" (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  18057. * The parameter "enclose" (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  18058. * The parameter "arc" (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  18059. * 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).
  18060. * 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
  18061. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  18062. * 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
  18063. * 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.
  18064. * If enclose is false, a ring surface is one element.
  18065. * If enclose true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  18066. * 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
  18067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18068. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18069. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18070. */
  18071. MeshBuilder.CreateCylinder = function (name, options, scene) {
  18072. var cylinder = new BABYLON.Mesh(name, scene);
  18073. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  18074. vertexData.applyToMesh(cylinder, options.updatable);
  18075. return cylinder;
  18076. };
  18077. /**
  18078. * Creates a torus mesh.
  18079. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  18080. * The parameter "diameter" sets the diameter size (float) of the torus (default 1).
  18081. * The parameter "thickness" sets the diameter size of the tube of the torus (float, default 0.5).
  18082. * The parameter "tessellation" sets the number of torus sides (postive integer, default 16).
  18083. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18084. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18085. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18086. */
  18087. MeshBuilder.CreateTorus = function (name, options, scene) {
  18088. var torus = new BABYLON.Mesh(name, scene);
  18089. var vertexData = BABYLON.VertexData.CreateTorus(options);
  18090. vertexData.applyToMesh(torus, options.updatable);
  18091. return torus;
  18092. };
  18093. /**
  18094. * Creates a torus knot mesh.
  18095. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  18096. * The parameter "radius" sets the global radius size (float) of the torus knot (default 2).
  18097. * The parameter "radialSegments" sets the number of sides on each tube segments (positive integer, default 32).
  18098. * The parameter "tubularSegments" sets the number of tubes to decompose the knot into (positive integer, default 32).
  18099. * The parameters "p" and "q" are the number of windings on each axis (positive integers, default 2 and 3).
  18100. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18101. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18102. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18103. */
  18104. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  18105. var torusKnot = new BABYLON.Mesh(name, scene);
  18106. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  18107. vertexData.applyToMesh(torusKnot, options.updatable);
  18108. return torusKnot;
  18109. };
  18110. /**
  18111. * Creates a line system mesh.
  18112. * A line system is a pool of many lines gathered in a single mesh.
  18113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  18114. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  18115. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  18116. * The parameter "lines" is an array of lines, each line being an array of successive Vector3.
  18117. * The optional parameter "instance" is an instance of an existing LineSystem object to be updated with the passed "lines" parameter. The way to update it is the same than for
  18118. * updating a simple Line mesh, you just need to update every line in the "lines" array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18119. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  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.CreateLineSystem = function (name, options, scene) {
  18123. var instance = options.instance;
  18124. var lines = options.lines;
  18125. if (instance) {
  18126. var positionFunction = function (positions) {
  18127. var i = 0;
  18128. for (var l = 0; l < lines.length; l++) {
  18129. var points = lines[l];
  18130. for (var p = 0; p < points.length; p++) {
  18131. positions[i] = points[p].x;
  18132. positions[i + 1] = points[p].y;
  18133. positions[i + 2] = points[p].z;
  18134. i += 3;
  18135. }
  18136. }
  18137. };
  18138. instance.updateMeshPositions(positionFunction, false);
  18139. return instance;
  18140. }
  18141. // line system creation
  18142. var lineSystem = new BABYLON.LinesMesh(name, scene);
  18143. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  18144. vertexData.applyToMesh(lineSystem, options.updatable);
  18145. return lineSystem;
  18146. };
  18147. /**
  18148. * Creates a line mesh.
  18149. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  18150. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18151. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18152. * The parameter "points" is an array successive Vector3.
  18153. * The optional parameter "instance" is an instance of an existing LineMesh object to be updated with the passed "points" parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18154. * When updating an instance, remember that only point positions can change, not the number of points.
  18155. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18156. */
  18157. MeshBuilder.CreateLines = function (name, options, scene) {
  18158. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  18159. return lines;
  18160. };
  18161. /**
  18162. * Creates a dashed line mesh.
  18163. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  18164. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18165. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18166. * The parameter "points" is an array successive Vector3.
  18167. * The parameter "dashNb" is the intended total number of dashes (positive integer, default 200).
  18168. * The parameter "dashSize" is the size of the dashes relatively the dash number (positive float, default 3).
  18169. * The parameter "gapSize" is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18170. * The optional parameter "instance" is an instance of an existing LineMesh object to be updated with the passed "points" parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18171. * When updating an instance, remember that only point positions can change, not the number of points.
  18172. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  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. /**
  18234. * Creates an extruded shape mesh.
  18235. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18236. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  18237. *
  18238. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18239. * The parameter "shape" is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18240. * extruded along the Z axis.
  18241. * The parameter "path" is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18242. * The parameter "rotation" (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  18243. * The parameter "scale" (float, default 1) is the value to scale the shape.
  18244. * The parameter "cap" sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18245. * The optional parameter "instance" is an instance of an existing ExtrudedShape object to be updated with the passed "shape", "path", "scale" or "rotation" parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18246. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18249. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18250. */
  18251. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  18252. var path = options.path;
  18253. var shape = options.shape;
  18254. var scale = options.scale || 1;
  18255. var rotation = options.rotation || 0;
  18256. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18257. var updatable = options.updatable;
  18258. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18259. var instance = options.instance;
  18260. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  18261. };
  18262. /**
  18263. * Creates an custom extruded shape mesh.
  18264. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18265. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  18266. *
  18267. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18268. * The parameter "shape" is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18269. * extruded along the Z axis.
  18270. * The parameter "path" is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18271. * The parameter "rotationFunction" (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18272. * and the distance of this point from the begining of the path : rotationFunction = function(i, distance) {}.
  18273. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18274. * The parameter "scaleFunction" (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18275. * and the distance of this point from the begining of the path : scaleFunction = function(i, distance) {}.
  18276. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18277. * The parameter "ribbonClosePath" (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its pathArray.
  18278. * The parameter "ribbonCloseArray" (boolean, default false) forces the extrusion underlying ribbon to close its pathArray.
  18279. * The parameter "cap" sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18280. * The optional parameter "instance" is an instance of an existing ExtrudedShape object to be updated with the passed "shape", "path", "scale" or "rotation" parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18281. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18282. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18283. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18284. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18285. */
  18286. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  18287. var path = options.path;
  18288. var shape = options.shape;
  18289. var scaleFunction = options.scaleFunction || (function () { return 1; });
  18290. var rotationFunction = options.rotationFunction || (function () { return 0; });
  18291. var ribbonCloseArray = options.ribbonCloseArray || false;
  18292. var ribbonClosePath = options.ribbonClosePath || false;
  18293. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18294. var updatable = options.updatable;
  18295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18296. var instance = options.instance;
  18297. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  18298. };
  18299. /**
  18300. * Creates lathe mesh.
  18301. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18302. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  18303. *
  18304. * The parameter "shape" is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  18305. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18306. * The parameter "radius" (positive float, default 1) is the radius value of the lathe.
  18307. * The parameter "tessellation" (positive integer, default 64) is the side number of the lathe.
  18308. * The parameter "arc" (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  18309. * The parameter "closed" (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  18310. * The parameter "cap" sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18313. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18314. */
  18315. MeshBuilder.CreateLathe = function (name, options, scene) {
  18316. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  18317. var closed = (options.closed === undefined) ? true : options.closed;
  18318. var shape = options.shape;
  18319. var radius = options.radius || 1;
  18320. var tessellation = options.tessellation || 64;
  18321. var updatable = options.updatable;
  18322. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18323. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  18324. var pi2 = Math.PI * 2;
  18325. var paths = new Array();
  18326. var i = 0;
  18327. var p = 0;
  18328. var step = pi2 / tessellation * arc;
  18329. var rotated;
  18330. var path = new Array();
  18331. ;
  18332. for (i = 0; i <= tessellation; i++) {
  18333. var path = [];
  18334. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  18335. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  18336. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  18337. }
  18338. for (p = 0; p < shape.length; p++) {
  18339. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  18340. path.push(rotated);
  18341. }
  18342. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  18343. 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));
  18344. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  18345. }
  18346. paths.push(path);
  18347. }
  18348. // lathe ribbon
  18349. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  18350. return lathe;
  18351. };
  18352. MeshBuilder.CreatePlane = function (name, options, scene) {
  18353. var plane = new BABYLON.Mesh(name, scene);
  18354. var vertexData = BABYLON.VertexData.CreatePlane(options);
  18355. vertexData.applyToMesh(plane, options.updatable);
  18356. if (options.sourcePlane) {
  18357. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  18358. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  18359. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  18360. plane.rotate(vectorProduct, product);
  18361. }
  18362. return plane;
  18363. };
  18364. MeshBuilder.CreateGround = function (name, options, scene) {
  18365. var ground = new BABYLON.GroundMesh(name, scene);
  18366. ground._setReady(false);
  18367. ground._subdivisions = options.subdivisions || 1;
  18368. ground._width = options.width || 1;
  18369. ground._height = options.height || 1;
  18370. ground._maxX = ground._width / 2;
  18371. ground._maxZ = ground._height / 2;
  18372. ground._minX = -ground._maxX;
  18373. ground._minZ = -ground._maxZ;
  18374. var vertexData = BABYLON.VertexData.CreateGround(options);
  18375. vertexData.applyToMesh(ground, options.updatable);
  18376. ground._setReady(true);
  18377. return ground;
  18378. };
  18379. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  18380. var tiledGround = new BABYLON.Mesh(name, scene);
  18381. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  18382. vertexData.applyToMesh(tiledGround, options.updatable);
  18383. return tiledGround;
  18384. };
  18385. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  18386. var width = options.width || 10;
  18387. var height = options.height || 10;
  18388. var subdivisions = options.subdivisions || 1;
  18389. var minHeight = options.minHeight;
  18390. var maxHeight = options.maxHeight || 10;
  18391. var updatable = options.updatable;
  18392. var onReady = options.onReady;
  18393. var ground = new BABYLON.GroundMesh(name, scene);
  18394. ground._subdivisions = subdivisions;
  18395. ground._width = width;
  18396. ground._height = height;
  18397. ground._maxX = ground._width / 2;
  18398. ground._maxZ = ground._height / 2;
  18399. ground._minX = -ground._maxX;
  18400. ground._minZ = -ground._maxZ;
  18401. ground._setReady(false);
  18402. var onload = function (img) {
  18403. // Getting height map data
  18404. var canvas = document.createElement("canvas");
  18405. var context = canvas.getContext("2d");
  18406. var bufferWidth = img.width;
  18407. var bufferHeight = img.height;
  18408. canvas.width = bufferWidth;
  18409. canvas.height = bufferHeight;
  18410. context.drawImage(img, 0, 0);
  18411. // Create VertexData from map data
  18412. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18413. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  18414. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  18415. width: width, height: height,
  18416. subdivisions: subdivisions,
  18417. minHeight: minHeight, maxHeight: maxHeight,
  18418. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  18419. });
  18420. vertexData.applyToMesh(ground, updatable);
  18421. ground._setReady(true);
  18422. //execute ready callback, if set
  18423. if (onReady) {
  18424. onReady(ground);
  18425. }
  18426. };
  18427. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18428. return ground;
  18429. };
  18430. MeshBuilder.CreateTube = function (name, options, scene) {
  18431. var path = options.path;
  18432. var radius = options.radius || 1;
  18433. var tessellation = options.tessellation || 64;
  18434. var radiusFunction = options.radiusFunction;
  18435. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  18436. var updatable = options.updatable;
  18437. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18438. var instance = options.instance;
  18439. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  18440. // tube geometry
  18441. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  18442. var tangents = path3D.getTangents();
  18443. var normals = path3D.getNormals();
  18444. var distances = path3D.getDistances();
  18445. var pi2 = Math.PI * 2;
  18446. var step = pi2 / tessellation * arc;
  18447. var returnRadius = function () { return radius; };
  18448. var radiusFunctionFinal = radiusFunction || returnRadius;
  18449. var circlePath;
  18450. var rad;
  18451. var normal;
  18452. var rotated;
  18453. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  18454. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  18455. for (var i = 0; i < path.length; i++) {
  18456. rad = radiusFunctionFinal(i, distances[i]); // current radius
  18457. circlePath = Array(); // current circle array
  18458. normal = normals[i]; // current normal
  18459. for (var t = 0; t < tessellation; t++) {
  18460. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  18461. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  18462. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  18463. rotated.scaleInPlace(rad).addInPlace(path[i]);
  18464. circlePath[t] = rotated;
  18465. }
  18466. circlePaths[index] = circlePath;
  18467. index++;
  18468. }
  18469. // cap
  18470. var capPath = function (nbPoints, pathIndex) {
  18471. var pointCap = Array();
  18472. for (var i = 0; i < nbPoints; i++) {
  18473. pointCap.push(path[pathIndex]);
  18474. }
  18475. return pointCap;
  18476. };
  18477. switch (cap) {
  18478. case BABYLON.Mesh.NO_CAP:
  18479. break;
  18480. case BABYLON.Mesh.CAP_START:
  18481. circlePaths[0] = capPath(tessellation, 0);
  18482. circlePaths[1] = circlePaths[2].slice(0);
  18483. break;
  18484. case BABYLON.Mesh.CAP_END:
  18485. circlePaths[index] = circlePaths[index - 1].slice(0);
  18486. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  18487. break;
  18488. case BABYLON.Mesh.CAP_ALL:
  18489. circlePaths[0] = capPath(tessellation, 0);
  18490. circlePaths[1] = circlePaths[2].slice(0);
  18491. circlePaths[index] = circlePaths[index - 1].slice(0);
  18492. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  18493. break;
  18494. default:
  18495. break;
  18496. }
  18497. return circlePaths;
  18498. };
  18499. var path3D;
  18500. var pathArray;
  18501. if (instance) {
  18502. var arc = options.arc || instance.arc;
  18503. path3D = (instance.path3D).update(path);
  18504. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  18505. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  18506. instance.path3D = path3D;
  18507. instance.pathArray = pathArray;
  18508. instance.arc = arc;
  18509. return instance;
  18510. }
  18511. // tube creation
  18512. path3D = new BABYLON.Path3D(path);
  18513. var newPathArray = new Array();
  18514. cap = (cap < 0 || cap > 3) ? 0 : cap;
  18515. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  18516. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  18517. tube.pathArray = pathArray;
  18518. tube.path3D = path3D;
  18519. tube.tessellation = tessellation;
  18520. tube.cap = cap;
  18521. tube.arc = options.arc;
  18522. return tube;
  18523. };
  18524. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  18525. var polyhedron = new BABYLON.Mesh(name, scene);
  18526. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  18527. vertexData.applyToMesh(polyhedron, options.updatable);
  18528. return polyhedron;
  18529. };
  18530. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  18531. var indices = sourceMesh.getIndices();
  18532. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18533. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18534. var position = options.position || BABYLON.Vector3.Zero();
  18535. var normal = options.normal || BABYLON.Vector3.Up();
  18536. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  18537. var angle = options.angle || 0;
  18538. // Getting correct rotation
  18539. if (!normal) {
  18540. var target = new BABYLON.Vector3(0, 0, 1);
  18541. var camera = sourceMesh.getScene().activeCamera;
  18542. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  18543. normal = camera.globalPosition.subtract(cameraWorldTarget);
  18544. }
  18545. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  18546. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  18547. var pitch = Math.atan2(normal.y, len);
  18548. // Matrix
  18549. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  18550. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  18551. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  18552. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  18553. var vertexData = new BABYLON.VertexData();
  18554. vertexData.indices = [];
  18555. vertexData.positions = [];
  18556. vertexData.normals = [];
  18557. vertexData.uvs = [];
  18558. var currentVertexDataIndex = 0;
  18559. var extractDecalVector3 = function (indexId) {
  18560. var vertexId = indices[indexId];
  18561. var result = new BABYLON.PositionNormalVertex();
  18562. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  18563. // Send vector to decal local world
  18564. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  18565. // Get normal
  18566. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  18567. return result;
  18568. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  18569. var clip = function (vertices, axis) {
  18570. if (vertices.length === 0) {
  18571. return vertices;
  18572. }
  18573. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  18574. var clipVertices = function (v0, v1) {
  18575. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  18576. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  18577. };
  18578. var result = new Array();
  18579. for (var index = 0; index < vertices.length; index += 3) {
  18580. var v1Out;
  18581. var v2Out;
  18582. var v3Out;
  18583. var total = 0;
  18584. var nV1, nV2, nV3, nV4;
  18585. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  18586. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  18587. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  18588. v1Out = d1 > 0;
  18589. v2Out = d2 > 0;
  18590. v3Out = d3 > 0;
  18591. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  18592. switch (total) {
  18593. case 0:
  18594. result.push(vertices[index]);
  18595. result.push(vertices[index + 1]);
  18596. result.push(vertices[index + 2]);
  18597. break;
  18598. case 1:
  18599. if (v1Out) {
  18600. nV1 = vertices[index + 1];
  18601. nV2 = vertices[index + 2];
  18602. nV3 = clipVertices(vertices[index], nV1);
  18603. nV4 = clipVertices(vertices[index], nV2);
  18604. }
  18605. if (v2Out) {
  18606. nV1 = vertices[index];
  18607. nV2 = vertices[index + 2];
  18608. nV3 = clipVertices(vertices[index + 1], nV1);
  18609. nV4 = clipVertices(vertices[index + 1], nV2);
  18610. result.push(nV3);
  18611. result.push(nV2.clone());
  18612. result.push(nV1.clone());
  18613. result.push(nV2.clone());
  18614. result.push(nV3.clone());
  18615. result.push(nV4);
  18616. break;
  18617. }
  18618. if (v3Out) {
  18619. nV1 = vertices[index];
  18620. nV2 = vertices[index + 1];
  18621. nV3 = clipVertices(vertices[index + 2], nV1);
  18622. nV4 = clipVertices(vertices[index + 2], nV2);
  18623. }
  18624. result.push(nV1.clone());
  18625. result.push(nV2.clone());
  18626. result.push(nV3);
  18627. result.push(nV4);
  18628. result.push(nV3.clone());
  18629. result.push(nV2.clone());
  18630. break;
  18631. case 2:
  18632. if (!v1Out) {
  18633. nV1 = vertices[index].clone();
  18634. nV2 = clipVertices(nV1, vertices[index + 1]);
  18635. nV3 = clipVertices(nV1, vertices[index + 2]);
  18636. result.push(nV1);
  18637. result.push(nV2);
  18638. result.push(nV3);
  18639. }
  18640. if (!v2Out) {
  18641. nV1 = vertices[index + 1].clone();
  18642. nV2 = clipVertices(nV1, vertices[index + 2]);
  18643. nV3 = clipVertices(nV1, vertices[index]);
  18644. result.push(nV1);
  18645. result.push(nV2);
  18646. result.push(nV3);
  18647. }
  18648. if (!v3Out) {
  18649. nV1 = vertices[index + 2].clone();
  18650. nV2 = clipVertices(nV1, vertices[index]);
  18651. nV3 = clipVertices(nV1, vertices[index + 1]);
  18652. result.push(nV1);
  18653. result.push(nV2);
  18654. result.push(nV3);
  18655. }
  18656. break;
  18657. case 3:
  18658. break;
  18659. }
  18660. }
  18661. return result;
  18662. };
  18663. for (var index = 0; index < indices.length; index += 3) {
  18664. var faceVertices = new Array();
  18665. faceVertices.push(extractDecalVector3(index));
  18666. faceVertices.push(extractDecalVector3(index + 1));
  18667. faceVertices.push(extractDecalVector3(index + 2));
  18668. // Clip
  18669. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  18670. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  18671. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  18672. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  18673. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  18674. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  18675. if (faceVertices.length === 0) {
  18676. continue;
  18677. }
  18678. // Add UVs and get back to world
  18679. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  18680. var vertex = faceVertices[vIndex];
  18681. //TODO check for Int32Array
  18682. vertexData.indices.push(currentVertexDataIndex);
  18683. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  18684. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  18685. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  18686. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  18687. currentVertexDataIndex++;
  18688. }
  18689. }
  18690. // Return mesh
  18691. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  18692. vertexData.applyToMesh(decal);
  18693. decal.position = position.clone();
  18694. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  18695. return decal;
  18696. };
  18697. // Privates
  18698. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  18699. // extrusion geometry
  18700. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  18701. var tangents = path3D.getTangents();
  18702. var normals = path3D.getNormals();
  18703. var binormals = path3D.getBinormals();
  18704. var distances = path3D.getDistances();
  18705. var angle = 0;
  18706. var returnScale = function () { return scale; };
  18707. var returnRotation = function () { return rotation; };
  18708. var rotate = custom ? rotateFunction : returnRotation;
  18709. var scl = custom ? scaleFunction : returnScale;
  18710. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  18711. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  18712. for (var i = 0; i < curve.length; i++) {
  18713. var shapePath = new Array();
  18714. var angleStep = rotate(i, distances[i]);
  18715. var scaleRatio = scl(i, distances[i]);
  18716. for (var p = 0; p < shape.length; p++) {
  18717. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  18718. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  18719. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  18720. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  18721. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  18722. shapePath[p] = rotated;
  18723. }
  18724. shapePaths[index] = shapePath;
  18725. angle += angleStep;
  18726. index++;
  18727. }
  18728. // cap
  18729. var capPath = function (shapePath) {
  18730. var pointCap = Array();
  18731. var barycenter = BABYLON.Vector3.Zero();
  18732. var i;
  18733. for (i = 0; i < shapePath.length; i++) {
  18734. barycenter.addInPlace(shapePath[i]);
  18735. }
  18736. barycenter.scaleInPlace(1 / shapePath.length);
  18737. for (i = 0; i < shapePath.length; i++) {
  18738. pointCap.push(barycenter);
  18739. }
  18740. return pointCap;
  18741. };
  18742. switch (cap) {
  18743. case BABYLON.Mesh.NO_CAP:
  18744. break;
  18745. case BABYLON.Mesh.CAP_START:
  18746. shapePaths[0] = capPath(shapePaths[2]);
  18747. shapePaths[1] = shapePaths[2].slice(0);
  18748. break;
  18749. case BABYLON.Mesh.CAP_END:
  18750. shapePaths[index] = shapePaths[index - 1];
  18751. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  18752. break;
  18753. case BABYLON.Mesh.CAP_ALL:
  18754. shapePaths[0] = capPath(shapePaths[2]);
  18755. shapePaths[1] = shapePaths[2].slice(0);
  18756. shapePaths[index] = shapePaths[index - 1];
  18757. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  18758. break;
  18759. default:
  18760. break;
  18761. }
  18762. return shapePaths;
  18763. };
  18764. var path3D;
  18765. var pathArray;
  18766. if (instance) {
  18767. path3D = (instance.path3D).update(curve);
  18768. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  18769. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  18770. return instance;
  18771. }
  18772. // extruded shape creation
  18773. path3D = new BABYLON.Path3D(curve);
  18774. var newShapePaths = new Array();
  18775. cap = (cap < 0 || cap > 3) ? 0 : cap;
  18776. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  18777. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  18778. extrudedGeneric.pathArray = pathArray;
  18779. extrudedGeneric.path3D = path3D;
  18780. extrudedGeneric.cap = cap;
  18781. return extrudedGeneric;
  18782. };
  18783. return MeshBuilder;
  18784. })();
  18785. BABYLON.MeshBuilder = MeshBuilder;
  18786. })(BABYLON || (BABYLON = {}));
  18787. var BABYLON;
  18788. (function (BABYLON) {
  18789. var BaseTexture = (function () {
  18790. function BaseTexture(scene) {
  18791. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18792. this.hasAlpha = false;
  18793. this.getAlphaFromRGB = false;
  18794. this.level = 1;
  18795. this.isCube = false;
  18796. this.isRenderTarget = false;
  18797. this.animations = new Array();
  18798. this.coordinatesIndex = 0;
  18799. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18800. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18801. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18802. this.anisotropicFilteringLevel = 4;
  18803. this._scene = scene;
  18804. this._scene.textures.push(this);
  18805. }
  18806. BaseTexture.prototype.getScene = function () {
  18807. return this._scene;
  18808. };
  18809. BaseTexture.prototype.getTextureMatrix = function () {
  18810. return null;
  18811. };
  18812. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18813. return null;
  18814. };
  18815. BaseTexture.prototype.getInternalTexture = function () {
  18816. return this._texture;
  18817. };
  18818. BaseTexture.prototype.isReady = function () {
  18819. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18820. return true;
  18821. }
  18822. if (this._texture) {
  18823. return this._texture.isReady;
  18824. }
  18825. return false;
  18826. };
  18827. BaseTexture.prototype.getSize = function () {
  18828. if (this._texture._width) {
  18829. return { width: this._texture._width, height: this._texture._height };
  18830. }
  18831. if (this._texture._size) {
  18832. return { width: this._texture._size, height: this._texture._size };
  18833. }
  18834. return { width: 0, height: 0 };
  18835. };
  18836. BaseTexture.prototype.getBaseSize = function () {
  18837. if (!this.isReady())
  18838. return { width: 0, height: 0 };
  18839. if (this._texture._size) {
  18840. return { width: this._texture._size, height: this._texture._size };
  18841. }
  18842. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  18843. };
  18844. BaseTexture.prototype.scale = function (ratio) {
  18845. };
  18846. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18847. get: function () {
  18848. return false;
  18849. },
  18850. enumerable: true,
  18851. configurable: true
  18852. });
  18853. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18854. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18855. for (var index = 0; index < texturesCache.length; index++) {
  18856. var texturesCacheEntry = texturesCache[index];
  18857. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18858. texturesCache.splice(index, 1);
  18859. return;
  18860. }
  18861. }
  18862. };
  18863. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18864. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18865. for (var index = 0; index < texturesCache.length; index++) {
  18866. var texturesCacheEntry = texturesCache[index];
  18867. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18868. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18869. texturesCacheEntry.references++;
  18870. return texturesCacheEntry;
  18871. }
  18872. }
  18873. }
  18874. return null;
  18875. };
  18876. BaseTexture.prototype.delayLoad = function () {
  18877. };
  18878. BaseTexture.prototype.clone = function () {
  18879. return null;
  18880. };
  18881. BaseTexture.prototype.releaseInternalTexture = function () {
  18882. if (this._texture) {
  18883. this._scene.getEngine().releaseInternalTexture(this._texture);
  18884. delete this._texture;
  18885. }
  18886. };
  18887. BaseTexture.prototype.dispose = function () {
  18888. // Animations
  18889. this.getScene().stopAnimation(this);
  18890. // Remove from scene
  18891. var index = this._scene.textures.indexOf(this);
  18892. if (index >= 0) {
  18893. this._scene.textures.splice(index, 1);
  18894. }
  18895. if (this._texture === undefined) {
  18896. return;
  18897. }
  18898. // Release
  18899. this.releaseInternalTexture();
  18900. // Callback
  18901. if (this.onDispose) {
  18902. this.onDispose();
  18903. }
  18904. };
  18905. BaseTexture.prototype.serialize = function () {
  18906. var serializationObject = {};
  18907. if (!this.name) {
  18908. return null;
  18909. }
  18910. serializationObject.name = this.name;
  18911. serializationObject.hasAlpha = this.hasAlpha;
  18912. serializationObject.level = this.level;
  18913. serializationObject.coordinatesIndex = this.coordinatesIndex;
  18914. serializationObject.coordinatesMode = this.coordinatesMode;
  18915. serializationObject.wrapU = this.wrapU;
  18916. serializationObject.wrapV = this.wrapV;
  18917. // Animations
  18918. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18919. return serializationObject;
  18920. };
  18921. return BaseTexture;
  18922. })();
  18923. BABYLON.BaseTexture = BaseTexture;
  18924. })(BABYLON || (BABYLON = {}));
  18925. var BABYLON;
  18926. (function (BABYLON) {
  18927. var Texture = (function (_super) {
  18928. __extends(Texture, _super);
  18929. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  18930. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18931. if (onLoad === void 0) { onLoad = null; }
  18932. if (onError === void 0) { onError = null; }
  18933. if (buffer === void 0) { buffer = null; }
  18934. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18935. _super.call(this, scene);
  18936. this.uOffset = 0;
  18937. this.vOffset = 0;
  18938. this.uScale = 1.0;
  18939. this.vScale = 1.0;
  18940. this.uAng = 0;
  18941. this.vAng = 0;
  18942. this.wAng = 0;
  18943. this.name = url;
  18944. this.url = url;
  18945. this._noMipmap = noMipmap;
  18946. this._invertY = invertY;
  18947. this._samplingMode = samplingMode;
  18948. this._buffer = buffer;
  18949. this._deleteBuffer = deleteBuffer;
  18950. if (!url) {
  18951. return;
  18952. }
  18953. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  18954. if (!this._texture) {
  18955. if (!scene.useDelayedTextureLoading) {
  18956. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  18957. if (deleteBuffer) {
  18958. delete this._buffer;
  18959. }
  18960. }
  18961. else {
  18962. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18963. this._delayedOnLoad = onLoad;
  18964. this._delayedOnError = onError;
  18965. }
  18966. }
  18967. else {
  18968. BABYLON.Tools.SetImmediate(function () {
  18969. if (onLoad) {
  18970. onLoad();
  18971. }
  18972. });
  18973. }
  18974. }
  18975. Texture.prototype.delayLoad = function () {
  18976. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18977. return;
  18978. }
  18979. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18980. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18981. if (!this._texture) {
  18982. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  18983. if (this._deleteBuffer) {
  18984. delete this._buffer;
  18985. }
  18986. }
  18987. };
  18988. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18989. if (!this._texture) {
  18990. return;
  18991. }
  18992. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18993. };
  18994. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18995. x *= this.uScale;
  18996. y *= this.vScale;
  18997. x -= 0.5 * this.uScale;
  18998. y -= 0.5 * this.vScale;
  18999. z -= 0.5;
  19000. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19001. t.x += 0.5 * this.uScale + this.uOffset;
  19002. t.y += 0.5 * this.vScale + this.vOffset;
  19003. t.z += 0.5;
  19004. };
  19005. Texture.prototype.getTextureMatrix = function () {
  19006. if (this.uOffset === this._cachedUOffset &&
  19007. this.vOffset === this._cachedVOffset &&
  19008. this.uScale === this._cachedUScale &&
  19009. this.vScale === this._cachedVScale &&
  19010. this.uAng === this._cachedUAng &&
  19011. this.vAng === this._cachedVAng &&
  19012. this.wAng === this._cachedWAng) {
  19013. return this._cachedTextureMatrix;
  19014. }
  19015. this._cachedUOffset = this.uOffset;
  19016. this._cachedVOffset = this.vOffset;
  19017. this._cachedUScale = this.uScale;
  19018. this._cachedVScale = this.vScale;
  19019. this._cachedUAng = this.uAng;
  19020. this._cachedVAng = this.vAng;
  19021. this._cachedWAng = this.wAng;
  19022. if (!this._cachedTextureMatrix) {
  19023. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19024. this._rowGenerationMatrix = new BABYLON.Matrix();
  19025. this._t0 = BABYLON.Vector3.Zero();
  19026. this._t1 = BABYLON.Vector3.Zero();
  19027. this._t2 = BABYLON.Vector3.Zero();
  19028. }
  19029. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19030. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19031. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19032. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19033. this._t1.subtractInPlace(this._t0);
  19034. this._t2.subtractInPlace(this._t0);
  19035. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19036. this._cachedTextureMatrix.m[0] = this._t1.x;
  19037. this._cachedTextureMatrix.m[1] = this._t1.y;
  19038. this._cachedTextureMatrix.m[2] = this._t1.z;
  19039. this._cachedTextureMatrix.m[4] = this._t2.x;
  19040. this._cachedTextureMatrix.m[5] = this._t2.y;
  19041. this._cachedTextureMatrix.m[6] = this._t2.z;
  19042. this._cachedTextureMatrix.m[8] = this._t0.x;
  19043. this._cachedTextureMatrix.m[9] = this._t0.y;
  19044. this._cachedTextureMatrix.m[10] = this._t0.z;
  19045. return this._cachedTextureMatrix;
  19046. };
  19047. Texture.prototype.getReflectionTextureMatrix = function () {
  19048. if (this.uOffset === this._cachedUOffset &&
  19049. this.vOffset === this._cachedVOffset &&
  19050. this.uScale === this._cachedUScale &&
  19051. this.vScale === this._cachedVScale &&
  19052. this.coordinatesMode === this._cachedCoordinatesMode) {
  19053. return this._cachedTextureMatrix;
  19054. }
  19055. if (!this._cachedTextureMatrix) {
  19056. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19057. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19058. }
  19059. this._cachedCoordinatesMode = this.coordinatesMode;
  19060. switch (this.coordinatesMode) {
  19061. case Texture.PLANAR_MODE:
  19062. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19063. this._cachedTextureMatrix[0] = this.uScale;
  19064. this._cachedTextureMatrix[5] = this.vScale;
  19065. this._cachedTextureMatrix[12] = this.uOffset;
  19066. this._cachedTextureMatrix[13] = this.vOffset;
  19067. break;
  19068. case Texture.PROJECTION_MODE:
  19069. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19070. this._projectionModeMatrix.m[0] = 0.5;
  19071. this._projectionModeMatrix.m[5] = -0.5;
  19072. this._projectionModeMatrix.m[10] = 0.0;
  19073. this._projectionModeMatrix.m[12] = 0.5;
  19074. this._projectionModeMatrix.m[13] = 0.5;
  19075. this._projectionModeMatrix.m[14] = 1.0;
  19076. this._projectionModeMatrix.m[15] = 1.0;
  19077. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19078. break;
  19079. default:
  19080. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19081. break;
  19082. }
  19083. return this._cachedTextureMatrix;
  19084. };
  19085. Texture.prototype.clone = function () {
  19086. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  19087. // Base texture
  19088. newTexture.hasAlpha = this.hasAlpha;
  19089. newTexture.level = this.level;
  19090. newTexture.wrapU = this.wrapU;
  19091. newTexture.wrapV = this.wrapV;
  19092. newTexture.coordinatesIndex = this.coordinatesIndex;
  19093. newTexture.coordinatesMode = this.coordinatesMode;
  19094. // Texture
  19095. newTexture.uOffset = this.uOffset;
  19096. newTexture.vOffset = this.vOffset;
  19097. newTexture.uScale = this.uScale;
  19098. newTexture.vScale = this.vScale;
  19099. newTexture.uAng = this.uAng;
  19100. newTexture.vAng = this.vAng;
  19101. newTexture.wAng = this.wAng;
  19102. return newTexture;
  19103. };
  19104. Texture.prototype.serialize = function () {
  19105. if (!this.name) {
  19106. return null;
  19107. }
  19108. var serializationObject = _super.prototype.serialize.call(this);
  19109. serializationObject.uOffset = this.uOffset;
  19110. serializationObject.vOffset = this.vOffset;
  19111. serializationObject.uScale = this.uScale;
  19112. serializationObject.vScale = this.vScale;
  19113. serializationObject.uAng = this.uAng;
  19114. serializationObject.vAng = this.vAng;
  19115. serializationObject.wAng = this.wAng;
  19116. return serializationObject;
  19117. };
  19118. // Statics
  19119. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  19120. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19121. if (onLoad === void 0) { onLoad = null; }
  19122. if (onError === void 0) { onError = null; }
  19123. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  19124. };
  19125. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19126. if (parsedTexture.isCube) {
  19127. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19128. }
  19129. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19130. return null;
  19131. }
  19132. var texture;
  19133. if (parsedTexture.mirrorPlane) {
  19134. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19135. texture._waitingRenderList = parsedTexture.renderList;
  19136. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19137. }
  19138. else if (parsedTexture.isRenderTarget) {
  19139. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19140. texture._waitingRenderList = parsedTexture.renderList;
  19141. }
  19142. else {
  19143. if (parsedTexture.base64String) {
  19144. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19145. }
  19146. else {
  19147. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19148. }
  19149. }
  19150. texture.name = parsedTexture.name;
  19151. texture.hasAlpha = parsedTexture.hasAlpha;
  19152. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19153. texture.level = parsedTexture.level;
  19154. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19155. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19156. texture.uOffset = parsedTexture.uOffset;
  19157. texture.vOffset = parsedTexture.vOffset;
  19158. texture.uScale = parsedTexture.uScale;
  19159. texture.vScale = parsedTexture.vScale;
  19160. texture.uAng = parsedTexture.uAng;
  19161. texture.vAng = parsedTexture.vAng;
  19162. texture.wAng = parsedTexture.wAng;
  19163. texture.wrapU = parsedTexture.wrapU;
  19164. texture.wrapV = parsedTexture.wrapV;
  19165. // Animations
  19166. if (parsedTexture.animations) {
  19167. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19168. var parsedAnimation = parsedTexture.animations[animationIndex];
  19169. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19170. }
  19171. }
  19172. return texture;
  19173. };
  19174. // Constants
  19175. Texture.NEAREST_SAMPLINGMODE = 1;
  19176. Texture.BILINEAR_SAMPLINGMODE = 2;
  19177. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19178. Texture.EXPLICIT_MODE = 0;
  19179. Texture.SPHERICAL_MODE = 1;
  19180. Texture.PLANAR_MODE = 2;
  19181. Texture.CUBIC_MODE = 3;
  19182. Texture.PROJECTION_MODE = 4;
  19183. Texture.SKYBOX_MODE = 5;
  19184. Texture.INVCUBIC_MODE = 6;
  19185. Texture.EQUIRECTANGULAR_MODE = 7;
  19186. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19187. Texture.CLAMP_ADDRESSMODE = 0;
  19188. Texture.WRAP_ADDRESSMODE = 1;
  19189. Texture.MIRROR_ADDRESSMODE = 2;
  19190. return Texture;
  19191. })(BABYLON.BaseTexture);
  19192. BABYLON.Texture = Texture;
  19193. })(BABYLON || (BABYLON = {}));
  19194. var BABYLON;
  19195. (function (BABYLON) {
  19196. var CubeTexture = (function (_super) {
  19197. __extends(CubeTexture, _super);
  19198. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  19199. _super.call(this, scene);
  19200. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  19201. this.name = rootUrl;
  19202. this.url = rootUrl;
  19203. this._noMipmap = noMipmap;
  19204. this.hasAlpha = false;
  19205. if (!rootUrl && !files) {
  19206. return;
  19207. }
  19208. this._texture = this._getFromCache(rootUrl, noMipmap);
  19209. if (!files) {
  19210. if (!extensions) {
  19211. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  19212. }
  19213. files = [];
  19214. for (var index = 0; index < extensions.length; index++) {
  19215. files.push(rootUrl + extensions[index]);
  19216. }
  19217. this._extensions = extensions;
  19218. }
  19219. this._files = files;
  19220. if (!this._texture) {
  19221. if (!scene.useDelayedTextureLoading) {
  19222. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  19223. }
  19224. else {
  19225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19226. }
  19227. }
  19228. this.isCube = true;
  19229. this._textureMatrix = BABYLON.Matrix.Identity();
  19230. }
  19231. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  19232. return new CubeTexture("", scene, null, noMipmap, files);
  19233. };
  19234. CubeTexture.prototype.clone = function () {
  19235. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  19236. // Base texture
  19237. newTexture.level = this.level;
  19238. newTexture.wrapU = this.wrapU;
  19239. newTexture.wrapV = this.wrapV;
  19240. newTexture.coordinatesIndex = this.coordinatesIndex;
  19241. newTexture.coordinatesMode = this.coordinatesMode;
  19242. return newTexture;
  19243. };
  19244. // Methods
  19245. CubeTexture.prototype.delayLoad = function () {
  19246. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19247. return;
  19248. }
  19249. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19250. this._texture = this._getFromCache(this.url, this._noMipmap);
  19251. if (!this._texture) {
  19252. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  19253. }
  19254. };
  19255. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  19256. return this._textureMatrix;
  19257. };
  19258. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  19259. var texture = null;
  19260. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19261. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19262. texture.name = parsedTexture.name;
  19263. texture.hasAlpha = parsedTexture.hasAlpha;
  19264. texture.level = parsedTexture.level;
  19265. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19266. }
  19267. return texture;
  19268. };
  19269. CubeTexture.prototype.serialize = function () {
  19270. if (!this.name) {
  19271. return null;
  19272. }
  19273. var serializationObject = {};
  19274. serializationObject.name = this.name;
  19275. serializationObject.hasAlpha = this.hasAlpha;
  19276. serializationObject.isCube = true;
  19277. serializationObject.level = this.level;
  19278. serializationObject.coordinatesMode = this.coordinatesMode;
  19279. return serializationObject;
  19280. };
  19281. return CubeTexture;
  19282. })(BABYLON.BaseTexture);
  19283. BABYLON.CubeTexture = CubeTexture;
  19284. })(BABYLON || (BABYLON = {}));
  19285. var BABYLON;
  19286. (function (BABYLON) {
  19287. var RenderTargetTexture = (function (_super) {
  19288. __extends(RenderTargetTexture, _super);
  19289. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  19290. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  19291. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  19292. if (isCube === void 0) { isCube = false; }
  19293. _super.call(this, null, scene, !generateMipMaps);
  19294. this.isCube = isCube;
  19295. this.renderList = new Array();
  19296. this.renderParticles = true;
  19297. this.renderSprites = false;
  19298. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  19299. this._currentRefreshId = -1;
  19300. this._refreshRate = 1;
  19301. this.name = name;
  19302. this.isRenderTarget = true;
  19303. this._size = size;
  19304. this._generateMipMaps = generateMipMaps;
  19305. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  19306. if (isCube) {
  19307. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  19308. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  19309. this._textureMatrix = BABYLON.Matrix.Identity();
  19310. }
  19311. else {
  19312. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  19313. }
  19314. // Rendering groups
  19315. this._renderingManager = new BABYLON.RenderingManager(scene);
  19316. }
  19317. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  19318. get: function () {
  19319. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  19320. },
  19321. enumerable: true,
  19322. configurable: true
  19323. });
  19324. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  19325. get: function () {
  19326. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  19327. },
  19328. enumerable: true,
  19329. configurable: true
  19330. });
  19331. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  19332. get: function () {
  19333. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  19339. this._currentRefreshId = -1;
  19340. };
  19341. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  19342. get: function () {
  19343. return this._refreshRate;
  19344. },
  19345. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  19346. set: function (value) {
  19347. this._refreshRate = value;
  19348. this.resetRefreshCounter();
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. RenderTargetTexture.prototype._shouldRender = function () {
  19354. if (this._currentRefreshId === -1) {
  19355. this._currentRefreshId = 1;
  19356. return true;
  19357. }
  19358. if (this.refreshRate === this._currentRefreshId) {
  19359. this._currentRefreshId = 1;
  19360. return true;
  19361. }
  19362. this._currentRefreshId++;
  19363. return false;
  19364. };
  19365. RenderTargetTexture.prototype.isReady = function () {
  19366. if (!this.getScene().renderTargetsEnabled) {
  19367. return false;
  19368. }
  19369. return _super.prototype.isReady.call(this);
  19370. };
  19371. RenderTargetTexture.prototype.getRenderSize = function () {
  19372. return this._size;
  19373. };
  19374. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  19375. get: function () {
  19376. return true;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. RenderTargetTexture.prototype.scale = function (ratio) {
  19382. var newSize = this._size * ratio;
  19383. this.resize(newSize, this._generateMipMaps);
  19384. };
  19385. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  19386. if (this.isCube) {
  19387. return this._textureMatrix;
  19388. }
  19389. return _super.prototype.getReflectionTextureMatrix.call(this);
  19390. };
  19391. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  19392. this.releaseInternalTexture();
  19393. if (this.isCube) {
  19394. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  19395. }
  19396. else {
  19397. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  19398. }
  19399. };
  19400. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  19401. var scene = this.getScene();
  19402. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  19403. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  19404. }
  19405. if (this._waitingRenderList) {
  19406. this.renderList = [];
  19407. for (var index = 0; index < this._waitingRenderList.length; index++) {
  19408. var id = this._waitingRenderList[index];
  19409. this.renderList.push(scene.getMeshByID(id));
  19410. }
  19411. delete this._waitingRenderList;
  19412. }
  19413. if (this.renderList && this.renderList.length === 0) {
  19414. return;
  19415. }
  19416. // Prepare renderingManager
  19417. this._renderingManager.reset();
  19418. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  19419. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  19420. var mesh = currentRenderList[meshIndex];
  19421. if (mesh) {
  19422. if (!mesh.isReady()) {
  19423. // Reset _currentRefreshId
  19424. this.resetRefreshCounter();
  19425. continue;
  19426. }
  19427. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  19428. mesh._activate(scene.getRenderId());
  19429. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19430. var subMesh = mesh.subMeshes[subIndex];
  19431. scene._activeIndices += subMesh.indexCount;
  19432. this._renderingManager.dispatch(subMesh);
  19433. }
  19434. }
  19435. }
  19436. }
  19437. if (this.isCube) {
  19438. for (var face = 0; face < 6; face++) {
  19439. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  19440. scene.incrementRenderId();
  19441. }
  19442. }
  19443. else {
  19444. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  19445. }
  19446. if (this.onAfterUnbind) {
  19447. this.onAfterUnbind();
  19448. }
  19449. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  19450. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  19451. }
  19452. scene.resetCachedMaterial();
  19453. };
  19454. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  19455. var scene = this.getScene();
  19456. var engine = scene.getEngine();
  19457. // Bind
  19458. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  19459. if (this.isCube) {
  19460. engine.bindFramebuffer(this._texture, faceIndex);
  19461. }
  19462. else {
  19463. engine.bindFramebuffer(this._texture);
  19464. }
  19465. }
  19466. if (this.onBeforeRender) {
  19467. this.onBeforeRender(faceIndex);
  19468. }
  19469. // Clear
  19470. if (this.onClear) {
  19471. this.onClear(engine);
  19472. }
  19473. else {
  19474. engine.clear(scene.clearColor, true, true);
  19475. }
  19476. if (!this._doNotChangeAspectRatio) {
  19477. scene.updateTransformMatrix(true);
  19478. }
  19479. // Render
  19480. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  19481. if (useCameraPostProcess) {
  19482. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  19483. }
  19484. if (!this._doNotChangeAspectRatio) {
  19485. scene.updateTransformMatrix(true);
  19486. }
  19487. if (this.onAfterRender) {
  19488. this.onAfterRender(faceIndex);
  19489. }
  19490. // Dump ?
  19491. if (dumpForDebug) {
  19492. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  19493. }
  19494. // Unbind
  19495. if (!this.isCube || faceIndex === 5) {
  19496. if (this.isCube) {
  19497. if (faceIndex === 5) {
  19498. engine.generateMipMapsForCubemap(this._texture);
  19499. }
  19500. }
  19501. engine.unBindFramebuffer(this._texture, this.isCube);
  19502. }
  19503. };
  19504. RenderTargetTexture.prototype.clone = function () {
  19505. var textureSize = this.getSize();
  19506. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19507. // Base texture
  19508. newTexture.hasAlpha = this.hasAlpha;
  19509. newTexture.level = this.level;
  19510. // RenderTarget Texture
  19511. newTexture.coordinatesMode = this.coordinatesMode;
  19512. newTexture.renderList = this.renderList.slice(0);
  19513. return newTexture;
  19514. };
  19515. RenderTargetTexture.prototype.serialize = function () {
  19516. if (!this.name) {
  19517. return null;
  19518. }
  19519. var serializationObject = _super.prototype.serialize.call(this);
  19520. serializationObject.renderTargetSize = this.getRenderSize();
  19521. serializationObject.renderList = [];
  19522. for (var index = 0; index < this.renderList.length; index++) {
  19523. serializationObject.renderList.push(this.renderList[index].id);
  19524. }
  19525. return serializationObject;
  19526. };
  19527. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  19528. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  19529. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  19530. return RenderTargetTexture;
  19531. })(BABYLON.Texture);
  19532. BABYLON.RenderTargetTexture = RenderTargetTexture;
  19533. })(BABYLON || (BABYLON = {}));
  19534. var BABYLON;
  19535. (function (BABYLON) {
  19536. var ProceduralTexture = (function (_super) {
  19537. __extends(ProceduralTexture, _super);
  19538. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  19539. if (generateMipMaps === void 0) { generateMipMaps = true; }
  19540. if (isCube === void 0) { isCube = false; }
  19541. _super.call(this, null, scene, !generateMipMaps);
  19542. this.isCube = isCube;
  19543. this.isEnabled = true;
  19544. this._currentRefreshId = -1;
  19545. this._refreshRate = 1;
  19546. this._vertexDeclaration = [2];
  19547. this._vertexStrideSize = 2 * 4;
  19548. this._uniforms = new Array();
  19549. this._samplers = new Array();
  19550. this._textures = new Array();
  19551. this._floats = new Array();
  19552. this._floatsArrays = {};
  19553. this._colors3 = new Array();
  19554. this._colors4 = new Array();
  19555. this._vectors2 = new Array();
  19556. this._vectors3 = new Array();
  19557. this._matrices = new Array();
  19558. this._fallbackTextureUsed = false;
  19559. scene._proceduralTextures.push(this);
  19560. this.name = name;
  19561. this.isRenderTarget = true;
  19562. this._size = size;
  19563. this._generateMipMaps = generateMipMaps;
  19564. this.setFragment(fragment);
  19565. this._fallbackTexture = fallbackTexture;
  19566. if (isCube) {
  19567. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  19568. this.setFloat("face", 0);
  19569. }
  19570. else {
  19571. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  19572. }
  19573. // VBO
  19574. var vertices = [];
  19575. vertices.push(1, 1);
  19576. vertices.push(-1, 1);
  19577. vertices.push(-1, -1);
  19578. vertices.push(1, -1);
  19579. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19580. // Indices
  19581. var indices = [];
  19582. indices.push(0);
  19583. indices.push(1);
  19584. indices.push(2);
  19585. indices.push(0);
  19586. indices.push(2);
  19587. indices.push(3);
  19588. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19589. }
  19590. ProceduralTexture.prototype.reset = function () {
  19591. if (this._effect === undefined) {
  19592. return;
  19593. }
  19594. var engine = this.getScene().getEngine();
  19595. engine._releaseEffect(this._effect);
  19596. };
  19597. ProceduralTexture.prototype.isReady = function () {
  19598. var _this = this;
  19599. var engine = this.getScene().getEngine();
  19600. var shaders;
  19601. if (!this._fragment) {
  19602. return false;
  19603. }
  19604. if (this._fallbackTextureUsed) {
  19605. return true;
  19606. }
  19607. if (this._fragment.fragmentElement !== undefined) {
  19608. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  19609. }
  19610. else {
  19611. shaders = { vertex: "procedural", fragment: this._fragment };
  19612. }
  19613. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  19614. _this.releaseInternalTexture();
  19615. if (_this._fallbackTexture) {
  19616. _this._texture = _this._fallbackTexture._texture;
  19617. _this._texture.references++;
  19618. }
  19619. _this._fallbackTextureUsed = true;
  19620. });
  19621. return this._effect.isReady();
  19622. };
  19623. ProceduralTexture.prototype.resetRefreshCounter = function () {
  19624. this._currentRefreshId = -1;
  19625. };
  19626. ProceduralTexture.prototype.setFragment = function (fragment) {
  19627. this._fragment = fragment;
  19628. };
  19629. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  19630. get: function () {
  19631. return this._refreshRate;
  19632. },
  19633. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  19634. set: function (value) {
  19635. this._refreshRate = value;
  19636. this.resetRefreshCounter();
  19637. },
  19638. enumerable: true,
  19639. configurable: true
  19640. });
  19641. ProceduralTexture.prototype._shouldRender = function () {
  19642. if (!this.isEnabled || !this.isReady() || !this._texture) {
  19643. return false;
  19644. }
  19645. if (this._fallbackTextureUsed) {
  19646. return false;
  19647. }
  19648. if (this._currentRefreshId === -1) {
  19649. this._currentRefreshId = 1;
  19650. return true;
  19651. }
  19652. if (this.refreshRate === this._currentRefreshId) {
  19653. this._currentRefreshId = 1;
  19654. return true;
  19655. }
  19656. this._currentRefreshId++;
  19657. return false;
  19658. };
  19659. ProceduralTexture.prototype.getRenderSize = function () {
  19660. return this._size;
  19661. };
  19662. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  19663. if (this._fallbackTextureUsed) {
  19664. return;
  19665. }
  19666. this.releaseInternalTexture();
  19667. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  19668. };
  19669. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  19670. if (this._uniforms.indexOf(uniformName) === -1) {
  19671. this._uniforms.push(uniformName);
  19672. }
  19673. };
  19674. ProceduralTexture.prototype.setTexture = function (name, texture) {
  19675. if (this._samplers.indexOf(name) === -1) {
  19676. this._samplers.push(name);
  19677. }
  19678. this._textures[name] = texture;
  19679. return this;
  19680. };
  19681. ProceduralTexture.prototype.setFloat = function (name, value) {
  19682. this._checkUniform(name);
  19683. this._floats[name] = value;
  19684. return this;
  19685. };
  19686. ProceduralTexture.prototype.setFloats = function (name, value) {
  19687. this._checkUniform(name);
  19688. this._floatsArrays[name] = value;
  19689. return this;
  19690. };
  19691. ProceduralTexture.prototype.setColor3 = function (name, value) {
  19692. this._checkUniform(name);
  19693. this._colors3[name] = value;
  19694. return this;
  19695. };
  19696. ProceduralTexture.prototype.setColor4 = function (name, value) {
  19697. this._checkUniform(name);
  19698. this._colors4[name] = value;
  19699. return this;
  19700. };
  19701. ProceduralTexture.prototype.setVector2 = function (name, value) {
  19702. this._checkUniform(name);
  19703. this._vectors2[name] = value;
  19704. return this;
  19705. };
  19706. ProceduralTexture.prototype.setVector3 = function (name, value) {
  19707. this._checkUniform(name);
  19708. this._vectors3[name] = value;
  19709. return this;
  19710. };
  19711. ProceduralTexture.prototype.setMatrix = function (name, value) {
  19712. this._checkUniform(name);
  19713. this._matrices[name] = value;
  19714. return this;
  19715. };
  19716. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  19717. var scene = this.getScene();
  19718. var engine = scene.getEngine();
  19719. // Render
  19720. engine.enableEffect(this._effect);
  19721. engine.setState(false);
  19722. // Texture
  19723. for (var name in this._textures) {
  19724. this._effect.setTexture(name, this._textures[name]);
  19725. }
  19726. // Float
  19727. for (name in this._floats) {
  19728. this._effect.setFloat(name, this._floats[name]);
  19729. }
  19730. // Floats
  19731. for (name in this._floatsArrays) {
  19732. this._effect.setArray(name, this._floatsArrays[name]);
  19733. }
  19734. // Color3
  19735. for (name in this._colors3) {
  19736. this._effect.setColor3(name, this._colors3[name]);
  19737. }
  19738. // Color4
  19739. for (name in this._colors4) {
  19740. var color = this._colors4[name];
  19741. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19742. }
  19743. // Vector2
  19744. for (name in this._vectors2) {
  19745. this._effect.setVector2(name, this._vectors2[name]);
  19746. }
  19747. // Vector3
  19748. for (name in this._vectors3) {
  19749. this._effect.setVector3(name, this._vectors3[name]);
  19750. }
  19751. // Matrix
  19752. for (name in this._matrices) {
  19753. this._effect.setMatrix(name, this._matrices[name]);
  19754. }
  19755. // VBOs
  19756. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19757. if (this.isCube) {
  19758. for (var face = 0; face < 6; face++) {
  19759. engine.bindFramebuffer(this._texture, face);
  19760. this._effect.setFloat("face", face);
  19761. // Clear
  19762. engine.clear(scene.clearColor, true, true);
  19763. // Draw order
  19764. engine.draw(true, 0, 6);
  19765. // Mipmaps
  19766. if (face === 5) {
  19767. engine.generateMipMapsForCubemap(this._texture);
  19768. }
  19769. }
  19770. }
  19771. else {
  19772. engine.bindFramebuffer(this._texture);
  19773. // Clear
  19774. engine.clear(scene.clearColor, true, true);
  19775. // Draw order
  19776. engine.draw(true, 0, 6);
  19777. }
  19778. // Unbind
  19779. engine.unBindFramebuffer(this._texture, this.isCube);
  19780. if (this.onGenerated) {
  19781. this.onGenerated();
  19782. }
  19783. };
  19784. ProceduralTexture.prototype.clone = function () {
  19785. var textureSize = this.getSize();
  19786. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  19787. // Base texture
  19788. newTexture.hasAlpha = this.hasAlpha;
  19789. newTexture.level = this.level;
  19790. // RenderTarget Texture
  19791. newTexture.coordinatesMode = this.coordinatesMode;
  19792. return newTexture;
  19793. };
  19794. ProceduralTexture.prototype.dispose = function () {
  19795. var index = this.getScene()._proceduralTextures.indexOf(this);
  19796. if (index >= 0) {
  19797. this.getScene()._proceduralTextures.splice(index, 1);
  19798. }
  19799. _super.prototype.dispose.call(this);
  19800. };
  19801. return ProceduralTexture;
  19802. })(BABYLON.Texture);
  19803. BABYLON.ProceduralTexture = ProceduralTexture;
  19804. })(BABYLON || (BABYLON = {}));
  19805. var BABYLON;
  19806. (function (BABYLON) {
  19807. var MirrorTexture = (function (_super) {
  19808. __extends(MirrorTexture, _super);
  19809. function MirrorTexture(name, size, scene, generateMipMaps) {
  19810. var _this = this;
  19811. _super.call(this, name, size, scene, generateMipMaps, true);
  19812. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  19813. this._transformMatrix = BABYLON.Matrix.Zero();
  19814. this._mirrorMatrix = BABYLON.Matrix.Zero();
  19815. this.onBeforeRender = function () {
  19816. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  19817. _this._savedViewMatrix = scene.getViewMatrix();
  19818. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  19819. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  19820. scene.clipPlane = _this.mirrorPlane;
  19821. scene.getEngine().cullBackFaces = false;
  19822. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  19823. };
  19824. this.onAfterRender = function () {
  19825. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  19826. scene.getEngine().cullBackFaces = true;
  19827. scene._mirroredCameraPosition = null;
  19828. delete scene.clipPlane;
  19829. };
  19830. }
  19831. MirrorTexture.prototype.clone = function () {
  19832. var textureSize = this.getSize();
  19833. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19834. // Base texture
  19835. newTexture.hasAlpha = this.hasAlpha;
  19836. newTexture.level = this.level;
  19837. // Mirror Texture
  19838. newTexture.mirrorPlane = this.mirrorPlane.clone();
  19839. newTexture.renderList = this.renderList.slice(0);
  19840. return newTexture;
  19841. };
  19842. MirrorTexture.prototype.serialize = function () {
  19843. if (!this.name) {
  19844. return null;
  19845. }
  19846. var serializationObject = _super.prototype.serialize.call(this);
  19847. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  19848. return serializationObject;
  19849. };
  19850. return MirrorTexture;
  19851. })(BABYLON.RenderTargetTexture);
  19852. BABYLON.MirrorTexture = MirrorTexture;
  19853. })(BABYLON || (BABYLON = {}));
  19854. var BABYLON;
  19855. (function (BABYLON) {
  19856. /**
  19857. * Creates a refraction texture used by refraction channel of the standard material.
  19858. * @param name the texture name
  19859. * @param size size of the underlying texture
  19860. * @param scene root scene
  19861. */
  19862. var RefractionTexture = (function (_super) {
  19863. __extends(RefractionTexture, _super);
  19864. function RefractionTexture(name, size, scene, generateMipMaps) {
  19865. var _this = this;
  19866. _super.call(this, name, size, scene, generateMipMaps, true);
  19867. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  19868. this.depth = 2.0;
  19869. this.onBeforeRender = function () {
  19870. scene.clipPlane = _this.refractionPlane;
  19871. };
  19872. this.onAfterRender = function () {
  19873. delete scene.clipPlane;
  19874. };
  19875. }
  19876. RefractionTexture.prototype.clone = function () {
  19877. var textureSize = this.getSize();
  19878. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19879. // Base texture
  19880. newTexture.hasAlpha = this.hasAlpha;
  19881. newTexture.level = this.level;
  19882. // Refraction Texture
  19883. newTexture.refractionPlane = this.refractionPlane.clone();
  19884. newTexture.renderList = this.renderList.slice(0);
  19885. newTexture.depth = this.depth;
  19886. return newTexture;
  19887. };
  19888. RefractionTexture.prototype.serialize = function () {
  19889. if (!this.name) {
  19890. return null;
  19891. }
  19892. var serializationObject = _super.prototype.serialize.call(this);
  19893. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  19894. serializationObject.depth = this.depth;
  19895. return serializationObject;
  19896. };
  19897. return RefractionTexture;
  19898. })(BABYLON.RenderTargetTexture);
  19899. BABYLON.RefractionTexture = RefractionTexture;
  19900. })(BABYLON || (BABYLON = {}));
  19901. var BABYLON;
  19902. (function (BABYLON) {
  19903. var DynamicTexture = (function (_super) {
  19904. __extends(DynamicTexture, _super);
  19905. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  19906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19907. _super.call(this, null, scene, !generateMipMaps);
  19908. this.name = name;
  19909. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19910. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19911. this._generateMipMaps = generateMipMaps;
  19912. if (options.getContext) {
  19913. this._canvas = options;
  19914. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  19915. }
  19916. else {
  19917. this._canvas = document.createElement("canvas");
  19918. if (options.width) {
  19919. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  19920. }
  19921. else {
  19922. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  19923. }
  19924. }
  19925. var textureSize = this.getSize();
  19926. this._canvas.width = textureSize.width;
  19927. this._canvas.height = textureSize.height;
  19928. this._context = this._canvas.getContext("2d");
  19929. }
  19930. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  19931. get: function () {
  19932. return true;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. DynamicTexture.prototype.scale = function (ratio) {
  19938. var textureSize = this.getSize();
  19939. textureSize.width *= ratio;
  19940. textureSize.height *= ratio;
  19941. this._canvas.width = textureSize.width;
  19942. this._canvas.height = textureSize.height;
  19943. this.releaseInternalTexture();
  19944. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  19945. };
  19946. DynamicTexture.prototype.getContext = function () {
  19947. return this._context;
  19948. };
  19949. DynamicTexture.prototype.clear = function () {
  19950. var size = this.getSize();
  19951. this._context.fillRect(0, 0, size.width, size.height);
  19952. };
  19953. DynamicTexture.prototype.update = function (invertY) {
  19954. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  19955. };
  19956. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  19957. if (update === void 0) { update = true; }
  19958. var size = this.getSize();
  19959. if (clearColor) {
  19960. this._context.fillStyle = clearColor;
  19961. this._context.fillRect(0, 0, size.width, size.height);
  19962. }
  19963. this._context.font = font;
  19964. if (x === null) {
  19965. var textSize = this._context.measureText(text);
  19966. x = (size.width - textSize.width) / 2;
  19967. }
  19968. this._context.fillStyle = color;
  19969. this._context.fillText(text, x, y);
  19970. if (update) {
  19971. this.update(invertY);
  19972. }
  19973. };
  19974. DynamicTexture.prototype.clone = function () {
  19975. var textureSize = this.getSize();
  19976. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19977. // Base texture
  19978. newTexture.hasAlpha = this.hasAlpha;
  19979. newTexture.level = this.level;
  19980. // Dynamic Texture
  19981. newTexture.wrapU = this.wrapU;
  19982. newTexture.wrapV = this.wrapV;
  19983. return newTexture;
  19984. };
  19985. return DynamicTexture;
  19986. })(BABYLON.Texture);
  19987. BABYLON.DynamicTexture = DynamicTexture;
  19988. })(BABYLON || (BABYLON = {}));
  19989. var BABYLON;
  19990. (function (BABYLON) {
  19991. var VideoTexture = (function (_super) {
  19992. __extends(VideoTexture, _super);
  19993. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  19994. var _this = this;
  19995. if (generateMipMaps === void 0) { generateMipMaps = false; }
  19996. if (invertY === void 0) { invertY = false; }
  19997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19998. _super.call(this, null, scene, !generateMipMaps, invertY);
  19999. this._autoLaunch = true;
  20000. this.name = name;
  20001. this.video = document.createElement("video");
  20002. this.video.autoplay = false;
  20003. this.video.loop = true;
  20004. this.video.addEventListener("canplaythrough", function () {
  20005. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  20006. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20007. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20008. }
  20009. else {
  20010. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20011. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20012. generateMipMaps = false;
  20013. }
  20014. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  20015. _this._texture.isReady = true;
  20016. });
  20017. urls.forEach(function (url) {
  20018. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  20019. var source = document.createElement("source");
  20020. source.src = url;
  20021. _this.video.appendChild(source);
  20022. });
  20023. this._lastUpdate = BABYLON.Tools.Now;
  20024. }
  20025. VideoTexture.prototype.update = function () {
  20026. if (this._autoLaunch) {
  20027. this._autoLaunch = false;
  20028. this.video.play();
  20029. }
  20030. var now = BABYLON.Tools.Now;
  20031. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  20032. return false;
  20033. }
  20034. this._lastUpdate = now;
  20035. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  20036. return true;
  20037. };
  20038. return VideoTexture;
  20039. })(BABYLON.Texture);
  20040. BABYLON.VideoTexture = VideoTexture;
  20041. })(BABYLON || (BABYLON = {}));
  20042. var BABYLON;
  20043. (function (BABYLON) {
  20044. var CustomProceduralTexture = (function (_super) {
  20045. __extends(CustomProceduralTexture, _super);
  20046. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  20047. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  20048. this._animate = true;
  20049. this._time = 0;
  20050. this._texturePath = texturePath;
  20051. //Try to load json
  20052. this.loadJson(texturePath);
  20053. this.refreshRate = 1;
  20054. }
  20055. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  20056. var _this = this;
  20057. var that = this;
  20058. function noConfigFile() {
  20059. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  20060. try {
  20061. that.setFragment(that._texturePath);
  20062. }
  20063. catch (ex) {
  20064. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  20065. }
  20066. }
  20067. var configFileUrl = jsonUrl + "/config.json";
  20068. var xhr = new XMLHttpRequest();
  20069. xhr.open("GET", configFileUrl, true);
  20070. xhr.addEventListener("load", function () {
  20071. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  20072. try {
  20073. _this._config = JSON.parse(xhr.response);
  20074. _this.updateShaderUniforms();
  20075. _this.updateTextures();
  20076. _this.setFragment(_this._texturePath + "/custom");
  20077. _this._animate = _this._config.animate;
  20078. _this.refreshRate = _this._config.refreshrate;
  20079. }
  20080. catch (ex) {
  20081. noConfigFile();
  20082. }
  20083. }
  20084. else {
  20085. noConfigFile();
  20086. }
  20087. }, false);
  20088. xhr.addEventListener("error", function () {
  20089. noConfigFile();
  20090. }, false);
  20091. try {
  20092. xhr.send();
  20093. }
  20094. catch (ex) {
  20095. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  20096. }
  20097. };
  20098. CustomProceduralTexture.prototype.isReady = function () {
  20099. if (!_super.prototype.isReady.call(this)) {
  20100. return false;
  20101. }
  20102. for (var name in this._textures) {
  20103. var texture = this._textures[name];
  20104. if (!texture.isReady()) {
  20105. return false;
  20106. }
  20107. }
  20108. return true;
  20109. };
  20110. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  20111. if (this._animate) {
  20112. this._time += this.getScene().getAnimationRatio() * 0.03;
  20113. this.updateShaderUniforms();
  20114. }
  20115. _super.prototype.render.call(this, useCameraPostProcess);
  20116. };
  20117. CustomProceduralTexture.prototype.updateTextures = function () {
  20118. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  20119. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  20120. }
  20121. };
  20122. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  20123. if (this._config) {
  20124. for (var j = 0; j < this._config.uniforms.length; j++) {
  20125. var uniform = this._config.uniforms[j];
  20126. switch (uniform.type) {
  20127. case "float":
  20128. this.setFloat(uniform.name, uniform.value);
  20129. break;
  20130. case "color3":
  20131. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  20132. break;
  20133. case "color4":
  20134. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  20135. break;
  20136. case "vector2":
  20137. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  20138. break;
  20139. case "vector3":
  20140. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  20141. break;
  20142. }
  20143. }
  20144. }
  20145. this.setFloat("time", this._time);
  20146. };
  20147. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  20148. get: function () {
  20149. return this._animate;
  20150. },
  20151. set: function (value) {
  20152. this._animate = value;
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. return CustomProceduralTexture;
  20158. })(BABYLON.ProceduralTexture);
  20159. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  20160. })(BABYLON || (BABYLON = {}));
  20161. var BABYLON;
  20162. (function (BABYLON) {
  20163. var EffectFallbacks = (function () {
  20164. function EffectFallbacks() {
  20165. this._defines = {};
  20166. this._currentRank = 32;
  20167. this._maxRank = -1;
  20168. }
  20169. EffectFallbacks.prototype.addFallback = function (rank, define) {
  20170. if (!this._defines[rank]) {
  20171. if (rank < this._currentRank) {
  20172. this._currentRank = rank;
  20173. }
  20174. if (rank > this._maxRank) {
  20175. this._maxRank = rank;
  20176. }
  20177. this._defines[rank] = new Array();
  20178. }
  20179. this._defines[rank].push(define);
  20180. };
  20181. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  20182. this._meshRank = rank;
  20183. this._mesh = mesh;
  20184. if (rank > this._maxRank) {
  20185. this._maxRank = rank;
  20186. }
  20187. };
  20188. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  20189. get: function () {
  20190. return this._currentRank <= this._maxRank;
  20191. },
  20192. enumerable: true,
  20193. configurable: true
  20194. });
  20195. EffectFallbacks.prototype.reduce = function (currentDefines) {
  20196. var currentFallbacks = this._defines[this._currentRank];
  20197. for (var index = 0; index < currentFallbacks.length; index++) {
  20198. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  20199. }
  20200. if (this._mesh && this._currentRank === this._meshRank) {
  20201. this._mesh.computeBonesUsingShaders = false;
  20202. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  20203. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  20204. }
  20205. this._currentRank++;
  20206. return currentDefines;
  20207. };
  20208. return EffectFallbacks;
  20209. })();
  20210. BABYLON.EffectFallbacks = EffectFallbacks;
  20211. var Effect = (function () {
  20212. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  20213. var _this = this;
  20214. this._isReady = false;
  20215. this._compilationError = "";
  20216. this._valueCache = [];
  20217. this._engine = engine;
  20218. this.name = baseName;
  20219. this.defines = defines;
  20220. this._uniformsNames = uniformsNames.concat(samplers);
  20221. this._samplers = samplers;
  20222. this._attributesNames = attributesNames;
  20223. this.onError = onError;
  20224. this.onCompiled = onCompiled;
  20225. var vertexSource;
  20226. var fragmentSource;
  20227. if (baseName.vertexElement) {
  20228. vertexSource = document.getElementById(baseName.vertexElement);
  20229. if (!vertexSource) {
  20230. vertexSource = baseName.vertexElement;
  20231. }
  20232. }
  20233. else {
  20234. vertexSource = baseName.vertex || baseName;
  20235. }
  20236. if (baseName.fragmentElement) {
  20237. fragmentSource = document.getElementById(baseName.fragmentElement);
  20238. if (!fragmentSource) {
  20239. fragmentSource = baseName.fragmentElement;
  20240. }
  20241. }
  20242. else {
  20243. fragmentSource = baseName.fragment || baseName;
  20244. }
  20245. this._loadVertexShader(vertexSource, function (vertexCode) {
  20246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  20247. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  20248. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  20249. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  20250. });
  20251. });
  20252. });
  20253. });
  20254. }
  20255. // Properties
  20256. Effect.prototype.isReady = function () {
  20257. return this._isReady;
  20258. };
  20259. Effect.prototype.getProgram = function () {
  20260. return this._program;
  20261. };
  20262. Effect.prototype.getAttributesNames = function () {
  20263. return this._attributesNames;
  20264. };
  20265. Effect.prototype.getAttributeLocation = function (index) {
  20266. return this._attributes[index];
  20267. };
  20268. Effect.prototype.getAttributeLocationByName = function (name) {
  20269. var index = this._attributesNames.indexOf(name);
  20270. return this._attributes[index];
  20271. };
  20272. Effect.prototype.getAttributesCount = function () {
  20273. return this._attributes.length;
  20274. };
  20275. Effect.prototype.getUniformIndex = function (uniformName) {
  20276. return this._uniformsNames.indexOf(uniformName);
  20277. };
  20278. Effect.prototype.getUniform = function (uniformName) {
  20279. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  20280. };
  20281. Effect.prototype.getSamplers = function () {
  20282. return this._samplers;
  20283. };
  20284. Effect.prototype.getCompilationError = function () {
  20285. return this._compilationError;
  20286. };
  20287. // Methods
  20288. Effect.prototype._loadVertexShader = function (vertex, callback) {
  20289. // DOM element ?
  20290. if (vertex instanceof HTMLElement) {
  20291. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  20292. callback(vertexCode);
  20293. return;
  20294. }
  20295. // Is in local store ?
  20296. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  20297. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  20298. return;
  20299. }
  20300. var vertexShaderUrl;
  20301. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  20302. vertexShaderUrl = vertex;
  20303. }
  20304. else {
  20305. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  20306. }
  20307. // Vertex shader
  20308. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  20309. };
  20310. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  20311. // DOM element ?
  20312. if (fragment instanceof HTMLElement) {
  20313. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  20314. callback(fragmentCode);
  20315. return;
  20316. }
  20317. // Is in local store ?
  20318. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  20319. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  20320. return;
  20321. }
  20322. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  20323. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  20324. return;
  20325. }
  20326. var fragmentShaderUrl;
  20327. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  20328. fragmentShaderUrl = fragment;
  20329. }
  20330. else {
  20331. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  20332. }
  20333. // Fragment shader
  20334. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  20335. };
  20336. Effect.prototype._dumpShadersName = function () {
  20337. if (this.name.vertexElement) {
  20338. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  20339. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  20340. }
  20341. else if (this.name.vertex) {
  20342. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  20343. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  20344. }
  20345. else {
  20346. BABYLON.Tools.Error("Vertex shader:" + this.name);
  20347. BABYLON.Tools.Error("Fragment shader:" + this.name);
  20348. }
  20349. };
  20350. Effect.prototype._processIncludes = function (sourceCode, callback) {
  20351. var _this = this;
  20352. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  20353. var match = regex.exec(sourceCode);
  20354. var returnValue = new String(sourceCode);
  20355. while (match != null) {
  20356. var includeFile = match[1];
  20357. if (Effect.IncludesShadersStore[includeFile]) {
  20358. // Substitution
  20359. var includeContent = Effect.IncludesShadersStore[includeFile];
  20360. if (match[2]) {
  20361. var splits = match[3].split(",");
  20362. for (var index = 0; index < splits.length; index += 2) {
  20363. var source = new RegExp(splits[index], "g");
  20364. var dest = splits[index + 1];
  20365. includeContent = includeContent.replace(source, dest);
  20366. }
  20367. }
  20368. if (match[4]) {
  20369. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  20370. }
  20371. // Replace
  20372. returnValue = returnValue.replace(match[0], includeContent);
  20373. }
  20374. else {
  20375. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  20376. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  20377. Effect.IncludesShadersStore[includeFile] = fileContent;
  20378. _this._processIncludes(returnValue, callback);
  20379. });
  20380. return;
  20381. }
  20382. match = regex.exec(sourceCode);
  20383. }
  20384. callback(returnValue);
  20385. };
  20386. Effect.prototype._processPrecision = function (source) {
  20387. if (source.indexOf("precision highp float") === -1) {
  20388. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  20389. source = "precision mediump float;\n" + source;
  20390. }
  20391. else {
  20392. source = "precision highp float;\n" + source;
  20393. }
  20394. }
  20395. else {
  20396. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  20397. source = source.replace("precision highp float", "precision mediump float");
  20398. }
  20399. }
  20400. return source;
  20401. };
  20402. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  20403. try {
  20404. var engine = this._engine;
  20405. // Precision
  20406. vertexSourceCode = this._processPrecision(vertexSourceCode);
  20407. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  20408. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  20409. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  20410. this._attributes = engine.getAttributes(this._program, attributesNames);
  20411. for (var index = 0; index < this._samplers.length; index++) {
  20412. var sampler = this.getUniform(this._samplers[index]);
  20413. if (sampler == null) {
  20414. this._samplers.splice(index, 1);
  20415. index--;
  20416. }
  20417. }
  20418. engine.bindSamplers(this);
  20419. this._isReady = true;
  20420. if (this.onCompiled) {
  20421. this.onCompiled(this);
  20422. }
  20423. }
  20424. catch (e) {
  20425. // Is it a problem with precision?
  20426. if (e.message.indexOf("highp") !== -1) {
  20427. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  20428. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  20429. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  20430. return;
  20431. }
  20432. // Let's go through fallbacks then
  20433. if (fallbacks && fallbacks.isMoreFallbacks) {
  20434. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  20435. this._dumpShadersName();
  20436. defines = fallbacks.reduce(defines);
  20437. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  20438. }
  20439. else {
  20440. BABYLON.Tools.Error("Unable to compile effect: ");
  20441. this._dumpShadersName();
  20442. BABYLON.Tools.Error("Defines: " + defines);
  20443. BABYLON.Tools.Error("Error: " + e.message);
  20444. this._compilationError = e.message;
  20445. if (this.onError) {
  20446. this.onError(this, this._compilationError);
  20447. }
  20448. }
  20449. }
  20450. };
  20451. Object.defineProperty(Effect.prototype, "isSupported", {
  20452. get: function () {
  20453. return this._compilationError === "";
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. Effect.prototype._bindTexture = function (channel, texture) {
  20459. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  20460. };
  20461. Effect.prototype.setTexture = function (channel, texture) {
  20462. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  20463. };
  20464. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  20465. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  20466. };
  20467. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  20468. if (!this._valueCache[uniformName]) {
  20469. this._valueCache[uniformName] = new BABYLON.Matrix();
  20470. }
  20471. for (var index = 0; index < 16; index++) {
  20472. this._valueCache[uniformName].m[index] = matrix.m[index];
  20473. }
  20474. };
  20475. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  20476. if (!this._valueCache[uniformName]) {
  20477. this._valueCache[uniformName] = [x, y];
  20478. return;
  20479. }
  20480. this._valueCache[uniformName][0] = x;
  20481. this._valueCache[uniformName][1] = y;
  20482. };
  20483. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  20484. if (!this._valueCache[uniformName]) {
  20485. this._valueCache[uniformName] = [x, y, z];
  20486. return;
  20487. }
  20488. this._valueCache[uniformName][0] = x;
  20489. this._valueCache[uniformName][1] = y;
  20490. this._valueCache[uniformName][2] = z;
  20491. };
  20492. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  20493. if (!this._valueCache[uniformName]) {
  20494. this._valueCache[uniformName] = [x, y, z, w];
  20495. return;
  20496. }
  20497. this._valueCache[uniformName][0] = x;
  20498. this._valueCache[uniformName][1] = y;
  20499. this._valueCache[uniformName][2] = z;
  20500. this._valueCache[uniformName][3] = w;
  20501. };
  20502. Effect.prototype.setArray = function (uniformName, array) {
  20503. this._engine.setArray(this.getUniform(uniformName), array);
  20504. return this;
  20505. };
  20506. Effect.prototype.setArray2 = function (uniformName, array) {
  20507. this._engine.setArray2(this.getUniform(uniformName), array);
  20508. return this;
  20509. };
  20510. Effect.prototype.setArray3 = function (uniformName, array) {
  20511. this._engine.setArray3(this.getUniform(uniformName), array);
  20512. return this;
  20513. };
  20514. Effect.prototype.setArray4 = function (uniformName, array) {
  20515. this._engine.setArray4(this.getUniform(uniformName), array);
  20516. return this;
  20517. };
  20518. Effect.prototype.setMatrices = function (uniformName, matrices) {
  20519. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  20520. return this;
  20521. };
  20522. Effect.prototype.setMatrix = function (uniformName, matrix) {
  20523. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  20524. // return this;
  20525. // this._cacheMatrix(uniformName, matrix);
  20526. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  20527. return this;
  20528. };
  20529. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  20530. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  20531. return this;
  20532. };
  20533. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  20534. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  20535. return this;
  20536. };
  20537. Effect.prototype.setFloat = function (uniformName, value) {
  20538. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  20539. return this;
  20540. this._valueCache[uniformName] = value;
  20541. this._engine.setFloat(this.getUniform(uniformName), value);
  20542. return this;
  20543. };
  20544. Effect.prototype.setBool = function (uniformName, bool) {
  20545. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  20546. return this;
  20547. this._valueCache[uniformName] = bool;
  20548. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  20549. return this;
  20550. };
  20551. Effect.prototype.setVector2 = function (uniformName, vector2) {
  20552. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  20553. return this;
  20554. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  20555. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  20556. return this;
  20557. };
  20558. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  20559. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  20560. return this;
  20561. this._cacheFloat2(uniformName, x, y);
  20562. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  20563. return this;
  20564. };
  20565. Effect.prototype.setVector3 = function (uniformName, vector3) {
  20566. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  20567. return this;
  20568. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  20569. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  20570. return this;
  20571. };
  20572. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  20573. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  20574. return this;
  20575. this._cacheFloat3(uniformName, x, y, z);
  20576. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  20577. return this;
  20578. };
  20579. Effect.prototype.setVector4 = function (uniformName, vector4) {
  20580. 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)
  20581. return this;
  20582. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  20583. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  20584. return this;
  20585. };
  20586. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  20587. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  20588. return this;
  20589. this._cacheFloat4(uniformName, x, y, z, w);
  20590. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  20591. return this;
  20592. };
  20593. Effect.prototype.setColor3 = function (uniformName, color3) {
  20594. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  20595. return this;
  20596. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  20597. this._engine.setColor3(this.getUniform(uniformName), color3);
  20598. return this;
  20599. };
  20600. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  20601. 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)
  20602. return this;
  20603. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  20604. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  20605. return this;
  20606. };
  20607. // Statics
  20608. Effect.ShadersStore = {};
  20609. Effect.IncludesShadersStore = {};
  20610. return Effect;
  20611. })();
  20612. BABYLON.Effect = Effect;
  20613. })(BABYLON || (BABYLON = {}));
  20614. var BABYLON;
  20615. (function (BABYLON) {
  20616. var maxSimultaneousLights = 4;
  20617. var MaterialHelper = (function () {
  20618. function MaterialHelper() {
  20619. }
  20620. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  20621. var lightIndex = 0;
  20622. var needNormals = false;
  20623. for (var index = 0; index < scene.lights.length; index++) {
  20624. var light = scene.lights[index];
  20625. if (!light.isEnabled()) {
  20626. continue;
  20627. }
  20628. // Excluded check
  20629. if (light._excludedMeshesIds.length > 0) {
  20630. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  20631. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  20632. if (excludedMesh) {
  20633. light.excludedMeshes.push(excludedMesh);
  20634. }
  20635. }
  20636. light._excludedMeshesIds = [];
  20637. }
  20638. // Included check
  20639. if (light._includedOnlyMeshesIds.length > 0) {
  20640. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  20641. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  20642. if (includedOnlyMesh) {
  20643. light.includedOnlyMeshes.push(includedOnlyMesh);
  20644. }
  20645. }
  20646. light._includedOnlyMeshesIds = [];
  20647. }
  20648. if (!light.canAffectMesh(mesh)) {
  20649. continue;
  20650. }
  20651. needNormals = true;
  20652. defines["LIGHT" + lightIndex] = true;
  20653. var type;
  20654. if (light instanceof BABYLON.SpotLight) {
  20655. type = "SPOTLIGHT" + lightIndex;
  20656. }
  20657. else if (light instanceof BABYLON.HemisphericLight) {
  20658. type = "HEMILIGHT" + lightIndex;
  20659. }
  20660. else if (light instanceof BABYLON.PointLight) {
  20661. type = "POINTLIGHT" + lightIndex;
  20662. }
  20663. else {
  20664. type = "DIRLIGHT" + lightIndex;
  20665. }
  20666. defines[type] = true;
  20667. // Specular
  20668. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  20669. defines["SPECULARTERM"] = true;
  20670. }
  20671. // Shadows
  20672. if (scene.shadowsEnabled) {
  20673. var shadowGenerator = light.getShadowGenerator();
  20674. if (mesh && mesh.receiveShadows && shadowGenerator) {
  20675. defines["SHADOW" + lightIndex] = true;
  20676. defines["SHADOWS"] = true;
  20677. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  20678. defines["SHADOWVSM" + lightIndex] = true;
  20679. }
  20680. if (shadowGenerator.usePoissonSampling) {
  20681. defines["SHADOWPCF" + lightIndex] = true;
  20682. }
  20683. }
  20684. }
  20685. lightIndex++;
  20686. if (lightIndex === maxSimultaneousLights)
  20687. break;
  20688. }
  20689. return needNormals;
  20690. };
  20691. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  20692. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  20693. if (!defines["LIGHT" + lightIndex]) {
  20694. continue;
  20695. }
  20696. if (lightIndex > 0) {
  20697. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  20698. }
  20699. if (defines["SHADOW" + lightIndex]) {
  20700. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  20701. }
  20702. if (defines["SHADOWPCF" + lightIndex]) {
  20703. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  20704. }
  20705. if (defines["SHADOWVSM" + lightIndex]) {
  20706. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  20707. }
  20708. }
  20709. };
  20710. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  20711. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  20712. fallbacks.addCPUSkinningFallback(0, mesh);
  20713. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20714. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20715. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  20716. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  20717. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  20718. }
  20719. }
  20720. };
  20721. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  20722. if (defines["INSTANCES"]) {
  20723. attribs.push("world0");
  20724. attribs.push("world1");
  20725. attribs.push("world2");
  20726. attribs.push("world3");
  20727. }
  20728. };
  20729. // Bindings
  20730. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  20731. var shadowGenerator = light.getShadowGenerator();
  20732. if (mesh.receiveShadows && shadowGenerator) {
  20733. if (!light.needCube()) {
  20734. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  20735. }
  20736. else {
  20737. if (!depthValuesAlreadySet) {
  20738. depthValuesAlreadySet = true;
  20739. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  20740. }
  20741. }
  20742. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  20743. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  20744. }
  20745. return depthValuesAlreadySet;
  20746. };
  20747. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  20748. if (light instanceof BABYLON.PointLight) {
  20749. // Point Light
  20750. light.transferToEffect(effect, "vLightData" + lightIndex);
  20751. }
  20752. else if (light instanceof BABYLON.DirectionalLight) {
  20753. // Directional Light
  20754. light.transferToEffect(effect, "vLightData" + lightIndex);
  20755. }
  20756. else if (light instanceof BABYLON.SpotLight) {
  20757. // Spot Light
  20758. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  20759. }
  20760. else if (light instanceof BABYLON.HemisphericLight) {
  20761. // Hemispheric Light
  20762. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  20763. }
  20764. };
  20765. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  20766. var lightIndex = 0;
  20767. var depthValuesAlreadySet = false;
  20768. for (var index = 0; index < scene.lights.length; index++) {
  20769. var light = scene.lights[index];
  20770. if (!light.isEnabled()) {
  20771. continue;
  20772. }
  20773. if (!light.canAffectMesh(mesh)) {
  20774. continue;
  20775. }
  20776. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  20777. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  20778. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  20779. if (defines["SPECULARTERM"]) {
  20780. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  20781. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  20782. }
  20783. // Shadows
  20784. if (scene.shadowsEnabled) {
  20785. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  20786. }
  20787. lightIndex++;
  20788. if (lightIndex === maxSimultaneousLights)
  20789. break;
  20790. }
  20791. };
  20792. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  20793. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  20794. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  20795. effect.setColor3("vFogColor", scene.fogColor);
  20796. }
  20797. };
  20798. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  20799. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  20800. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  20801. }
  20802. };
  20803. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  20804. if (defines["LOGARITHMICDEPTH"]) {
  20805. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  20806. }
  20807. };
  20808. MaterialHelper.BindClipPlane = function (effect, scene) {
  20809. if (scene.clipPlane) {
  20810. var clipPlane = scene.clipPlane;
  20811. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20812. }
  20813. };
  20814. return MaterialHelper;
  20815. })();
  20816. BABYLON.MaterialHelper = MaterialHelper;
  20817. })(BABYLON || (BABYLON = {}));
  20818. var BABYLON;
  20819. (function (BABYLON) {
  20820. var FresnelParameters = (function () {
  20821. function FresnelParameters() {
  20822. this.isEnabled = true;
  20823. this.leftColor = BABYLON.Color3.White();
  20824. this.rightColor = BABYLON.Color3.Black();
  20825. this.bias = 0;
  20826. this.power = 1;
  20827. }
  20828. FresnelParameters.prototype.clone = function () {
  20829. var newFresnelParameters = new FresnelParameters();
  20830. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  20831. return new FresnelParameters;
  20832. };
  20833. FresnelParameters.prototype.serialize = function () {
  20834. var serializationObject = {};
  20835. serializationObject.isEnabled = this.isEnabled;
  20836. serializationObject.leftColor = this.leftColor;
  20837. serializationObject.rightColor = this.rightColor;
  20838. serializationObject.bias = this.bias;
  20839. serializationObject.power = this.power;
  20840. return serializationObject;
  20841. };
  20842. FresnelParameters.Parse = function (parsedFresnelParameters) {
  20843. var fresnelParameters = new FresnelParameters();
  20844. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  20845. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  20846. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  20847. fresnelParameters.bias = parsedFresnelParameters.bias;
  20848. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  20849. return fresnelParameters;
  20850. };
  20851. return FresnelParameters;
  20852. })();
  20853. BABYLON.FresnelParameters = FresnelParameters;
  20854. })(BABYLON || (BABYLON = {}));
  20855. var BABYLON;
  20856. (function (BABYLON) {
  20857. var MaterialDefines = (function () {
  20858. function MaterialDefines() {
  20859. }
  20860. MaterialDefines.prototype.isEqual = function (other) {
  20861. for (var index = 0; index < this._keys.length; index++) {
  20862. var prop = this._keys[index];
  20863. if (this[prop] !== other[prop]) {
  20864. return false;
  20865. }
  20866. }
  20867. return true;
  20868. };
  20869. MaterialDefines.prototype.cloneTo = function (other) {
  20870. for (var index = 0; index < this._keys.length; index++) {
  20871. var prop = this._keys[index];
  20872. other[prop] = this[prop];
  20873. }
  20874. };
  20875. MaterialDefines.prototype.reset = function () {
  20876. for (var index = 0; index < this._keys.length; index++) {
  20877. var prop = this._keys[index];
  20878. if (typeof (this[prop]) === "number") {
  20879. this[prop] = 0;
  20880. }
  20881. else {
  20882. this[prop] = false;
  20883. }
  20884. }
  20885. };
  20886. MaterialDefines.prototype.toString = function () {
  20887. var result = "";
  20888. for (var index = 0; index < this._keys.length; index++) {
  20889. var prop = this._keys[index];
  20890. if (typeof (this[prop]) === "number") {
  20891. result += "#define " + prop + " " + this[prop] + "\n";
  20892. }
  20893. else if (this[prop]) {
  20894. result += "#define " + prop + "\n";
  20895. }
  20896. }
  20897. return result;
  20898. };
  20899. return MaterialDefines;
  20900. })();
  20901. BABYLON.MaterialDefines = MaterialDefines;
  20902. var Material = (function () {
  20903. function Material(name, scene, doNotAdd) {
  20904. this.name = name;
  20905. this.checkReadyOnEveryCall = false;
  20906. this.checkReadyOnlyOnce = false;
  20907. this.state = "";
  20908. this.alpha = 1.0;
  20909. this.backFaceCulling = true;
  20910. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  20911. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  20912. this.disableDepthWrite = false;
  20913. this.fogEnabled = true;
  20914. this.pointSize = 1.0;
  20915. this.zOffset = 0;
  20916. this._wasPreviouslyReady = false;
  20917. this._fillMode = Material.TriangleFillMode;
  20918. this.id = name;
  20919. this._scene = scene;
  20920. if (!doNotAdd) {
  20921. scene.materials.push(this);
  20922. }
  20923. }
  20924. Object.defineProperty(Material, "TriangleFillMode", {
  20925. get: function () {
  20926. return Material._TriangleFillMode;
  20927. },
  20928. enumerable: true,
  20929. configurable: true
  20930. });
  20931. Object.defineProperty(Material, "WireFrameFillMode", {
  20932. get: function () {
  20933. return Material._WireFrameFillMode;
  20934. },
  20935. enumerable: true,
  20936. configurable: true
  20937. });
  20938. Object.defineProperty(Material, "PointFillMode", {
  20939. get: function () {
  20940. return Material._PointFillMode;
  20941. },
  20942. enumerable: true,
  20943. configurable: true
  20944. });
  20945. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  20946. get: function () {
  20947. return Material._ClockWiseSideOrientation;
  20948. },
  20949. enumerable: true,
  20950. configurable: true
  20951. });
  20952. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  20953. get: function () {
  20954. return Material._CounterClockWiseSideOrientation;
  20955. },
  20956. enumerable: true,
  20957. configurable: true
  20958. });
  20959. Object.defineProperty(Material.prototype, "wireframe", {
  20960. get: function () {
  20961. return this._fillMode === Material.WireFrameFillMode;
  20962. },
  20963. set: function (value) {
  20964. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  20965. },
  20966. enumerable: true,
  20967. configurable: true
  20968. });
  20969. Object.defineProperty(Material.prototype, "pointsCloud", {
  20970. get: function () {
  20971. return this._fillMode === Material.PointFillMode;
  20972. },
  20973. set: function (value) {
  20974. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  20975. },
  20976. enumerable: true,
  20977. configurable: true
  20978. });
  20979. Object.defineProperty(Material.prototype, "fillMode", {
  20980. get: function () {
  20981. return this._fillMode;
  20982. },
  20983. set: function (value) {
  20984. this._fillMode = value;
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. /**
  20990. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20991. * subclasses should override adding information pertainent to themselves
  20992. */
  20993. Material.prototype.toString = function (fullDetails) {
  20994. var ret = "Name: " + this.name;
  20995. if (fullDetails) {
  20996. }
  20997. return ret;
  20998. };
  20999. Object.defineProperty(Material.prototype, "isFrozen", {
  21000. get: function () {
  21001. return this.checkReadyOnlyOnce;
  21002. },
  21003. enumerable: true,
  21004. configurable: true
  21005. });
  21006. Material.prototype.freeze = function () {
  21007. this.checkReadyOnlyOnce = true;
  21008. };
  21009. Material.prototype.unfreeze = function () {
  21010. this.checkReadyOnlyOnce = false;
  21011. };
  21012. Material.prototype.isReady = function (mesh, useInstances) {
  21013. return true;
  21014. };
  21015. Material.prototype.getEffect = function () {
  21016. return this._effect;
  21017. };
  21018. Material.prototype.getScene = function () {
  21019. return this._scene;
  21020. };
  21021. Material.prototype.needAlphaBlending = function () {
  21022. return (this.alpha < 1.0);
  21023. };
  21024. Material.prototype.needAlphaTesting = function () {
  21025. return false;
  21026. };
  21027. Material.prototype.getAlphaTestTexture = function () {
  21028. return null;
  21029. };
  21030. Material.prototype.trackCreation = function (onCompiled, onError) {
  21031. };
  21032. Material.prototype.markDirty = function () {
  21033. this._wasPreviouslyReady = false;
  21034. };
  21035. Material.prototype._preBind = function () {
  21036. var engine = this._scene.getEngine();
  21037. engine.enableEffect(this._effect);
  21038. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  21039. };
  21040. Material.prototype.bind = function (world, mesh) {
  21041. this._scene._cachedMaterial = this;
  21042. if (this.onBind) {
  21043. this.onBind(this, mesh);
  21044. }
  21045. if (this.disableDepthWrite) {
  21046. var engine = this._scene.getEngine();
  21047. this._cachedDepthWriteState = engine.getDepthWrite();
  21048. engine.setDepthWrite(false);
  21049. }
  21050. };
  21051. Material.prototype.bindOnlyWorldMatrix = function (world) {
  21052. };
  21053. Material.prototype.unbind = function () {
  21054. if (this.disableDepthWrite) {
  21055. var engine = this._scene.getEngine();
  21056. engine.setDepthWrite(this._cachedDepthWriteState);
  21057. }
  21058. };
  21059. Material.prototype.clone = function (name) {
  21060. return null;
  21061. };
  21062. Material.prototype.getBindedMeshes = function () {
  21063. var result = new Array();
  21064. for (var index = 0; index < this._scene.meshes.length; index++) {
  21065. var mesh = this._scene.meshes[index];
  21066. if (mesh.material === this) {
  21067. result.push(mesh);
  21068. }
  21069. }
  21070. return result;
  21071. };
  21072. Material.prototype.dispose = function (forceDisposeEffect) {
  21073. // Animations
  21074. this.getScene().stopAnimation(this);
  21075. // Remove from scene
  21076. var index = this._scene.materials.indexOf(this);
  21077. if (index >= 0) {
  21078. this._scene.materials.splice(index, 1);
  21079. }
  21080. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  21081. if (forceDisposeEffect && this._effect) {
  21082. this._scene.getEngine()._releaseEffect(this._effect);
  21083. this._effect = null;
  21084. }
  21085. // Remove from meshes
  21086. for (index = 0; index < this._scene.meshes.length; index++) {
  21087. var mesh = this._scene.meshes[index];
  21088. if (mesh.material === this) {
  21089. mesh.material = null;
  21090. }
  21091. }
  21092. // Callback
  21093. if (this.onDispose) {
  21094. this.onDispose();
  21095. }
  21096. };
  21097. Material.prototype.serialize = function () {
  21098. return BABYLON.SerializationHelper.Serialize(this);
  21099. };
  21100. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  21101. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  21102. multiMaterial.id = parsedMultiMaterial.id;
  21103. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  21104. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21105. var subMatId = parsedMultiMaterial.materials[matIndex];
  21106. if (subMatId) {
  21107. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  21108. }
  21109. else {
  21110. multiMaterial.subMaterials.push(null);
  21111. }
  21112. }
  21113. return multiMaterial;
  21114. };
  21115. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  21116. if (!parsedMaterial.customType) {
  21117. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  21118. }
  21119. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  21120. return materialType.Parse(parsedMaterial, scene, rootUrl);
  21121. ;
  21122. };
  21123. Material._TriangleFillMode = 0;
  21124. Material._WireFrameFillMode = 1;
  21125. Material._PointFillMode = 2;
  21126. Material._ClockWiseSideOrientation = 0;
  21127. Material._CounterClockWiseSideOrientation = 1;
  21128. __decorate([
  21129. BABYLON.serialize()
  21130. ], Material.prototype, "id", void 0);
  21131. __decorate([
  21132. BABYLON.serialize()
  21133. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  21134. __decorate([
  21135. BABYLON.serialize()
  21136. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  21137. __decorate([
  21138. BABYLON.serialize()
  21139. ], Material.prototype, "state", void 0);
  21140. __decorate([
  21141. BABYLON.serialize()
  21142. ], Material.prototype, "alpha", void 0);
  21143. __decorate([
  21144. BABYLON.serialize()
  21145. ], Material.prototype, "backFaceCulling", void 0);
  21146. __decorate([
  21147. BABYLON.serialize()
  21148. ], Material.prototype, "sideOrientation", void 0);
  21149. __decorate([
  21150. BABYLON.serialize()
  21151. ], Material.prototype, "alphaMode", void 0);
  21152. __decorate([
  21153. BABYLON.serialize()
  21154. ], Material.prototype, "disableDepthWrite", void 0);
  21155. __decorate([
  21156. BABYLON.serialize()
  21157. ], Material.prototype, "fogEnabled", void 0);
  21158. __decorate([
  21159. BABYLON.serialize()
  21160. ], Material.prototype, "pointSize", void 0);
  21161. __decorate([
  21162. BABYLON.serialize()
  21163. ], Material.prototype, "zOffset", void 0);
  21164. __decorate([
  21165. BABYLON.serialize()
  21166. ], Material.prototype, "wireframe", null);
  21167. __decorate([
  21168. BABYLON.serialize()
  21169. ], Material.prototype, "pointsCloud", null);
  21170. __decorate([
  21171. BABYLON.serialize()
  21172. ], Material.prototype, "fillMode", null);
  21173. return Material;
  21174. })();
  21175. BABYLON.Material = Material;
  21176. })(BABYLON || (BABYLON = {}));
  21177. var BABYLON;
  21178. (function (BABYLON) {
  21179. var StandardMaterialDefines = (function (_super) {
  21180. __extends(StandardMaterialDefines, _super);
  21181. function StandardMaterialDefines() {
  21182. _super.call(this);
  21183. this.DIFFUSE = false;
  21184. this.AMBIENT = false;
  21185. this.OPACITY = false;
  21186. this.OPACITYRGB = false;
  21187. this.REFLECTION = false;
  21188. this.EMISSIVE = false;
  21189. this.SPECULAR = false;
  21190. this.BUMP = false;
  21191. this.PARALLAX = false;
  21192. this.PARALLAXOCCLUSION = false;
  21193. this.SPECULAROVERALPHA = false;
  21194. this.CLIPPLANE = false;
  21195. this.ALPHATEST = false;
  21196. this.ALPHAFROMDIFFUSE = false;
  21197. this.POINTSIZE = false;
  21198. this.FOG = false;
  21199. this.LIGHT0 = false;
  21200. this.LIGHT1 = false;
  21201. this.LIGHT2 = false;
  21202. this.LIGHT3 = false;
  21203. this.SPOTLIGHT0 = false;
  21204. this.SPOTLIGHT1 = false;
  21205. this.SPOTLIGHT2 = false;
  21206. this.SPOTLIGHT3 = false;
  21207. this.HEMILIGHT0 = false;
  21208. this.HEMILIGHT1 = false;
  21209. this.HEMILIGHT2 = false;
  21210. this.HEMILIGHT3 = false;
  21211. this.POINTLIGHT0 = false;
  21212. this.POINTLIGHT1 = false;
  21213. this.POINTLIGHT2 = false;
  21214. this.POINTLIGHT3 = false;
  21215. this.DIRLIGHT0 = false;
  21216. this.DIRLIGHT1 = false;
  21217. this.DIRLIGHT2 = false;
  21218. this.DIRLIGHT3 = false;
  21219. this.SPECULARTERM = false;
  21220. this.SHADOW0 = false;
  21221. this.SHADOW1 = false;
  21222. this.SHADOW2 = false;
  21223. this.SHADOW3 = false;
  21224. this.SHADOWS = false;
  21225. this.SHADOWVSM0 = false;
  21226. this.SHADOWVSM1 = false;
  21227. this.SHADOWVSM2 = false;
  21228. this.SHADOWVSM3 = false;
  21229. this.SHADOWPCF0 = false;
  21230. this.SHADOWPCF1 = false;
  21231. this.SHADOWPCF2 = false;
  21232. this.SHADOWPCF3 = false;
  21233. this.DIFFUSEFRESNEL = false;
  21234. this.OPACITYFRESNEL = false;
  21235. this.REFLECTIONFRESNEL = false;
  21236. this.REFRACTIONFRESNEL = false;
  21237. this.EMISSIVEFRESNEL = false;
  21238. this.FRESNEL = false;
  21239. this.NORMAL = false;
  21240. this.UV1 = false;
  21241. this.UV2 = false;
  21242. this.VERTEXCOLOR = false;
  21243. this.VERTEXALPHA = false;
  21244. this.NUM_BONE_INFLUENCERS = 0;
  21245. this.BonesPerMesh = 0;
  21246. this.INSTANCES = false;
  21247. this.GLOSSINESS = false;
  21248. this.ROUGHNESS = false;
  21249. this.EMISSIVEASILLUMINATION = false;
  21250. this.LINKEMISSIVEWITHDIFFUSE = false;
  21251. this.REFLECTIONFRESNELFROMSPECULAR = false;
  21252. this.LIGHTMAP = false;
  21253. this.USELIGHTMAPASSHADOWMAP = false;
  21254. this.REFLECTIONMAP_3D = false;
  21255. this.REFLECTIONMAP_SPHERICAL = false;
  21256. this.REFLECTIONMAP_PLANAR = false;
  21257. this.REFLECTIONMAP_CUBIC = false;
  21258. this.REFLECTIONMAP_PROJECTION = false;
  21259. this.REFLECTIONMAP_SKYBOX = false;
  21260. this.REFLECTIONMAP_EXPLICIT = false;
  21261. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  21262. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  21263. this.INVERTCUBICMAP = false;
  21264. this.LOGARITHMICDEPTH = false;
  21265. this.REFRACTION = false;
  21266. this.REFRACTIONMAP_3D = false;
  21267. this.REFLECTIONOVERALPHA = false;
  21268. this._keys = Object.keys(this);
  21269. }
  21270. return StandardMaterialDefines;
  21271. })(BABYLON.MaterialDefines);
  21272. var StandardMaterial = (function (_super) {
  21273. __extends(StandardMaterial, _super);
  21274. function StandardMaterial(name, scene) {
  21275. var _this = this;
  21276. _super.call(this, name, scene);
  21277. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21278. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  21279. this.specularColor = new BABYLON.Color3(1, 1, 1);
  21280. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  21281. this.specularPower = 64;
  21282. this.useAlphaFromDiffuseTexture = false;
  21283. this.useEmissiveAsIllumination = false;
  21284. this.linkEmissiveWithDiffuse = false;
  21285. this.useReflectionFresnelFromSpecular = false;
  21286. this.useSpecularOverAlpha = false;
  21287. this.useReflectionOverAlpha = false;
  21288. this.disableLighting = false;
  21289. this.useParallax = false;
  21290. this.useParallaxOcclusion = false;
  21291. this.parallaxScaleBias = 0.05;
  21292. this.roughness = 0;
  21293. this.indexOfRefraction = 0.98;
  21294. this.invertRefractionY = true;
  21295. this.useLightmapAsShadowmap = false;
  21296. this.useGlossinessFromSpecularMapAlpha = false;
  21297. this._renderTargets = new BABYLON.SmartArray(16);
  21298. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  21299. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  21300. this._defines = new StandardMaterialDefines();
  21301. this._cachedDefines = new StandardMaterialDefines();
  21302. this._cachedDefines.BonesPerMesh = -1;
  21303. this.getRenderTargetTextures = function () {
  21304. _this._renderTargets.reset();
  21305. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  21306. _this._renderTargets.push(_this.reflectionTexture);
  21307. }
  21308. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  21309. _this._renderTargets.push(_this.refractionTexture);
  21310. }
  21311. return _this._renderTargets;
  21312. };
  21313. }
  21314. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  21315. get: function () {
  21316. return this._useLogarithmicDepth;
  21317. },
  21318. set: function (value) {
  21319. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  21320. },
  21321. enumerable: true,
  21322. configurable: true
  21323. });
  21324. StandardMaterial.prototype.needAlphaBlending = function () {
  21325. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  21326. };
  21327. StandardMaterial.prototype.needAlphaTesting = function () {
  21328. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  21329. };
  21330. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  21331. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  21332. };
  21333. StandardMaterial.prototype.getAlphaTestTexture = function () {
  21334. return this.diffuseTexture;
  21335. };
  21336. // Methods
  21337. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  21338. if (!mesh) {
  21339. return true;
  21340. }
  21341. if (this._defines.INSTANCES !== useInstances) {
  21342. return false;
  21343. }
  21344. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  21345. return true;
  21346. }
  21347. return false;
  21348. };
  21349. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  21350. if (this.isFrozen) {
  21351. if (this._wasPreviouslyReady) {
  21352. return true;
  21353. }
  21354. }
  21355. var scene = this.getScene();
  21356. if (!this.checkReadyOnEveryCall) {
  21357. if (this._renderId === scene.getRenderId()) {
  21358. if (this._checkCache(scene, mesh, useInstances)) {
  21359. return true;
  21360. }
  21361. }
  21362. }
  21363. var engine = scene.getEngine();
  21364. var needNormals = false;
  21365. var needUVs = false;
  21366. this._defines.reset();
  21367. // Textures
  21368. if (scene.texturesEnabled) {
  21369. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  21370. if (!this.diffuseTexture.isReady()) {
  21371. return false;
  21372. }
  21373. else {
  21374. needUVs = true;
  21375. this._defines.DIFFUSE = true;
  21376. }
  21377. }
  21378. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  21379. if (!this.ambientTexture.isReady()) {
  21380. return false;
  21381. }
  21382. else {
  21383. needUVs = true;
  21384. this._defines.AMBIENT = true;
  21385. }
  21386. }
  21387. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  21388. if (!this.opacityTexture.isReady()) {
  21389. return false;
  21390. }
  21391. else {
  21392. needUVs = true;
  21393. this._defines.OPACITY = true;
  21394. if (this.opacityTexture.getAlphaFromRGB) {
  21395. this._defines.OPACITYRGB = true;
  21396. }
  21397. }
  21398. }
  21399. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  21400. if (!this.reflectionTexture.isReady()) {
  21401. return false;
  21402. }
  21403. else {
  21404. needNormals = true;
  21405. this._defines.REFLECTION = true;
  21406. if (this.roughness > 0) {
  21407. this._defines.ROUGHNESS = true;
  21408. }
  21409. if (this.useReflectionOverAlpha) {
  21410. this._defines.REFLECTIONOVERALPHA = true;
  21411. }
  21412. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  21413. this._defines.INVERTCUBICMAP = true;
  21414. }
  21415. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  21416. switch (this.reflectionTexture.coordinatesMode) {
  21417. case BABYLON.Texture.CUBIC_MODE:
  21418. case BABYLON.Texture.INVCUBIC_MODE:
  21419. this._defines.REFLECTIONMAP_CUBIC = true;
  21420. break;
  21421. case BABYLON.Texture.EXPLICIT_MODE:
  21422. this._defines.REFLECTIONMAP_EXPLICIT = true;
  21423. break;
  21424. case BABYLON.Texture.PLANAR_MODE:
  21425. this._defines.REFLECTIONMAP_PLANAR = true;
  21426. break;
  21427. case BABYLON.Texture.PROJECTION_MODE:
  21428. this._defines.REFLECTIONMAP_PROJECTION = true;
  21429. break;
  21430. case BABYLON.Texture.SKYBOX_MODE:
  21431. this._defines.REFLECTIONMAP_SKYBOX = true;
  21432. break;
  21433. case BABYLON.Texture.SPHERICAL_MODE:
  21434. this._defines.REFLECTIONMAP_SPHERICAL = true;
  21435. break;
  21436. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  21437. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  21438. break;
  21439. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  21440. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  21441. break;
  21442. }
  21443. }
  21444. }
  21445. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  21446. if (!this.emissiveTexture.isReady()) {
  21447. return false;
  21448. }
  21449. else {
  21450. needUVs = true;
  21451. this._defines.EMISSIVE = true;
  21452. }
  21453. }
  21454. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  21455. if (!this.lightmapTexture.isReady()) {
  21456. return false;
  21457. }
  21458. else {
  21459. needUVs = true;
  21460. this._defines.LIGHTMAP = true;
  21461. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  21462. }
  21463. }
  21464. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  21465. if (!this.specularTexture.isReady()) {
  21466. return false;
  21467. }
  21468. else {
  21469. needUVs = true;
  21470. this._defines.SPECULAR = true;
  21471. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  21472. }
  21473. }
  21474. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  21475. if (!this.bumpTexture.isReady()) {
  21476. return false;
  21477. }
  21478. else {
  21479. needUVs = true;
  21480. this._defines.BUMP = true;
  21481. if (this.useParallax) {
  21482. this._defines.PARALLAX = true;
  21483. if (this.useParallaxOcclusion) {
  21484. this._defines.PARALLAXOCCLUSION = true;
  21485. }
  21486. }
  21487. }
  21488. }
  21489. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  21490. if (!this.refractionTexture.isReady()) {
  21491. return false;
  21492. }
  21493. else {
  21494. needUVs = true;
  21495. this._defines.REFRACTION = true;
  21496. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  21497. }
  21498. }
  21499. }
  21500. // Effect
  21501. if (scene.clipPlane) {
  21502. this._defines.CLIPPLANE = true;
  21503. }
  21504. if (engine.getAlphaTesting()) {
  21505. this._defines.ALPHATEST = true;
  21506. }
  21507. if (this._shouldUseAlphaFromDiffuseTexture()) {
  21508. this._defines.ALPHAFROMDIFFUSE = true;
  21509. }
  21510. if (this.useEmissiveAsIllumination) {
  21511. this._defines.EMISSIVEASILLUMINATION = true;
  21512. }
  21513. if (this.linkEmissiveWithDiffuse) {
  21514. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  21515. }
  21516. if (this.useLogarithmicDepth) {
  21517. this._defines.LOGARITHMICDEPTH = true;
  21518. }
  21519. // Point size
  21520. if (this.pointsCloud || scene.forcePointsCloud) {
  21521. this._defines.POINTSIZE = true;
  21522. }
  21523. // Fog
  21524. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21525. this._defines.FOG = true;
  21526. }
  21527. if (scene.lightsEnabled && !this.disableLighting) {
  21528. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  21529. }
  21530. if (StandardMaterial.FresnelEnabled) {
  21531. // Fresnel
  21532. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  21533. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  21534. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  21535. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  21536. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21537. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  21538. this._defines.DIFFUSEFRESNEL = true;
  21539. }
  21540. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  21541. this._defines.OPACITYFRESNEL = true;
  21542. }
  21543. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21544. this._defines.REFLECTIONFRESNEL = true;
  21545. if (this.useReflectionFresnelFromSpecular) {
  21546. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  21547. }
  21548. }
  21549. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  21550. this._defines.REFRACTIONFRESNEL = true;
  21551. }
  21552. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  21553. this._defines.EMISSIVEFRESNEL = true;
  21554. }
  21555. needNormals = true;
  21556. this._defines.FRESNEL = true;
  21557. }
  21558. }
  21559. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  21560. this._defines.SPECULAROVERALPHA = true;
  21561. }
  21562. // Attribs
  21563. if (mesh) {
  21564. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21565. this._defines.NORMAL = true;
  21566. }
  21567. if (needUVs) {
  21568. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21569. this._defines.UV1 = true;
  21570. }
  21571. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21572. this._defines.UV2 = true;
  21573. }
  21574. }
  21575. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21576. this._defines.VERTEXCOLOR = true;
  21577. if (mesh.hasVertexAlpha) {
  21578. this._defines.VERTEXALPHA = true;
  21579. }
  21580. }
  21581. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  21582. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  21583. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  21584. }
  21585. // Instances
  21586. if (useInstances) {
  21587. this._defines.INSTANCES = true;
  21588. }
  21589. }
  21590. // Get correct effect
  21591. if (!this._defines.isEqual(this._cachedDefines)) {
  21592. this._defines.cloneTo(this._cachedDefines);
  21593. scene.resetCachedMaterial();
  21594. // Fallbacks
  21595. var fallbacks = new BABYLON.EffectFallbacks();
  21596. if (this._defines.REFLECTION) {
  21597. fallbacks.addFallback(0, "REFLECTION");
  21598. }
  21599. if (this._defines.SPECULAR) {
  21600. fallbacks.addFallback(0, "SPECULAR");
  21601. }
  21602. if (this._defines.BUMP) {
  21603. fallbacks.addFallback(0, "BUMP");
  21604. }
  21605. if (this._defines.PARALLAX) {
  21606. fallbacks.addFallback(1, "PARALLAX");
  21607. }
  21608. if (this._defines.PARALLAXOCCLUSION) {
  21609. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  21610. }
  21611. if (this._defines.SPECULAROVERALPHA) {
  21612. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  21613. }
  21614. if (this._defines.FOG) {
  21615. fallbacks.addFallback(1, "FOG");
  21616. }
  21617. if (this._defines.POINTSIZE) {
  21618. fallbacks.addFallback(0, "POINTSIZE");
  21619. }
  21620. if (this._defines.LOGARITHMICDEPTH) {
  21621. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  21622. }
  21623. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  21624. if (this._defines.SPECULARTERM) {
  21625. fallbacks.addFallback(0, "SPECULARTERM");
  21626. }
  21627. if (this._defines.DIFFUSEFRESNEL) {
  21628. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  21629. }
  21630. if (this._defines.OPACITYFRESNEL) {
  21631. fallbacks.addFallback(2, "OPACITYFRESNEL");
  21632. }
  21633. if (this._defines.REFLECTIONFRESNEL) {
  21634. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  21635. }
  21636. if (this._defines.EMISSIVEFRESNEL) {
  21637. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  21638. }
  21639. if (this._defines.FRESNEL) {
  21640. fallbacks.addFallback(4, "FRESNEL");
  21641. }
  21642. //Attributes
  21643. var attribs = [BABYLON.VertexBuffer.PositionKind];
  21644. if (this._defines.NORMAL) {
  21645. attribs.push(BABYLON.VertexBuffer.NormalKind);
  21646. }
  21647. if (this._defines.UV1) {
  21648. attribs.push(BABYLON.VertexBuffer.UVKind);
  21649. }
  21650. if (this._defines.UV2) {
  21651. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  21652. }
  21653. if (this._defines.VERTEXCOLOR) {
  21654. attribs.push(BABYLON.VertexBuffer.ColorKind);
  21655. }
  21656. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  21657. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  21658. // Legacy browser patch
  21659. var shaderName = "default";
  21660. if (!scene.getEngine().getCaps().standardDerivatives) {
  21661. shaderName = "legacydefault";
  21662. }
  21663. var join = this._defines.toString();
  21664. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  21665. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  21666. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  21667. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  21668. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  21669. "vFogInfos", "vFogColor", "pointSize",
  21670. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  21671. "mBones",
  21672. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  21673. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  21674. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  21675. "logarithmicDepthConstant"
  21676. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  21677. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  21678. ], join, fallbacks, this.onCompiled, this.onError);
  21679. }
  21680. if (!this._effect.isReady()) {
  21681. return false;
  21682. }
  21683. this._renderId = scene.getRenderId();
  21684. this._wasPreviouslyReady = true;
  21685. if (mesh) {
  21686. if (!mesh._materialDefines) {
  21687. mesh._materialDefines = new StandardMaterialDefines();
  21688. }
  21689. this._defines.cloneTo(mesh._materialDefines);
  21690. }
  21691. return true;
  21692. };
  21693. StandardMaterial.prototype.unbind = function () {
  21694. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  21695. this._effect.setTexture("reflection2DSampler", null);
  21696. }
  21697. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  21698. this._effect.setTexture("refraction2DSampler", null);
  21699. }
  21700. _super.prototype.unbind.call(this);
  21701. };
  21702. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21703. this._effect.setMatrix("world", world);
  21704. };
  21705. StandardMaterial.prototype.bind = function (world, mesh) {
  21706. var scene = this.getScene();
  21707. // Matrices
  21708. this.bindOnlyWorldMatrix(world);
  21709. // Bones
  21710. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  21711. if (scene.getCachedMaterial() !== this) {
  21712. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  21713. if (StandardMaterial.FresnelEnabled) {
  21714. // Fresnel
  21715. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  21716. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  21717. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  21718. }
  21719. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  21720. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  21721. }
  21722. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21723. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  21724. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  21725. }
  21726. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  21727. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  21728. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  21729. }
  21730. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  21731. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  21732. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  21733. }
  21734. }
  21735. // Textures
  21736. if (scene.texturesEnabled) {
  21737. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  21738. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  21739. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  21740. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  21741. }
  21742. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  21743. this._effect.setTexture("ambientSampler", this.ambientTexture);
  21744. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  21745. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  21746. }
  21747. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  21748. this._effect.setTexture("opacitySampler", this.opacityTexture);
  21749. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  21750. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  21751. }
  21752. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  21753. if (this.reflectionTexture.isCube) {
  21754. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  21755. }
  21756. else {
  21757. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  21758. }
  21759. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  21760. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  21761. }
  21762. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  21763. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  21764. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  21765. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  21766. }
  21767. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  21768. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  21769. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  21770. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  21771. }
  21772. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  21773. this._effect.setTexture("specularSampler", this.specularTexture);
  21774. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  21775. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  21776. }
  21777. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  21778. this._effect.setTexture("bumpSampler", this.bumpTexture);
  21779. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  21780. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  21781. }
  21782. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  21783. var depth = 1.0;
  21784. if (this.refractionTexture.isCube) {
  21785. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  21786. }
  21787. else {
  21788. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  21789. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  21790. if (this.refractionTexture.depth) {
  21791. depth = this.refractionTexture.depth;
  21792. }
  21793. }
  21794. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  21795. }
  21796. }
  21797. // Clip plane
  21798. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  21799. // Point size
  21800. if (this.pointsCloud) {
  21801. this._effect.setFloat("pointSize", this.pointSize);
  21802. }
  21803. // Colors
  21804. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  21805. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  21806. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  21807. if (this._defines.SPECULARTERM) {
  21808. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  21809. }
  21810. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  21811. }
  21812. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  21813. // Diffuse
  21814. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  21815. // Lights
  21816. if (scene.lightsEnabled && !this.disableLighting) {
  21817. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  21818. }
  21819. // View
  21820. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  21821. this._effect.setMatrix("view", scene.getViewMatrix());
  21822. }
  21823. // Fog
  21824. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  21825. // Log. depth
  21826. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  21827. }
  21828. _super.prototype.bind.call(this, world, mesh);
  21829. };
  21830. StandardMaterial.prototype.getAnimatables = function () {
  21831. var results = [];
  21832. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  21833. results.push(this.diffuseTexture);
  21834. }
  21835. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  21836. results.push(this.ambientTexture);
  21837. }
  21838. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  21839. results.push(this.opacityTexture);
  21840. }
  21841. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  21842. results.push(this.reflectionTexture);
  21843. }
  21844. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  21845. results.push(this.emissiveTexture);
  21846. }
  21847. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  21848. results.push(this.specularTexture);
  21849. }
  21850. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  21851. results.push(this.bumpTexture);
  21852. }
  21853. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  21854. results.push(this.lightmapTexture);
  21855. }
  21856. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  21857. results.push(this.refractionTexture);
  21858. }
  21859. return results;
  21860. };
  21861. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  21862. if (this.diffuseTexture) {
  21863. this.diffuseTexture.dispose();
  21864. }
  21865. if (this.ambientTexture) {
  21866. this.ambientTexture.dispose();
  21867. }
  21868. if (this.opacityTexture) {
  21869. this.opacityTexture.dispose();
  21870. }
  21871. if (this.reflectionTexture) {
  21872. this.reflectionTexture.dispose();
  21873. }
  21874. if (this.emissiveTexture) {
  21875. this.emissiveTexture.dispose();
  21876. }
  21877. if (this.specularTexture) {
  21878. this.specularTexture.dispose();
  21879. }
  21880. if (this.bumpTexture) {
  21881. this.bumpTexture.dispose();
  21882. }
  21883. if (this.lightmapTexture) {
  21884. this.lightmapTexture.dispose();
  21885. }
  21886. if (this.refractionTexture) {
  21887. this.refractionTexture.dispose();
  21888. }
  21889. _super.prototype.dispose.call(this, forceDisposeEffect);
  21890. };
  21891. StandardMaterial.prototype.clone = function (name) {
  21892. var _this = this;
  21893. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  21894. };
  21895. StandardMaterial.prototype.serialize = function () {
  21896. return BABYLON.SerializationHelper.Serialize(this);
  21897. };
  21898. // Statics
  21899. StandardMaterial.Parse = function (source, scene, rootUrl) {
  21900. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  21901. };
  21902. // Flags used to enable or disable a type of texture for all Standard Materials
  21903. StandardMaterial.DiffuseTextureEnabled = true;
  21904. StandardMaterial.AmbientTextureEnabled = true;
  21905. StandardMaterial.OpacityTextureEnabled = true;
  21906. StandardMaterial.ReflectionTextureEnabled = true;
  21907. StandardMaterial.EmissiveTextureEnabled = true;
  21908. StandardMaterial.SpecularTextureEnabled = true;
  21909. StandardMaterial.BumpTextureEnabled = true;
  21910. StandardMaterial.FresnelEnabled = true;
  21911. StandardMaterial.LightmapTextureEnabled = true;
  21912. StandardMaterial.RefractionTextureEnabled = true;
  21913. __decorate([
  21914. BABYLON.serializeAsTexture()
  21915. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  21916. __decorate([
  21917. BABYLON.serializeAsTexture()
  21918. ], StandardMaterial.prototype, "ambientTexture", void 0);
  21919. __decorate([
  21920. BABYLON.serializeAsTexture()
  21921. ], StandardMaterial.prototype, "opacityTexture", void 0);
  21922. __decorate([
  21923. BABYLON.serializeAsTexture()
  21924. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  21925. __decorate([
  21926. BABYLON.serializeAsTexture()
  21927. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  21928. __decorate([
  21929. BABYLON.serializeAsTexture()
  21930. ], StandardMaterial.prototype, "specularTexture", void 0);
  21931. __decorate([
  21932. BABYLON.serializeAsTexture()
  21933. ], StandardMaterial.prototype, "bumpTexture", void 0);
  21934. __decorate([
  21935. BABYLON.serializeAsTexture()
  21936. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  21937. __decorate([
  21938. BABYLON.serializeAsTexture()
  21939. ], StandardMaterial.prototype, "refractionTexture", void 0);
  21940. __decorate([
  21941. BABYLON.serializeAsColor3("ambient")
  21942. ], StandardMaterial.prototype, "ambientColor", void 0);
  21943. __decorate([
  21944. BABYLON.serializeAsColor3("diffuse")
  21945. ], StandardMaterial.prototype, "diffuseColor", void 0);
  21946. __decorate([
  21947. BABYLON.serializeAsColor3("specular")
  21948. ], StandardMaterial.prototype, "specularColor", void 0);
  21949. __decorate([
  21950. BABYLON.serializeAsColor3("emissive")
  21951. ], StandardMaterial.prototype, "emissiveColor", void 0);
  21952. __decorate([
  21953. BABYLON.serialize()
  21954. ], StandardMaterial.prototype, "specularPower", void 0);
  21955. __decorate([
  21956. BABYLON.serialize()
  21957. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  21958. __decorate([
  21959. BABYLON.serialize()
  21960. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  21961. __decorate([
  21962. BABYLON.serialize()
  21963. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  21964. __decorate([
  21965. BABYLON.serialize()
  21966. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  21967. __decorate([
  21968. BABYLON.serialize()
  21969. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  21970. __decorate([
  21971. BABYLON.serialize()
  21972. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  21973. __decorate([
  21974. BABYLON.serialize()
  21975. ], StandardMaterial.prototype, "disableLighting", void 0);
  21976. __decorate([
  21977. BABYLON.serialize()
  21978. ], StandardMaterial.prototype, "useParallax", void 0);
  21979. __decorate([
  21980. BABYLON.serialize()
  21981. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  21982. __decorate([
  21983. BABYLON.serialize()
  21984. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  21985. __decorate([
  21986. BABYLON.serialize()
  21987. ], StandardMaterial.prototype, "roughness", void 0);
  21988. __decorate([
  21989. BABYLON.serialize()
  21990. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  21991. __decorate([
  21992. BABYLON.serialize()
  21993. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  21994. __decorate([
  21995. BABYLON.serialize()
  21996. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  21997. __decorate([
  21998. BABYLON.serializeAsFresnelParameters()
  21999. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  22000. __decorate([
  22001. BABYLON.serializeAsFresnelParameters()
  22002. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  22003. __decorate([
  22004. BABYLON.serializeAsFresnelParameters()
  22005. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  22006. __decorate([
  22007. BABYLON.serializeAsFresnelParameters()
  22008. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  22009. __decorate([
  22010. BABYLON.serializeAsFresnelParameters()
  22011. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  22012. __decorate([
  22013. BABYLON.serialize()
  22014. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  22015. __decorate([
  22016. BABYLON.serialize()
  22017. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  22018. return StandardMaterial;
  22019. })(BABYLON.Material);
  22020. BABYLON.StandardMaterial = StandardMaterial;
  22021. })(BABYLON || (BABYLON = {}));
  22022. var BABYLON;
  22023. (function (BABYLON) {
  22024. var MultiMaterial = (function (_super) {
  22025. __extends(MultiMaterial, _super);
  22026. function MultiMaterial(name, scene) {
  22027. _super.call(this, name, scene, true);
  22028. this.subMaterials = new Array();
  22029. scene.multiMaterials.push(this);
  22030. }
  22031. // Properties
  22032. MultiMaterial.prototype.getSubMaterial = function (index) {
  22033. if (index < 0 || index >= this.subMaterials.length) {
  22034. return this.getScene().defaultMaterial;
  22035. }
  22036. return this.subMaterials[index];
  22037. };
  22038. // Methods
  22039. MultiMaterial.prototype.isReady = function (mesh) {
  22040. for (var index = 0; index < this.subMaterials.length; index++) {
  22041. var subMaterial = this.subMaterials[index];
  22042. if (subMaterial) {
  22043. if (!this.subMaterials[index].isReady(mesh)) {
  22044. return false;
  22045. }
  22046. }
  22047. }
  22048. return true;
  22049. };
  22050. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  22051. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  22052. for (var index = 0; index < this.subMaterials.length; index++) {
  22053. var subMaterial = null;
  22054. if (cloneChildren) {
  22055. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  22056. }
  22057. else {
  22058. subMaterial = this.subMaterials[index];
  22059. }
  22060. newMultiMaterial.subMaterials.push(subMaterial);
  22061. }
  22062. return newMultiMaterial;
  22063. };
  22064. MultiMaterial.prototype.serialize = function () {
  22065. var serializationObject = {};
  22066. serializationObject.name = this.name;
  22067. serializationObject.id = this.id;
  22068. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22069. serializationObject.materials = [];
  22070. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  22071. var subMat = this.subMaterials[matIndex];
  22072. if (subMat) {
  22073. serializationObject.materials.push(subMat.id);
  22074. }
  22075. else {
  22076. serializationObject.materials.push(null);
  22077. }
  22078. }
  22079. return serializationObject;
  22080. };
  22081. return MultiMaterial;
  22082. })(BABYLON.Material);
  22083. BABYLON.MultiMaterial = MultiMaterial;
  22084. })(BABYLON || (BABYLON = {}));
  22085. var BABYLON;
  22086. (function (BABYLON) {
  22087. var SceneLoader = (function () {
  22088. function SceneLoader() {
  22089. }
  22090. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  22091. get: function () {
  22092. return 0;
  22093. },
  22094. enumerable: true,
  22095. configurable: true
  22096. });
  22097. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  22098. get: function () {
  22099. return 1;
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  22105. get: function () {
  22106. return 2;
  22107. },
  22108. enumerable: true,
  22109. configurable: true
  22110. });
  22111. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  22112. get: function () {
  22113. return 3;
  22114. },
  22115. enumerable: true,
  22116. configurable: true
  22117. });
  22118. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  22119. get: function () {
  22120. return SceneLoader._ForceFullSceneLoadingForIncremental;
  22121. },
  22122. set: function (value) {
  22123. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  22124. },
  22125. enumerable: true,
  22126. configurable: true
  22127. });
  22128. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  22129. get: function () {
  22130. return SceneLoader._ShowLoadingScreen;
  22131. },
  22132. set: function (value) {
  22133. SceneLoader._ShowLoadingScreen = value;
  22134. },
  22135. enumerable: true,
  22136. configurable: true
  22137. });
  22138. Object.defineProperty(SceneLoader, "loggingLevel", {
  22139. get: function () {
  22140. return SceneLoader._loggingLevel;
  22141. },
  22142. set: function (value) {
  22143. SceneLoader._loggingLevel = value;
  22144. },
  22145. enumerable: true,
  22146. configurable: true
  22147. });
  22148. SceneLoader._getPluginForFilename = function (sceneFilename) {
  22149. var dotPosition = sceneFilename.lastIndexOf(".");
  22150. var queryStringPosition = sceneFilename.indexOf("?");
  22151. if (queryStringPosition === -1) {
  22152. queryStringPosition = sceneFilename.length;
  22153. }
  22154. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  22155. for (var index = 0; index < this._registeredPlugins.length; index++) {
  22156. var plugin = this._registeredPlugins[index];
  22157. if (plugin.extensions.indexOf(extension) !== -1) {
  22158. return plugin;
  22159. }
  22160. }
  22161. return this._registeredPlugins[this._registeredPlugins.length - 1];
  22162. };
  22163. // Public functions
  22164. SceneLoader.GetPluginForExtension = function (extension) {
  22165. for (var index = 0; index < this._registeredPlugins.length; index++) {
  22166. var plugin = this._registeredPlugins[index];
  22167. if (plugin.extensions.indexOf(extension) !== -1) {
  22168. return plugin;
  22169. }
  22170. }
  22171. return null;
  22172. };
  22173. SceneLoader.RegisterPlugin = function (plugin) {
  22174. plugin.extensions = plugin.extensions.toLowerCase();
  22175. SceneLoader._registeredPlugins.push(plugin);
  22176. };
  22177. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  22178. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  22179. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  22180. return;
  22181. }
  22182. var loadingToken = {};
  22183. scene._addPendingData(loadingToken);
  22184. var manifestChecked = function (success) {
  22185. scene.database = database;
  22186. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  22187. var importMeshFromData = function (data) {
  22188. var meshes = [];
  22189. var particleSystems = [];
  22190. var skeletons = [];
  22191. try {
  22192. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  22193. if (onerror) {
  22194. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  22195. }
  22196. scene._removePendingData(loadingToken);
  22197. return;
  22198. }
  22199. }
  22200. catch (e) {
  22201. if (onerror) {
  22202. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  22203. }
  22204. scene._removePendingData(loadingToken);
  22205. return;
  22206. }
  22207. if (onsuccess) {
  22208. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  22209. onsuccess(meshes, particleSystems, skeletons);
  22210. scene._removePendingData(loadingToken);
  22211. }
  22212. };
  22213. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  22214. // Direct load
  22215. importMeshFromData(sceneFilename.substr(5));
  22216. return;
  22217. }
  22218. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  22219. importMeshFromData(data);
  22220. }, progressCallBack, database);
  22221. };
  22222. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  22223. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  22224. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  22225. }
  22226. else {
  22227. // If the scene is a data stream or offline support is not enabled, it's a direct load
  22228. manifestChecked(true);
  22229. }
  22230. };
  22231. /**
  22232. * Load a scene
  22233. * @param rootUrl a string that defines the root url for scene and resources
  22234. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  22235. * @param engine is the instance of BABYLON.Engine to use to create the scene
  22236. */
  22237. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  22238. if (!SceneLoader._warned) {
  22239. BABYLON.Tools.Warn("SceneLoader.Load deprecated since 2.4. Use SceneLoader.Append.");
  22240. SceneLoader._warned = true;
  22241. }
  22242. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  22243. };
  22244. /**
  22245. * Append a scene
  22246. * @param rootUrl a string that defines the root url for scene and resources
  22247. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  22248. * @param scene is the instance of BABYLON.Scene to append to
  22249. */
  22250. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  22251. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  22252. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  22253. return;
  22254. }
  22255. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  22256. var database;
  22257. var loadingToken = {};
  22258. scene._addPendingData(loadingToken);
  22259. if (SceneLoader.ShowLoadingScreen) {
  22260. scene.getEngine().displayLoadingUI();
  22261. }
  22262. var loadSceneFromData = function (data) {
  22263. scene.database = database;
  22264. if (!plugin.load(scene, data, rootUrl)) {
  22265. if (onerror) {
  22266. onerror(scene);
  22267. }
  22268. scene._removePendingData(loadingToken);
  22269. scene.getEngine().hideLoadingUI();
  22270. return;
  22271. }
  22272. if (onsuccess) {
  22273. onsuccess(scene);
  22274. }
  22275. scene._removePendingData(loadingToken);
  22276. if (SceneLoader.ShowLoadingScreen) {
  22277. scene.executeWhenReady(function () {
  22278. scene.getEngine().hideLoadingUI();
  22279. });
  22280. }
  22281. };
  22282. var manifestChecked = function (success) {
  22283. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  22284. };
  22285. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  22286. // Direct load
  22287. loadSceneFromData(sceneFilename.substr(5));
  22288. return;
  22289. }
  22290. if (rootUrl.indexOf("file:") === -1) {
  22291. if (scene.getEngine().enableOfflineSupport) {
  22292. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  22293. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  22294. }
  22295. else {
  22296. manifestChecked(true);
  22297. }
  22298. }
  22299. else {
  22300. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  22301. }
  22302. };
  22303. // Flags
  22304. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  22305. SceneLoader._ShowLoadingScreen = true;
  22306. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  22307. // Members
  22308. SceneLoader._registeredPlugins = new Array();
  22309. return SceneLoader;
  22310. })();
  22311. BABYLON.SceneLoader = SceneLoader;
  22312. ;
  22313. })(BABYLON || (BABYLON = {}));
  22314. var BABYLON;
  22315. (function (BABYLON) {
  22316. var Internals;
  22317. (function (Internals) {
  22318. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  22319. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  22320. var parsedMaterial = parsedData.materials[index];
  22321. if (parsedMaterial.id === id) {
  22322. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  22323. }
  22324. }
  22325. return null;
  22326. };
  22327. var isDescendantOf = function (mesh, names, hierarchyIds) {
  22328. names = (names instanceof Array) ? names : [names];
  22329. for (var i in names) {
  22330. if (mesh.name === names[i]) {
  22331. hierarchyIds.push(mesh.id);
  22332. return true;
  22333. }
  22334. }
  22335. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  22336. hierarchyIds.push(mesh.id);
  22337. return true;
  22338. }
  22339. return false;
  22340. };
  22341. var logOperation = function (operation, producer) {
  22342. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  22343. };
  22344. BABYLON.SceneLoader.RegisterPlugin({
  22345. extensions: ".babylon",
  22346. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  22347. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  22348. // when SceneLoader.debugLogging = true (default), or exception encountered.
  22349. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  22350. // and avoid problems with multiple concurrent .babylon loads.
  22351. var log = "importMesh has failed JSON parse";
  22352. try {
  22353. var parsedData = JSON.parse(data);
  22354. log = "";
  22355. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  22356. var loadedSkeletonsIds = [];
  22357. var loadedMaterialsIds = [];
  22358. var hierarchyIds = [];
  22359. var index;
  22360. var cache;
  22361. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  22362. var parsedMesh = parsedData.meshes[index];
  22363. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  22364. if (meshesNames instanceof Array) {
  22365. // Remove found mesh name from list.
  22366. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  22367. }
  22368. //Geometry?
  22369. if (parsedMesh.geometryId) {
  22370. //does the file contain geometries?
  22371. if (parsedData.geometries) {
  22372. //find the correct geometry and add it to the scene
  22373. var found = false;
  22374. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  22375. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  22376. return;
  22377. }
  22378. else {
  22379. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  22380. if (parsedGeometryData.id === parsedMesh.geometryId) {
  22381. switch (geometryType) {
  22382. case "boxes":
  22383. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  22384. break;
  22385. case "spheres":
  22386. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  22387. break;
  22388. case "cylinders":
  22389. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  22390. break;
  22391. case "toruses":
  22392. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  22393. break;
  22394. case "grounds":
  22395. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  22396. break;
  22397. case "planes":
  22398. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  22399. break;
  22400. case "torusKnots":
  22401. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  22402. break;
  22403. case "vertexData":
  22404. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  22405. break;
  22406. }
  22407. found = true;
  22408. }
  22409. });
  22410. }
  22411. });
  22412. if (!found) {
  22413. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  22414. }
  22415. }
  22416. }
  22417. // Material ?
  22418. if (parsedMesh.materialId) {
  22419. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  22420. if (!materialFound && parsedData.multiMaterials) {
  22421. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  22422. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  22423. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  22424. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  22425. var subMatId = parsedMultiMaterial.materials[matIndex];
  22426. loadedMaterialsIds.push(subMatId);
  22427. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  22428. log += "\n\tMaterial " + mat.toString(fullDetails);
  22429. }
  22430. loadedMaterialsIds.push(parsedMultiMaterial.id);
  22431. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  22432. materialFound = true;
  22433. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  22434. break;
  22435. }
  22436. }
  22437. }
  22438. if (!materialFound) {
  22439. loadedMaterialsIds.push(parsedMesh.materialId);
  22440. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  22441. if (!mat) {
  22442. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  22443. }
  22444. else {
  22445. log += "\n\tMaterial " + mat.toString(fullDetails);
  22446. }
  22447. }
  22448. }
  22449. // Skeleton ?
  22450. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  22451. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  22452. if (!skeletonAlreadyLoaded) {
  22453. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  22454. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  22455. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  22456. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  22457. skeletons.push(skeleton);
  22458. loadedSkeletonsIds.push(parsedSkeleton.id);
  22459. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  22460. }
  22461. }
  22462. }
  22463. }
  22464. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  22465. meshes.push(mesh);
  22466. log += "\n\tMesh " + mesh.toString(fullDetails);
  22467. }
  22468. }
  22469. // Connecting parents
  22470. var currentMesh;
  22471. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22472. currentMesh = scene.meshes[index];
  22473. if (currentMesh._waitingParentId) {
  22474. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  22475. currentMesh._waitingParentId = undefined;
  22476. }
  22477. }
  22478. // freeze and compute world matrix application
  22479. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22480. currentMesh = scene.meshes[index];
  22481. if (currentMesh._waitingFreezeWorldMatrix) {
  22482. currentMesh.freezeWorldMatrix();
  22483. currentMesh._waitingFreezeWorldMatrix = undefined;
  22484. }
  22485. else {
  22486. currentMesh.computeWorldMatrix(true);
  22487. }
  22488. }
  22489. // Particles
  22490. if (parsedData.particleSystems) {
  22491. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  22492. var parsedParticleSystem = parsedData.particleSystems[index];
  22493. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  22494. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  22495. }
  22496. }
  22497. }
  22498. return true;
  22499. }
  22500. catch (err) {
  22501. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  22502. log = null;
  22503. throw err;
  22504. }
  22505. finally {
  22506. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  22507. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  22508. }
  22509. }
  22510. },
  22511. load: function (scene, data, rootUrl) {
  22512. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  22513. // when SceneLoader.debugLogging = true (default), or exception encountered.
  22514. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  22515. // and avoid problems with multiple concurrent .babylon loads.
  22516. var log = "importScene has failed JSON parse";
  22517. try {
  22518. var parsedData = JSON.parse(data);
  22519. log = "";
  22520. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  22521. // Scene
  22522. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  22523. scene.autoClear = parsedData.autoClear;
  22524. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  22525. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  22526. if (parsedData.gravity) {
  22527. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  22528. }
  22529. // Fog
  22530. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  22531. scene.fogMode = parsedData.fogMode;
  22532. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  22533. scene.fogStart = parsedData.fogStart;
  22534. scene.fogEnd = parsedData.fogEnd;
  22535. scene.fogDensity = parsedData.fogDensity;
  22536. log += "\tFog mode for scene: ";
  22537. switch (scene.fogMode) {
  22538. // getters not compiling, so using hardcoded
  22539. case 1:
  22540. log += "exp\n";
  22541. break;
  22542. case 2:
  22543. log += "exp2\n";
  22544. break;
  22545. case 3:
  22546. log += "linear\n";
  22547. break;
  22548. }
  22549. }
  22550. //Physics
  22551. if (parsedData.physicsEnabled) {
  22552. var physicsPlugin;
  22553. if (parsedData.physicsEngine === "cannon") {
  22554. physicsPlugin = new BABYLON.CannonJSPlugin();
  22555. }
  22556. else if (parsedData.physicsEngine === "oimo") {
  22557. physicsPlugin = new BABYLON.OimoJSPlugin();
  22558. }
  22559. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  22560. //else - default engine, which is currently oimo
  22561. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  22562. scene.enablePhysics(physicsGravity, physicsPlugin);
  22563. }
  22564. //collisions, if defined. otherwise, default is true
  22565. if (parsedData.collisionsEnabled != undefined) {
  22566. scene.collisionsEnabled = parsedData.collisionsEnabled;
  22567. }
  22568. scene.workerCollisions = !!parsedData.workerCollisions;
  22569. var index;
  22570. var cache;
  22571. // Lights
  22572. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  22573. var parsedLight = parsedData.lights[index];
  22574. var light = BABYLON.Light.Parse(parsedLight, scene);
  22575. log += (index === 0 ? "\n\tLights:" : "");
  22576. log += "\n\t\t" + light.toString(fullDetails);
  22577. }
  22578. // Animations
  22579. if (parsedData.animations) {
  22580. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  22581. var parsedAnimation = parsedData.animations[index];
  22582. var animation = BABYLON.Animation.Parse(parsedAnimation);
  22583. scene.animations.push(animation);
  22584. log += (index === 0 ? "\n\tAnimations:" : "");
  22585. log += "\n\t\t" + animation.toString(fullDetails);
  22586. }
  22587. }
  22588. // Materials
  22589. if (parsedData.materials) {
  22590. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  22591. var parsedMaterial = parsedData.materials[index];
  22592. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  22593. log += (index === 0 ? "\n\tMaterials:" : "");
  22594. log += "\n\t\t" + mat.toString(fullDetails);
  22595. }
  22596. }
  22597. if (parsedData.multiMaterials) {
  22598. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  22599. var parsedMultiMaterial = parsedData.multiMaterials[index];
  22600. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  22601. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  22602. log += "\n\t\t" + mmat.toString(fullDetails);
  22603. }
  22604. }
  22605. // Skeletons
  22606. if (parsedData.skeletons) {
  22607. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  22608. var parsedSkeleton = parsedData.skeletons[index];
  22609. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  22610. log += (index === 0 ? "\n\tSkeletons:" : "");
  22611. log += "\n\t\t" + skeleton.toString(fullDetails);
  22612. }
  22613. }
  22614. // Geometries
  22615. var geometries = parsedData.geometries;
  22616. if (geometries) {
  22617. // Boxes
  22618. var boxes = geometries.boxes;
  22619. if (boxes) {
  22620. for (index = 0, cache = boxes.length; index < cache; index++) {
  22621. var parsedBox = boxes[index];
  22622. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  22623. }
  22624. }
  22625. // Spheres
  22626. var spheres = geometries.spheres;
  22627. if (spheres) {
  22628. for (index = 0, cache = spheres.length; index < cache; index++) {
  22629. var parsedSphere = spheres[index];
  22630. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  22631. }
  22632. }
  22633. // Cylinders
  22634. var cylinders = geometries.cylinders;
  22635. if (cylinders) {
  22636. for (index = 0, cache = cylinders.length; index < cache; index++) {
  22637. var parsedCylinder = cylinders[index];
  22638. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  22639. }
  22640. }
  22641. // Toruses
  22642. var toruses = geometries.toruses;
  22643. if (toruses) {
  22644. for (index = 0, cache = toruses.length; index < cache; index++) {
  22645. var parsedTorus = toruses[index];
  22646. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  22647. }
  22648. }
  22649. // Grounds
  22650. var grounds = geometries.grounds;
  22651. if (grounds) {
  22652. for (index = 0, cache = grounds.length; index < cache; index++) {
  22653. var parsedGround = grounds[index];
  22654. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  22655. }
  22656. }
  22657. // Planes
  22658. var planes = geometries.planes;
  22659. if (planes) {
  22660. for (index = 0, cache = planes.length; index < cache; index++) {
  22661. var parsedPlane = planes[index];
  22662. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  22663. }
  22664. }
  22665. // TorusKnots
  22666. var torusKnots = geometries.torusKnots;
  22667. if (torusKnots) {
  22668. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  22669. var parsedTorusKnot = torusKnots[index];
  22670. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  22671. }
  22672. }
  22673. // VertexData
  22674. var vertexData = geometries.vertexData;
  22675. if (vertexData) {
  22676. for (index = 0, cache = vertexData.length; index < cache; index++) {
  22677. var parsedVertexData = vertexData[index];
  22678. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  22679. }
  22680. }
  22681. }
  22682. // Meshes
  22683. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  22684. var parsedMesh = parsedData.meshes[index];
  22685. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  22686. log += (index === 0 ? "\n\tMeshes:" : "");
  22687. log += "\n\t\t" + mesh.toString(fullDetails);
  22688. }
  22689. // Cameras
  22690. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  22691. var parsedCamera = parsedData.cameras[index];
  22692. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  22693. log += (index === 0 ? "\n\tCameras:" : "");
  22694. log += "\n\t\t" + camera.toString(fullDetails);
  22695. }
  22696. if (parsedData.activeCameraID) {
  22697. scene.setActiveCameraByID(parsedData.activeCameraID);
  22698. }
  22699. // Browsing all the graph to connect the dots
  22700. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  22701. var camera = scene.cameras[index];
  22702. if (camera._waitingParentId) {
  22703. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  22704. camera._waitingParentId = undefined;
  22705. }
  22706. }
  22707. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  22708. var light = scene.lights[index];
  22709. if (light._waitingParentId) {
  22710. light.parent = scene.getLastEntryByID(light._waitingParentId);
  22711. light._waitingParentId = undefined;
  22712. }
  22713. }
  22714. // Sounds
  22715. var loadedSounds = [];
  22716. var loadedSound;
  22717. if (BABYLON.AudioEngine && parsedData.sounds) {
  22718. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  22719. var parsedSound = parsedData.sounds[index];
  22720. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  22721. if (!parsedSound.url)
  22722. parsedSound.url = parsedSound.name;
  22723. if (!loadedSounds[parsedSound.url]) {
  22724. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  22725. loadedSounds[parsedSound.url] = loadedSound;
  22726. }
  22727. else {
  22728. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  22729. }
  22730. }
  22731. else {
  22732. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  22733. }
  22734. }
  22735. log += (index === 0 ? "\n\tSounds:" : "");
  22736. log += "\n\t\t" + mat.toString(fullDetails);
  22737. }
  22738. loadedSounds = [];
  22739. // Connect parents & children and parse actions
  22740. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22741. var mesh = scene.meshes[index];
  22742. if (mesh._waitingParentId) {
  22743. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  22744. mesh._waitingParentId = undefined;
  22745. }
  22746. if (mesh._waitingActions) {
  22747. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  22748. mesh._waitingActions = undefined;
  22749. }
  22750. }
  22751. // freeze world matrix application
  22752. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22753. var currentMesh = scene.meshes[index];
  22754. if (currentMesh._waitingFreezeWorldMatrix) {
  22755. currentMesh.freezeWorldMatrix();
  22756. currentMesh._waitingFreezeWorldMatrix = undefined;
  22757. }
  22758. else {
  22759. currentMesh.computeWorldMatrix(true);
  22760. }
  22761. }
  22762. // Particles Systems
  22763. if (parsedData.particleSystems) {
  22764. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  22765. var parsedParticleSystem = parsedData.particleSystems[index];
  22766. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  22767. }
  22768. }
  22769. // Lens flares
  22770. if (parsedData.lensFlareSystems) {
  22771. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  22772. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  22773. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  22774. }
  22775. }
  22776. // Shadows
  22777. if (parsedData.shadowGenerators) {
  22778. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  22779. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  22780. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  22781. }
  22782. }
  22783. // Actions (scene)
  22784. if (parsedData.actions) {
  22785. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  22786. }
  22787. // Finish
  22788. return true;
  22789. }
  22790. catch (err) {
  22791. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  22792. log = null;
  22793. throw err;
  22794. }
  22795. finally {
  22796. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  22797. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  22798. }
  22799. }
  22800. }
  22801. });
  22802. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22803. })(BABYLON || (BABYLON = {}));
  22804. var BABYLON;
  22805. (function (BABYLON) {
  22806. var SpriteManager = (function () {
  22807. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  22808. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22809. this.name = name;
  22810. this.cellSize = cellSize;
  22811. this.sprites = new Array();
  22812. this.renderingGroupId = 0;
  22813. this.layerMask = 0x0FFFFFFF;
  22814. this.fogEnabled = true;
  22815. this.isPickable = false;
  22816. this._vertexDeclaration = [4, 4, 4, 4];
  22817. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  22818. this._capacity = capacity;
  22819. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  22820. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22821. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22822. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  22823. this._scene = scene;
  22824. this._scene.spriteManagers.push(this);
  22825. // VBO
  22826. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  22827. var indices = [];
  22828. var index = 0;
  22829. for (var count = 0; count < capacity; count++) {
  22830. indices.push(index);
  22831. indices.push(index + 1);
  22832. indices.push(index + 2);
  22833. indices.push(index);
  22834. indices.push(index + 2);
  22835. indices.push(index + 3);
  22836. index += 4;
  22837. }
  22838. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22839. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  22840. // Effects
  22841. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  22842. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  22843. }
  22844. Object.defineProperty(SpriteManager.prototype, "texture", {
  22845. get: function () {
  22846. return this._spriteTexture;
  22847. },
  22848. set: function (value) {
  22849. this._spriteTexture = value;
  22850. },
  22851. enumerable: true,
  22852. configurable: true
  22853. });
  22854. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  22855. var arrayOffset = index * 16;
  22856. if (offsetX === 0)
  22857. offsetX = this._epsilon;
  22858. else if (offsetX === 1)
  22859. offsetX = 1 - this._epsilon;
  22860. if (offsetY === 0)
  22861. offsetY = this._epsilon;
  22862. else if (offsetY === 1)
  22863. offsetY = 1 - this._epsilon;
  22864. this._vertices[arrayOffset] = sprite.position.x;
  22865. this._vertices[arrayOffset + 1] = sprite.position.y;
  22866. this._vertices[arrayOffset + 2] = sprite.position.z;
  22867. this._vertices[arrayOffset + 3] = sprite.angle;
  22868. this._vertices[arrayOffset + 4] = sprite.width;
  22869. this._vertices[arrayOffset + 5] = sprite.height;
  22870. this._vertices[arrayOffset + 6] = offsetX;
  22871. this._vertices[arrayOffset + 7] = offsetY;
  22872. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  22873. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  22874. var offset = (sprite.cellIndex / rowSize) >> 0;
  22875. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  22876. this._vertices[arrayOffset + 11] = offset;
  22877. // Color
  22878. this._vertices[arrayOffset + 12] = sprite.color.r;
  22879. this._vertices[arrayOffset + 13] = sprite.color.g;
  22880. this._vertices[arrayOffset + 14] = sprite.color.b;
  22881. this._vertices[arrayOffset + 15] = sprite.color.a;
  22882. };
  22883. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  22884. var count = Math.min(this._capacity, this.sprites.length);
  22885. var min = BABYLON.Vector3.Zero();
  22886. var max = BABYLON.Vector3.Zero();
  22887. var distance = Number.MAX_VALUE;
  22888. var currentSprite;
  22889. var cameraSpacePosition = BABYLON.Vector3.Zero();
  22890. var cameraView = camera.getViewMatrix();
  22891. for (var index = 0; index < count; index++) {
  22892. var sprite = this.sprites[index];
  22893. if (!sprite) {
  22894. continue;
  22895. }
  22896. if (predicate) {
  22897. if (!predicate(sprite)) {
  22898. continue;
  22899. }
  22900. }
  22901. else if (!sprite.isPickable) {
  22902. continue;
  22903. }
  22904. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  22905. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  22906. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  22907. if (ray.intersectsBoxMinMax(min, max)) {
  22908. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  22909. if (distance > currentDistance) {
  22910. distance = currentDistance;
  22911. currentSprite = sprite;
  22912. if (fastCheck) {
  22913. break;
  22914. }
  22915. }
  22916. }
  22917. }
  22918. if (currentSprite) {
  22919. var result = new BABYLON.PickingInfo();
  22920. result.hit = true;
  22921. result.pickedSprite = currentSprite;
  22922. result.distance = distance;
  22923. return result;
  22924. }
  22925. return null;
  22926. };
  22927. SpriteManager.prototype.render = function () {
  22928. // Check
  22929. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  22930. return;
  22931. var engine = this._scene.getEngine();
  22932. var baseSize = this._spriteTexture.getBaseSize();
  22933. // Sprites
  22934. var deltaTime = engine.getDeltaTime();
  22935. var max = Math.min(this._capacity, this.sprites.length);
  22936. var rowSize = baseSize.width / this.cellSize;
  22937. var offset = 0;
  22938. for (var index = 0; index < max; index++) {
  22939. var sprite = this.sprites[index];
  22940. if (!sprite) {
  22941. continue;
  22942. }
  22943. sprite._animate(deltaTime);
  22944. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  22945. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  22946. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  22947. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  22948. }
  22949. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22950. // Render
  22951. var effect = this._effectBase;
  22952. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22953. effect = this._effectFog;
  22954. }
  22955. engine.enableEffect(effect);
  22956. var viewMatrix = this._scene.getViewMatrix();
  22957. effect.setTexture("diffuseSampler", this._spriteTexture);
  22958. effect.setMatrix("view", viewMatrix);
  22959. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22960. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  22961. // Fog
  22962. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22963. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  22964. effect.setColor3("vFogColor", this._scene.fogColor);
  22965. }
  22966. // VBOs
  22967. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22968. // Draw order
  22969. engine.setDepthFunctionToLessOrEqual();
  22970. effect.setBool("alphaTest", true);
  22971. engine.setColorWrite(false);
  22972. engine.draw(true, 0, max * 6);
  22973. engine.setColorWrite(true);
  22974. effect.setBool("alphaTest", false);
  22975. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22976. engine.draw(true, 0, max * 6);
  22977. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22978. };
  22979. SpriteManager.prototype.dispose = function () {
  22980. if (this._vertexBuffer) {
  22981. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22982. this._vertexBuffer = null;
  22983. }
  22984. if (this._indexBuffer) {
  22985. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22986. this._indexBuffer = null;
  22987. }
  22988. if (this._spriteTexture) {
  22989. this._spriteTexture.dispose();
  22990. this._spriteTexture = null;
  22991. }
  22992. // Remove from scene
  22993. var index = this._scene.spriteManagers.indexOf(this);
  22994. this._scene.spriteManagers.splice(index, 1);
  22995. // Callback
  22996. if (this.onDispose) {
  22997. this.onDispose();
  22998. }
  22999. };
  23000. return SpriteManager;
  23001. })();
  23002. BABYLON.SpriteManager = SpriteManager;
  23003. })(BABYLON || (BABYLON = {}));
  23004. var BABYLON;
  23005. (function (BABYLON) {
  23006. var Sprite = (function () {
  23007. function Sprite(name, manager) {
  23008. this.name = name;
  23009. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23010. this.width = 1.0;
  23011. this.height = 1.0;
  23012. this.angle = 0;
  23013. this.cellIndex = 0;
  23014. this.invertU = 0;
  23015. this.invertV = 0;
  23016. this.animations = new Array();
  23017. this.isPickable = false;
  23018. this._animationStarted = false;
  23019. this._loopAnimation = false;
  23020. this._fromIndex = 0;
  23021. this._toIndex = 0;
  23022. this._delay = 0;
  23023. this._direction = 1;
  23024. this._frameCount = 0;
  23025. this._time = 0;
  23026. this._manager = manager;
  23027. this._manager.sprites.push(this);
  23028. this.position = BABYLON.Vector3.Zero();
  23029. }
  23030. Object.defineProperty(Sprite.prototype, "size", {
  23031. get: function () {
  23032. return this.width;
  23033. },
  23034. set: function (value) {
  23035. this.width = value;
  23036. this.height = value;
  23037. },
  23038. enumerable: true,
  23039. configurable: true
  23040. });
  23041. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  23042. this._fromIndex = from;
  23043. this._toIndex = to;
  23044. this._loopAnimation = loop;
  23045. this._delay = delay;
  23046. this._animationStarted = true;
  23047. this._direction = from < to ? 1 : -1;
  23048. this.cellIndex = from;
  23049. this._time = 0;
  23050. };
  23051. Sprite.prototype.stopAnimation = function () {
  23052. this._animationStarted = false;
  23053. };
  23054. Sprite.prototype._animate = function (deltaTime) {
  23055. if (!this._animationStarted)
  23056. return;
  23057. this._time += deltaTime;
  23058. if (this._time > this._delay) {
  23059. this._time = this._time % this._delay;
  23060. this.cellIndex += this._direction;
  23061. if (this.cellIndex == this._toIndex) {
  23062. if (this._loopAnimation) {
  23063. this.cellIndex = this._fromIndex;
  23064. }
  23065. else {
  23066. this._animationStarted = false;
  23067. if (this.disposeWhenFinishedAnimating) {
  23068. this.dispose();
  23069. }
  23070. }
  23071. }
  23072. }
  23073. };
  23074. Sprite.prototype.dispose = function () {
  23075. for (var i = 0; i < this._manager.sprites.length; i++) {
  23076. if (this._manager.sprites[i] == this) {
  23077. this._manager.sprites.splice(i, 1);
  23078. }
  23079. }
  23080. };
  23081. return Sprite;
  23082. })();
  23083. BABYLON.Sprite = Sprite;
  23084. })(BABYLON || (BABYLON = {}));
  23085. var BABYLON;
  23086. (function (BABYLON) {
  23087. var Layer = (function () {
  23088. function Layer(name, imgUrl, scene, isBackground, color) {
  23089. this.name = name;
  23090. this.scale = new BABYLON.Vector2(1, 1);
  23091. this.offset = new BABYLON.Vector2(0, 0);
  23092. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  23093. this._vertexDeclaration = [2];
  23094. this._vertexStrideSize = 2 * 4;
  23095. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  23096. this.isBackground = isBackground === undefined ? true : isBackground;
  23097. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  23098. this._scene = scene;
  23099. this._scene.layers.push(this);
  23100. // VBO
  23101. var vertices = [];
  23102. vertices.push(1, 1);
  23103. vertices.push(-1, 1);
  23104. vertices.push(-1, -1);
  23105. vertices.push(1, -1);
  23106. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23107. // Indices
  23108. var indices = [];
  23109. indices.push(0);
  23110. indices.push(1);
  23111. indices.push(2);
  23112. indices.push(0);
  23113. indices.push(2);
  23114. indices.push(3);
  23115. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23116. // Effects
  23117. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  23118. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  23119. }
  23120. Layer.prototype.render = function () {
  23121. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  23122. // Check
  23123. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  23124. return;
  23125. var engine = this._scene.getEngine();
  23126. if (this.onBeforeRender) {
  23127. this.onBeforeRender();
  23128. }
  23129. // Render
  23130. engine.enableEffect(currentEffect);
  23131. engine.setState(false);
  23132. // Texture
  23133. currentEffect.setTexture("textureSampler", this.texture);
  23134. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  23135. // Color
  23136. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  23137. // Scale / offset
  23138. currentEffect.setVector2("offset", this.offset);
  23139. currentEffect.setVector2("scale", this.scale);
  23140. // VBOs
  23141. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  23142. // Draw order
  23143. if (!this._alphaTestEffect) {
  23144. engine.setAlphaMode(this.alphaBlendingMode);
  23145. engine.draw(true, 0, 6);
  23146. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23147. }
  23148. else {
  23149. engine.draw(true, 0, 6);
  23150. }
  23151. if (this.onAfterRender) {
  23152. this.onAfterRender();
  23153. }
  23154. };
  23155. Layer.prototype.dispose = function () {
  23156. if (this._vertexBuffer) {
  23157. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23158. this._vertexBuffer = null;
  23159. }
  23160. if (this._indexBuffer) {
  23161. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23162. this._indexBuffer = null;
  23163. }
  23164. if (this.texture) {
  23165. this.texture.dispose();
  23166. this.texture = null;
  23167. }
  23168. // Remove from scene
  23169. var index = this._scene.layers.indexOf(this);
  23170. this._scene.layers.splice(index, 1);
  23171. // Callback
  23172. if (this.onDispose) {
  23173. this.onDispose();
  23174. }
  23175. };
  23176. return Layer;
  23177. })();
  23178. BABYLON.Layer = Layer;
  23179. })(BABYLON || (BABYLON = {}));
  23180. var BABYLON;
  23181. (function (BABYLON) {
  23182. var Particle = (function () {
  23183. function Particle() {
  23184. this.position = BABYLON.Vector3.Zero();
  23185. this.direction = BABYLON.Vector3.Zero();
  23186. this.color = new BABYLON.Color4(0, 0, 0, 0);
  23187. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  23188. this.lifeTime = 1.0;
  23189. this.age = 0;
  23190. this.size = 0;
  23191. this.angle = 0;
  23192. this.angularSpeed = 0;
  23193. }
  23194. Particle.prototype.copyTo = function (other) {
  23195. other.position.copyFrom(this.position);
  23196. other.direction.copyFrom(this.direction);
  23197. other.color.copyFrom(this.color);
  23198. other.colorStep.copyFrom(this.colorStep);
  23199. other.lifeTime = this.lifeTime;
  23200. other.age = this.age;
  23201. other.size = this.size;
  23202. other.angle = this.angle;
  23203. other.angularSpeed = this.angularSpeed;
  23204. };
  23205. return Particle;
  23206. })();
  23207. BABYLON.Particle = Particle;
  23208. })(BABYLON || (BABYLON = {}));
  23209. var BABYLON;
  23210. (function (BABYLON) {
  23211. var randomNumber = function (min, max) {
  23212. if (min === max) {
  23213. return (min);
  23214. }
  23215. var random = Math.random();
  23216. return ((random * (max - min)) + min);
  23217. };
  23218. var ParticleSystem = (function () {
  23219. function ParticleSystem(name, capacity, scene, customEffect) {
  23220. var _this = this;
  23221. this.name = name;
  23222. // Members
  23223. this.animations = [];
  23224. this.renderingGroupId = 0;
  23225. this.emitter = null;
  23226. this.emitRate = 10;
  23227. this.manualEmitCount = -1;
  23228. this.updateSpeed = 0.01;
  23229. this.targetStopDuration = 0;
  23230. this.disposeOnStop = false;
  23231. this.minEmitPower = 1;
  23232. this.maxEmitPower = 1;
  23233. this.minLifeTime = 1;
  23234. this.maxLifeTime = 1;
  23235. this.minSize = 1;
  23236. this.maxSize = 1;
  23237. this.minAngularSpeed = 0;
  23238. this.maxAngularSpeed = 0;
  23239. this.layerMask = 0x0FFFFFFF;
  23240. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  23241. this.forceDepthWrite = false;
  23242. this.gravity = BABYLON.Vector3.Zero();
  23243. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  23244. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  23245. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  23246. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  23247. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23248. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23249. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  23250. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23251. this.particles = new Array();
  23252. this._vertexDeclaration = [3, 4, 4];
  23253. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  23254. this._stockParticles = new Array();
  23255. this._newPartsExcess = 0;
  23256. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  23257. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  23258. this._scaledDirection = BABYLON.Vector3.Zero();
  23259. this._scaledGravity = BABYLON.Vector3.Zero();
  23260. this._currentRenderId = -1;
  23261. this._started = false;
  23262. this._stopped = false;
  23263. this._actualFrame = 0;
  23264. this.id = name;
  23265. this._capacity = capacity;
  23266. this._scene = scene;
  23267. this._customEffect = customEffect;
  23268. scene.particleSystems.push(this);
  23269. // VBO
  23270. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  23271. var indices = [];
  23272. var index = 0;
  23273. for (var count = 0; count < capacity; count++) {
  23274. indices.push(index);
  23275. indices.push(index + 1);
  23276. indices.push(index + 2);
  23277. indices.push(index);
  23278. indices.push(index + 2);
  23279. indices.push(index + 3);
  23280. index += 4;
  23281. }
  23282. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23283. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  23284. // Default behaviors
  23285. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  23286. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  23287. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  23288. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  23289. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  23290. };
  23291. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  23292. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  23293. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  23294. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  23295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  23296. };
  23297. this.updateFunction = function (particles) {
  23298. for (var index = 0; index < particles.length; index++) {
  23299. var particle = particles[index];
  23300. particle.age += _this._scaledUpdateSpeed;
  23301. if (particle.age >= particle.lifeTime) {
  23302. _this.recycleParticle(particle);
  23303. index--;
  23304. continue;
  23305. }
  23306. else {
  23307. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  23308. particle.color.addInPlace(_this._scaledColorStep);
  23309. if (particle.color.a < 0)
  23310. particle.color.a = 0;
  23311. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  23312. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  23313. particle.position.addInPlace(_this._scaledDirection);
  23314. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  23315. particle.direction.addInPlace(_this._scaledGravity);
  23316. }
  23317. }
  23318. };
  23319. }
  23320. ParticleSystem.prototype.recycleParticle = function (particle) {
  23321. var lastParticle = this.particles.pop();
  23322. if (lastParticle !== particle) {
  23323. lastParticle.copyTo(particle);
  23324. this._stockParticles.push(lastParticle);
  23325. }
  23326. };
  23327. ParticleSystem.prototype.getCapacity = function () {
  23328. return this._capacity;
  23329. };
  23330. ParticleSystem.prototype.isAlive = function () {
  23331. return this._alive;
  23332. };
  23333. ParticleSystem.prototype.isStarted = function () {
  23334. return this._started;
  23335. };
  23336. ParticleSystem.prototype.start = function () {
  23337. this._started = true;
  23338. this._stopped = false;
  23339. this._actualFrame = 0;
  23340. };
  23341. ParticleSystem.prototype.stop = function () {
  23342. this._stopped = true;
  23343. };
  23344. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  23345. var offset = index * 11;
  23346. this._vertices[offset] = particle.position.x;
  23347. this._vertices[offset + 1] = particle.position.y;
  23348. this._vertices[offset + 2] = particle.position.z;
  23349. this._vertices[offset + 3] = particle.color.r;
  23350. this._vertices[offset + 4] = particle.color.g;
  23351. this._vertices[offset + 5] = particle.color.b;
  23352. this._vertices[offset + 6] = particle.color.a;
  23353. this._vertices[offset + 7] = particle.angle;
  23354. this._vertices[offset + 8] = particle.size;
  23355. this._vertices[offset + 9] = offsetX;
  23356. this._vertices[offset + 10] = offsetY;
  23357. };
  23358. ParticleSystem.prototype._update = function (newParticles) {
  23359. // Update current
  23360. this._alive = this.particles.length > 0;
  23361. this.updateFunction(this.particles);
  23362. // Add new ones
  23363. var worldMatrix;
  23364. if (this.emitter.position) {
  23365. worldMatrix = this.emitter.getWorldMatrix();
  23366. }
  23367. else {
  23368. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  23369. }
  23370. var particle;
  23371. for (var index = 0; index < newParticles; index++) {
  23372. if (this.particles.length === this._capacity) {
  23373. break;
  23374. }
  23375. if (this._stockParticles.length !== 0) {
  23376. particle = this._stockParticles.pop();
  23377. particle.age = 0;
  23378. }
  23379. else {
  23380. particle = new BABYLON.Particle();
  23381. }
  23382. this.particles.push(particle);
  23383. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  23384. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  23385. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  23386. particle.size = randomNumber(this.minSize, this.maxSize);
  23387. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  23388. this.startPositionFunction(worldMatrix, particle.position, particle);
  23389. var step = randomNumber(0, 1.0);
  23390. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  23391. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  23392. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  23393. }
  23394. };
  23395. ParticleSystem.prototype._getEffect = function () {
  23396. if (this._customEffect) {
  23397. return this._customEffect;
  23398. }
  23399. ;
  23400. var defines = [];
  23401. if (this._scene.clipPlane) {
  23402. defines.push("#define CLIPPLANE");
  23403. }
  23404. // Effect
  23405. var join = defines.join("\n");
  23406. if (this._cachedDefines !== join) {
  23407. this._cachedDefines = join;
  23408. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  23409. }
  23410. return this._effect;
  23411. };
  23412. ParticleSystem.prototype.animate = function () {
  23413. if (!this._started)
  23414. return;
  23415. var effect = this._getEffect();
  23416. // Check
  23417. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  23418. return;
  23419. if (this._currentRenderId === this._scene.getRenderId()) {
  23420. return;
  23421. }
  23422. this._currentRenderId = this._scene.getRenderId();
  23423. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  23424. // determine the number of particles we need to create
  23425. var newParticles;
  23426. if (this.manualEmitCount > -1) {
  23427. newParticles = this.manualEmitCount;
  23428. this._newPartsExcess = 0;
  23429. this.manualEmitCount = 0;
  23430. }
  23431. else {
  23432. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  23433. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  23434. }
  23435. if (this._newPartsExcess > 1.0) {
  23436. newParticles += this._newPartsExcess >> 0;
  23437. this._newPartsExcess -= this._newPartsExcess >> 0;
  23438. }
  23439. this._alive = false;
  23440. if (!this._stopped) {
  23441. this._actualFrame += this._scaledUpdateSpeed;
  23442. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  23443. this.stop();
  23444. }
  23445. else {
  23446. newParticles = 0;
  23447. }
  23448. this._update(newParticles);
  23449. // Stopped?
  23450. if (this._stopped) {
  23451. if (!this._alive) {
  23452. this._started = false;
  23453. if (this.disposeOnStop) {
  23454. this._scene._toBeDisposed.push(this);
  23455. }
  23456. }
  23457. }
  23458. // Update VBO
  23459. var offset = 0;
  23460. for (var index = 0; index < this.particles.length; index++) {
  23461. var particle = this.particles[index];
  23462. this._appendParticleVertex(offset++, particle, 0, 0);
  23463. this._appendParticleVertex(offset++, particle, 1, 0);
  23464. this._appendParticleVertex(offset++, particle, 1, 1);
  23465. this._appendParticleVertex(offset++, particle, 0, 1);
  23466. }
  23467. var engine = this._scene.getEngine();
  23468. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  23469. };
  23470. ParticleSystem.prototype.render = function () {
  23471. var effect = this._getEffect();
  23472. // Check
  23473. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  23474. return 0;
  23475. var engine = this._scene.getEngine();
  23476. // Render
  23477. engine.enableEffect(effect);
  23478. engine.setState(false);
  23479. var viewMatrix = this._scene.getViewMatrix();
  23480. effect.setTexture("diffuseSampler", this.particleTexture);
  23481. effect.setMatrix("view", viewMatrix);
  23482. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  23483. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  23484. if (this._scene.clipPlane) {
  23485. var clipPlane = this._scene.clipPlane;
  23486. var invView = viewMatrix.clone();
  23487. invView.invert();
  23488. effect.setMatrix("invView", invView);
  23489. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23490. }
  23491. // VBOs
  23492. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23493. // Draw order
  23494. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  23495. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23496. }
  23497. else {
  23498. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23499. }
  23500. if (this.forceDepthWrite) {
  23501. engine.setDepthWrite(true);
  23502. }
  23503. engine.draw(true, 0, this.particles.length * 6);
  23504. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23505. return this.particles.length;
  23506. };
  23507. ParticleSystem.prototype.dispose = function () {
  23508. if (this._vertexBuffer) {
  23509. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23510. this._vertexBuffer = null;
  23511. }
  23512. if (this._indexBuffer) {
  23513. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23514. this._indexBuffer = null;
  23515. }
  23516. if (this.particleTexture) {
  23517. this.particleTexture.dispose();
  23518. this.particleTexture = null;
  23519. }
  23520. // Remove from scene
  23521. var index = this._scene.particleSystems.indexOf(this);
  23522. this._scene.particleSystems.splice(index, 1);
  23523. // Callback
  23524. if (this.onDispose) {
  23525. this.onDispose();
  23526. }
  23527. };
  23528. // Clone
  23529. ParticleSystem.prototype.clone = function (name, newEmitter) {
  23530. var result = new ParticleSystem(name, this._capacity, this._scene);
  23531. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  23532. if (newEmitter === undefined) {
  23533. newEmitter = this.emitter;
  23534. }
  23535. result.emitter = newEmitter;
  23536. if (this.particleTexture) {
  23537. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  23538. }
  23539. result.start();
  23540. return result;
  23541. };
  23542. ParticleSystem.prototype.serialize = function () {
  23543. var serializationObject = {};
  23544. serializationObject.name = this.name;
  23545. serializationObject.id = this.id;
  23546. // Emitter
  23547. if (this.emitter.position) {
  23548. serializationObject.emitterId = this.emitter.id;
  23549. }
  23550. else {
  23551. serializationObject.emitter = this.emitter.asArray();
  23552. }
  23553. serializationObject.capacity = this.getCapacity();
  23554. if (this.particleTexture) {
  23555. serializationObject.textureName = this.particleTexture.name;
  23556. }
  23557. // Animations
  23558. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23559. // Particle system
  23560. serializationObject.minAngularSpeed = this.minAngularSpeed;
  23561. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  23562. serializationObject.minSize = this.minSize;
  23563. serializationObject.maxSize = this.maxSize;
  23564. serializationObject.minEmitPower = this.minEmitPower;
  23565. serializationObject.maxEmitPower = this.maxEmitPower;
  23566. serializationObject.minLifeTime = this.minLifeTime;
  23567. serializationObject.maxLifeTime = this.maxLifeTime;
  23568. serializationObject.emitRate = this.emitRate;
  23569. serializationObject.minEmitBox = this.minEmitBox.asArray();
  23570. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  23571. serializationObject.gravity = this.gravity.asArray();
  23572. serializationObject.direction1 = this.direction1.asArray();
  23573. serializationObject.direction2 = this.direction2.asArray();
  23574. serializationObject.color1 = this.color1.asArray();
  23575. serializationObject.color2 = this.color2.asArray();
  23576. serializationObject.colorDead = this.colorDead.asArray();
  23577. serializationObject.updateSpeed = this.updateSpeed;
  23578. serializationObject.targetStopDuration = this.targetStopDuration;
  23579. serializationObject.textureMask = this.textureMask.asArray();
  23580. serializationObject.blendMode = this.blendMode;
  23581. return serializationObject;
  23582. };
  23583. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  23584. var name = parsedParticleSystem.name;
  23585. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  23586. if (parsedParticleSystem.id) {
  23587. particleSystem.id = parsedParticleSystem.id;
  23588. }
  23589. // Texture
  23590. if (parsedParticleSystem.textureName) {
  23591. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  23592. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  23593. }
  23594. // Emitter
  23595. if (parsedParticleSystem.emitterId) {
  23596. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  23597. }
  23598. else {
  23599. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  23600. }
  23601. // Animations
  23602. if (parsedParticleSystem.animations) {
  23603. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  23604. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  23605. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23606. }
  23607. }
  23608. if (parsedParticleSystem.autoAnimate) {
  23609. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  23610. }
  23611. // Particle system
  23612. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  23613. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  23614. particleSystem.minSize = parsedParticleSystem.minSize;
  23615. particleSystem.maxSize = parsedParticleSystem.maxSize;
  23616. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  23617. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  23618. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  23619. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  23620. particleSystem.emitRate = parsedParticleSystem.emitRate;
  23621. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  23622. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  23623. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  23624. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  23625. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  23626. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  23627. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  23628. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  23629. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  23630. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  23631. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  23632. particleSystem.blendMode = parsedParticleSystem.blendMode;
  23633. particleSystem.start();
  23634. return particleSystem;
  23635. };
  23636. // Statics
  23637. ParticleSystem.BLENDMODE_ONEONE = 0;
  23638. ParticleSystem.BLENDMODE_STANDARD = 1;
  23639. return ParticleSystem;
  23640. })();
  23641. BABYLON.ParticleSystem = ParticleSystem;
  23642. })(BABYLON || (BABYLON = {}));
  23643. var BABYLON;
  23644. (function (BABYLON) {
  23645. var AnimationRange = (function () {
  23646. function AnimationRange(name, from, to) {
  23647. this.name = name;
  23648. this.from = from;
  23649. this.to = to;
  23650. }
  23651. AnimationRange.prototype.clone = function () {
  23652. return new AnimationRange(this.name, this.from, this.to);
  23653. };
  23654. return AnimationRange;
  23655. })();
  23656. BABYLON.AnimationRange = AnimationRange;
  23657. /**
  23658. * Composed of a frame, and an action function
  23659. */
  23660. var AnimationEvent = (function () {
  23661. function AnimationEvent(frame, action, onlyOnce) {
  23662. this.frame = frame;
  23663. this.action = action;
  23664. this.onlyOnce = onlyOnce;
  23665. this.isDone = false;
  23666. }
  23667. return AnimationEvent;
  23668. })();
  23669. BABYLON.AnimationEvent = AnimationEvent;
  23670. var PathCursor = (function () {
  23671. function PathCursor(path) {
  23672. this.path = path;
  23673. this._onchange = new Array();
  23674. this.value = 0;
  23675. this.animations = new Array();
  23676. }
  23677. PathCursor.prototype.getPoint = function () {
  23678. var point = this.path.getPointAtLengthPosition(this.value);
  23679. return new BABYLON.Vector3(point.x, 0, point.y);
  23680. };
  23681. PathCursor.prototype.moveAhead = function (step) {
  23682. if (step === void 0) { step = 0.002; }
  23683. this.move(step);
  23684. return this;
  23685. };
  23686. PathCursor.prototype.moveBack = function (step) {
  23687. if (step === void 0) { step = 0.002; }
  23688. this.move(-step);
  23689. return this;
  23690. };
  23691. PathCursor.prototype.move = function (step) {
  23692. if (Math.abs(step) > 1) {
  23693. throw "step size should be less than 1.";
  23694. }
  23695. this.value += step;
  23696. this.ensureLimits();
  23697. this.raiseOnChange();
  23698. return this;
  23699. };
  23700. PathCursor.prototype.ensureLimits = function () {
  23701. while (this.value > 1) {
  23702. this.value -= 1;
  23703. }
  23704. while (this.value < 0) {
  23705. this.value += 1;
  23706. }
  23707. return this;
  23708. };
  23709. // used by animation engine
  23710. PathCursor.prototype.markAsDirty = function (propertyName) {
  23711. this.ensureLimits();
  23712. this.raiseOnChange();
  23713. return this;
  23714. };
  23715. PathCursor.prototype.raiseOnChange = function () {
  23716. var _this = this;
  23717. this._onchange.forEach(function (f) { return f(_this); });
  23718. return this;
  23719. };
  23720. PathCursor.prototype.onchange = function (f) {
  23721. this._onchange.push(f);
  23722. return this;
  23723. };
  23724. return PathCursor;
  23725. })();
  23726. BABYLON.PathCursor = PathCursor;
  23727. var Animation = (function () {
  23728. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  23729. this.name = name;
  23730. this.targetProperty = targetProperty;
  23731. this.framePerSecond = framePerSecond;
  23732. this.dataType = dataType;
  23733. this.loopMode = loopMode;
  23734. this.enableBlending = enableBlending;
  23735. this._offsetsCache = {};
  23736. this._highLimitsCache = {};
  23737. this._stopped = false;
  23738. this._blendingFactor = 0;
  23739. // The set of event that will be linked to this animation
  23740. this._events = new Array();
  23741. this.allowMatricesInterpolation = false;
  23742. this.blendingSpeed = 0.01;
  23743. this._ranges = {};
  23744. this.targetPropertyPath = targetProperty.split(".");
  23745. this.dataType = dataType;
  23746. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  23747. }
  23748. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  23749. var dataType = undefined;
  23750. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  23751. dataType = Animation.ANIMATIONTYPE_FLOAT;
  23752. }
  23753. else if (from instanceof BABYLON.Quaternion) {
  23754. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  23755. }
  23756. else if (from instanceof BABYLON.Vector3) {
  23757. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  23758. }
  23759. else if (from instanceof BABYLON.Vector2) {
  23760. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  23761. }
  23762. else if (from instanceof BABYLON.Color3) {
  23763. dataType = Animation.ANIMATIONTYPE_COLOR3;
  23764. }
  23765. if (dataType == undefined) {
  23766. return null;
  23767. }
  23768. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  23769. var keys = [];
  23770. keys.push({ frame: 0, value: from });
  23771. keys.push({ frame: totalFrame, value: to });
  23772. animation.setKeys(keys);
  23773. if (easingFunction !== undefined) {
  23774. animation.setEasingFunction(easingFunction);
  23775. }
  23776. return animation;
  23777. };
  23778. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  23779. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  23780. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  23781. };
  23782. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  23783. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  23784. node.animations.push(animation);
  23785. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  23786. };
  23787. // Methods
  23788. /**
  23789. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23790. */
  23791. Animation.prototype.toString = function (fullDetails) {
  23792. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  23793. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  23794. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  23795. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  23796. if (fullDetails) {
  23797. ret += ", Ranges: {";
  23798. var first = true;
  23799. for (var name in this._ranges) {
  23800. if (!first) {
  23801. ret + ", ";
  23802. first = false;
  23803. }
  23804. ret += name;
  23805. }
  23806. ret += "}";
  23807. }
  23808. return ret;
  23809. };
  23810. /**
  23811. * Add an event to this animation.
  23812. */
  23813. Animation.prototype.addEvent = function (event) {
  23814. this._events.push(event);
  23815. };
  23816. /**
  23817. * Remove all events found at the given frame
  23818. * @param frame
  23819. */
  23820. Animation.prototype.removeEvents = function (frame) {
  23821. for (var index = 0; index < this._events.length; index++) {
  23822. if (this._events[index].frame === frame) {
  23823. this._events.splice(index, 1);
  23824. index--;
  23825. }
  23826. }
  23827. };
  23828. Animation.prototype.createRange = function (name, from, to) {
  23829. // check name not already in use; could happen for bones after serialized
  23830. if (!this._ranges[name]) {
  23831. this._ranges[name] = new AnimationRange(name, from, to);
  23832. }
  23833. };
  23834. Animation.prototype.deleteRange = function (name, deleteFrames) {
  23835. if (deleteFrames === void 0) { deleteFrames = true; }
  23836. if (this._ranges[name]) {
  23837. if (deleteFrames) {
  23838. var from = this._ranges[name].from;
  23839. var to = this._ranges[name].to;
  23840. // this loop MUST go high to low for multiple splices to work
  23841. for (var key = this._keys.length - 1; key >= 0; key--) {
  23842. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  23843. this._keys.splice(key, 1);
  23844. }
  23845. }
  23846. }
  23847. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23848. }
  23849. };
  23850. Animation.prototype.getRange = function (name) {
  23851. return this._ranges[name];
  23852. };
  23853. Animation.prototype.reset = function () {
  23854. this._offsetsCache = {};
  23855. this._highLimitsCache = {};
  23856. this.currentFrame = 0;
  23857. this._blendingFactor = 0;
  23858. this._originalBlendValue = null;
  23859. };
  23860. Animation.prototype.isStopped = function () {
  23861. return this._stopped;
  23862. };
  23863. Animation.prototype.getKeys = function () {
  23864. return this._keys;
  23865. };
  23866. Animation.prototype.getHighestFrame = function () {
  23867. var ret = 0;
  23868. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  23869. if (ret < this._keys[key].frame) {
  23870. ret = this._keys[key].frame;
  23871. }
  23872. }
  23873. return ret;
  23874. };
  23875. Animation.prototype.getEasingFunction = function () {
  23876. return this._easingFunction;
  23877. };
  23878. Animation.prototype.setEasingFunction = function (easingFunction) {
  23879. this._easingFunction = easingFunction;
  23880. };
  23881. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  23882. return startValue + (endValue - startValue) * gradient;
  23883. };
  23884. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  23885. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  23886. };
  23887. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  23888. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  23889. };
  23890. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  23891. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  23892. };
  23893. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  23894. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  23895. };
  23896. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  23897. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  23898. };
  23899. Animation.prototype.clone = function () {
  23900. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  23901. if (this._keys) {
  23902. clone.setKeys(this._keys);
  23903. }
  23904. if (this._ranges) {
  23905. clone._ranges = {};
  23906. for (var name in this._ranges) {
  23907. clone._ranges[name] = this._ranges[name].clone();
  23908. }
  23909. }
  23910. return clone;
  23911. };
  23912. Animation.prototype.setKeys = function (values) {
  23913. this._keys = values.slice(0);
  23914. this._offsetsCache = {};
  23915. this._highLimitsCache = {};
  23916. };
  23917. Animation.prototype._getKeyValue = function (value) {
  23918. if (typeof value === "function") {
  23919. return value();
  23920. }
  23921. return value;
  23922. };
  23923. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  23924. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  23925. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  23926. }
  23927. this.currentFrame = currentFrame;
  23928. // Try to get a hash to find the right key
  23929. 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));
  23930. if (this._keys[startKey].frame >= currentFrame) {
  23931. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  23932. startKey--;
  23933. }
  23934. }
  23935. for (var key = startKey; key < this._keys.length; key++) {
  23936. if (this._keys[key + 1].frame >= currentFrame) {
  23937. var startValue = this._getKeyValue(this._keys[key].value);
  23938. var endValue = this._getKeyValue(this._keys[key + 1].value);
  23939. // gradient : percent of currentFrame between the frame inf and the frame sup
  23940. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  23941. // check for easingFunction and correction of gradient
  23942. if (this._easingFunction != null) {
  23943. gradient = this._easingFunction.ease(gradient);
  23944. }
  23945. switch (this.dataType) {
  23946. // Float
  23947. case Animation.ANIMATIONTYPE_FLOAT:
  23948. switch (loopMode) {
  23949. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23950. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23951. return this.floatInterpolateFunction(startValue, endValue, gradient);
  23952. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23953. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  23954. }
  23955. break;
  23956. // Quaternion
  23957. case Animation.ANIMATIONTYPE_QUATERNION:
  23958. var quaternion = null;
  23959. switch (loopMode) {
  23960. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23961. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23962. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  23963. break;
  23964. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23965. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23966. break;
  23967. }
  23968. return quaternion;
  23969. // Vector3
  23970. case Animation.ANIMATIONTYPE_VECTOR3:
  23971. switch (loopMode) {
  23972. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23973. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23974. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  23975. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23976. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23977. }
  23978. // Vector2
  23979. case Animation.ANIMATIONTYPE_VECTOR2:
  23980. switch (loopMode) {
  23981. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23982. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23983. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  23984. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23985. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23986. }
  23987. // Color3
  23988. case Animation.ANIMATIONTYPE_COLOR3:
  23989. switch (loopMode) {
  23990. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23991. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23992. return this.color3InterpolateFunction(startValue, endValue, gradient);
  23993. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23994. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23995. }
  23996. // Matrix
  23997. case Animation.ANIMATIONTYPE_MATRIX:
  23998. switch (loopMode) {
  23999. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24000. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24001. if (this.allowMatricesInterpolation) {
  24002. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  24003. }
  24004. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24005. return startValue;
  24006. }
  24007. default:
  24008. break;
  24009. }
  24010. break;
  24011. }
  24012. }
  24013. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  24014. };
  24015. Animation.prototype.setValue = function (currentValue, blend) {
  24016. if (blend === void 0) { blend = false; }
  24017. // Set value
  24018. var path;
  24019. var destination;
  24020. if (this.targetPropertyPath.length > 1) {
  24021. var property = this._target[this.targetPropertyPath[0]];
  24022. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  24023. property = property[this.targetPropertyPath[index]];
  24024. }
  24025. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  24026. destination = property;
  24027. }
  24028. else {
  24029. path = this.targetPropertyPath[0];
  24030. destination = this._target;
  24031. }
  24032. // Blending
  24033. if (this.enableBlending && this._blendingFactor <= 1.0) {
  24034. if (!this._originalBlendValue) {
  24035. this._originalBlendValue = destination[path];
  24036. }
  24037. if (this._originalBlendValue.prototype) {
  24038. if (this._originalBlendValue.prototype.Lerp) {
  24039. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  24040. }
  24041. else {
  24042. destination[path] = currentValue;
  24043. }
  24044. }
  24045. else {
  24046. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  24047. }
  24048. this._blendingFactor += this.blendingSpeed;
  24049. }
  24050. else {
  24051. destination[path] = currentValue;
  24052. }
  24053. if (this._target.markAsDirty) {
  24054. this._target.markAsDirty(this.targetProperty);
  24055. }
  24056. };
  24057. Animation.prototype.goToFrame = function (frame) {
  24058. if (frame < this._keys[0].frame) {
  24059. frame = this._keys[0].frame;
  24060. }
  24061. else if (frame > this._keys[this._keys.length - 1].frame) {
  24062. frame = this._keys[this._keys.length - 1].frame;
  24063. }
  24064. var currentValue = this._interpolate(frame, 0, this.loopMode);
  24065. this.setValue(currentValue);
  24066. };
  24067. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  24068. if (blend === void 0) { blend = false; }
  24069. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  24070. this._stopped = true;
  24071. return false;
  24072. }
  24073. var returnValue = true;
  24074. // Adding a start key at frame 0 if missing
  24075. if (this._keys[0].frame !== 0) {
  24076. var newKey = { frame: 0, value: this._keys[0].value };
  24077. this._keys.splice(0, 0, newKey);
  24078. }
  24079. // Check limits
  24080. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  24081. from = this._keys[0].frame;
  24082. }
  24083. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  24084. to = this._keys[this._keys.length - 1].frame;
  24085. }
  24086. // Compute ratio
  24087. var range = to - from;
  24088. var offsetValue;
  24089. // ratio represents the frame delta between from and to
  24090. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  24091. var highLimitValue = 0;
  24092. if (ratio > range && !loop) {
  24093. returnValue = false;
  24094. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  24095. }
  24096. else {
  24097. // Get max value if required
  24098. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  24099. var keyOffset = to.toString() + from.toString();
  24100. if (!this._offsetsCache[keyOffset]) {
  24101. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24102. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24103. switch (this.dataType) {
  24104. // Float
  24105. case Animation.ANIMATIONTYPE_FLOAT:
  24106. this._offsetsCache[keyOffset] = toValue - fromValue;
  24107. break;
  24108. // Quaternion
  24109. case Animation.ANIMATIONTYPE_QUATERNION:
  24110. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24111. break;
  24112. // Vector3
  24113. case Animation.ANIMATIONTYPE_VECTOR3:
  24114. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24115. // Vector2
  24116. case Animation.ANIMATIONTYPE_VECTOR2:
  24117. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24118. // Color3
  24119. case Animation.ANIMATIONTYPE_COLOR3:
  24120. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24121. default:
  24122. break;
  24123. }
  24124. this._highLimitsCache[keyOffset] = toValue;
  24125. }
  24126. highLimitValue = this._highLimitsCache[keyOffset];
  24127. offsetValue = this._offsetsCache[keyOffset];
  24128. }
  24129. }
  24130. if (offsetValue === undefined) {
  24131. switch (this.dataType) {
  24132. // Float
  24133. case Animation.ANIMATIONTYPE_FLOAT:
  24134. offsetValue = 0;
  24135. break;
  24136. // Quaternion
  24137. case Animation.ANIMATIONTYPE_QUATERNION:
  24138. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  24139. break;
  24140. // Vector3
  24141. case Animation.ANIMATIONTYPE_VECTOR3:
  24142. offsetValue = BABYLON.Vector3.Zero();
  24143. break;
  24144. // Vector2
  24145. case Animation.ANIMATIONTYPE_VECTOR2:
  24146. offsetValue = BABYLON.Vector2.Zero();
  24147. break;
  24148. // Color3
  24149. case Animation.ANIMATIONTYPE_COLOR3:
  24150. offsetValue = BABYLON.Color3.Black();
  24151. }
  24152. }
  24153. // Compute value
  24154. var repeatCount = (ratio / range) >> 0;
  24155. var currentFrame = returnValue ? from + ratio % range : to;
  24156. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  24157. // Set value
  24158. this.setValue(currentValue);
  24159. // Check events
  24160. for (var index = 0; index < this._events.length; index++) {
  24161. if (currentFrame >= this._events[index].frame) {
  24162. var event = this._events[index];
  24163. if (!event.isDone) {
  24164. // If event should be done only once, remove it.
  24165. if (event.onlyOnce) {
  24166. this._events.splice(index, 1);
  24167. index--;
  24168. }
  24169. event.isDone = true;
  24170. event.action();
  24171. } // Don't do anything if the event has already be done.
  24172. }
  24173. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  24174. // reset event, the animation is looping
  24175. this._events[index].isDone = false;
  24176. }
  24177. }
  24178. if (!returnValue) {
  24179. this._stopped = true;
  24180. }
  24181. return returnValue;
  24182. };
  24183. Animation.prototype.serialize = function () {
  24184. var serializationObject = {};
  24185. serializationObject.name = this.name;
  24186. serializationObject.property = this.targetProperty;
  24187. serializationObject.framePerSecond = this.framePerSecond;
  24188. serializationObject.dataType = this.dataType;
  24189. serializationObject.loopBehavior = this.loopMode;
  24190. var dataType = this.dataType;
  24191. serializationObject.keys = [];
  24192. var keys = this.getKeys();
  24193. for (var index = 0; index < keys.length; index++) {
  24194. var animationKey = keys[index];
  24195. var key = {};
  24196. key.frame = animationKey.frame;
  24197. switch (dataType) {
  24198. case Animation.ANIMATIONTYPE_FLOAT:
  24199. key.values = [animationKey.value];
  24200. break;
  24201. case Animation.ANIMATIONTYPE_QUATERNION:
  24202. case Animation.ANIMATIONTYPE_MATRIX:
  24203. case Animation.ANIMATIONTYPE_VECTOR3:
  24204. case Animation.ANIMATIONTYPE_COLOR3:
  24205. key.values = animationKey.value.asArray();
  24206. break;
  24207. }
  24208. serializationObject.keys.push(key);
  24209. }
  24210. serializationObject.ranges = [];
  24211. for (var name in this._ranges) {
  24212. var range = {};
  24213. range.name = name;
  24214. range.from = this._ranges[name].from;
  24215. range.to = this._ranges[name].to;
  24216. serializationObject.ranges.push(range);
  24217. }
  24218. return serializationObject;
  24219. };
  24220. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  24221. get: function () {
  24222. return Animation._ANIMATIONTYPE_FLOAT;
  24223. },
  24224. enumerable: true,
  24225. configurable: true
  24226. });
  24227. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  24228. get: function () {
  24229. return Animation._ANIMATIONTYPE_VECTOR3;
  24230. },
  24231. enumerable: true,
  24232. configurable: true
  24233. });
  24234. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  24235. get: function () {
  24236. return Animation._ANIMATIONTYPE_VECTOR2;
  24237. },
  24238. enumerable: true,
  24239. configurable: true
  24240. });
  24241. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  24242. get: function () {
  24243. return Animation._ANIMATIONTYPE_QUATERNION;
  24244. },
  24245. enumerable: true,
  24246. configurable: true
  24247. });
  24248. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  24249. get: function () {
  24250. return Animation._ANIMATIONTYPE_MATRIX;
  24251. },
  24252. enumerable: true,
  24253. configurable: true
  24254. });
  24255. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  24256. get: function () {
  24257. return Animation._ANIMATIONTYPE_COLOR3;
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  24263. get: function () {
  24264. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  24265. },
  24266. enumerable: true,
  24267. configurable: true
  24268. });
  24269. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  24270. get: function () {
  24271. return Animation._ANIMATIONLOOPMODE_CYCLE;
  24272. },
  24273. enumerable: true,
  24274. configurable: true
  24275. });
  24276. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  24277. get: function () {
  24278. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  24279. },
  24280. enumerable: true,
  24281. configurable: true
  24282. });
  24283. Animation.Parse = function (parsedAnimation) {
  24284. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  24285. var dataType = parsedAnimation.dataType;
  24286. var keys = [];
  24287. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  24288. var key = parsedAnimation.keys[index];
  24289. var data;
  24290. switch (dataType) {
  24291. case Animation.ANIMATIONTYPE_FLOAT:
  24292. data = key.values[0];
  24293. break;
  24294. case Animation.ANIMATIONTYPE_QUATERNION:
  24295. data = BABYLON.Quaternion.FromArray(key.values);
  24296. break;
  24297. case Animation.ANIMATIONTYPE_MATRIX:
  24298. data = BABYLON.Matrix.FromArray(key.values);
  24299. break;
  24300. case Animation.ANIMATIONTYPE_COLOR3:
  24301. data = BABYLON.Color3.FromArray(key.values);
  24302. break;
  24303. case Animation.ANIMATIONTYPE_VECTOR3:
  24304. default:
  24305. data = BABYLON.Vector3.FromArray(key.values);
  24306. break;
  24307. }
  24308. keys.push({
  24309. frame: key.frame,
  24310. value: data
  24311. });
  24312. }
  24313. animation.setKeys(keys);
  24314. if (parsedAnimation.ranges) {
  24315. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  24316. data = parsedAnimation.ranges[index];
  24317. animation.createRange(data.name, data.from, data.to);
  24318. }
  24319. }
  24320. return animation;
  24321. };
  24322. Animation.AppendSerializedAnimations = function (source, destination) {
  24323. if (source.animations) {
  24324. destination.animations = [];
  24325. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24326. var animation = source.animations[animationIndex];
  24327. destination.animations.push(animation.serialize());
  24328. }
  24329. }
  24330. };
  24331. // Statics
  24332. Animation._ANIMATIONTYPE_FLOAT = 0;
  24333. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  24334. Animation._ANIMATIONTYPE_QUATERNION = 2;
  24335. Animation._ANIMATIONTYPE_MATRIX = 3;
  24336. Animation._ANIMATIONTYPE_COLOR3 = 4;
  24337. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  24338. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  24339. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  24340. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  24341. return Animation;
  24342. })();
  24343. BABYLON.Animation = Animation;
  24344. })(BABYLON || (BABYLON = {}));
  24345. var BABYLON;
  24346. (function (BABYLON) {
  24347. var Animatable = (function () {
  24348. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  24349. if (fromFrame === void 0) { fromFrame = 0; }
  24350. if (toFrame === void 0) { toFrame = 100; }
  24351. if (loopAnimation === void 0) { loopAnimation = false; }
  24352. if (speedRatio === void 0) { speedRatio = 1.0; }
  24353. this.target = target;
  24354. this.fromFrame = fromFrame;
  24355. this.toFrame = toFrame;
  24356. this.loopAnimation = loopAnimation;
  24357. this.speedRatio = speedRatio;
  24358. this.onAnimationEnd = onAnimationEnd;
  24359. this._animations = new Array();
  24360. this._paused = false;
  24361. this.animationStarted = false;
  24362. if (animations) {
  24363. this.appendAnimations(target, animations);
  24364. }
  24365. this._scene = scene;
  24366. scene._activeAnimatables.push(this);
  24367. }
  24368. // Methods
  24369. Animatable.prototype.getAnimations = function () {
  24370. return this._animations;
  24371. };
  24372. Animatable.prototype.appendAnimations = function (target, animations) {
  24373. for (var index = 0; index < animations.length; index++) {
  24374. var animation = animations[index];
  24375. animation._target = target;
  24376. this._animations.push(animation);
  24377. }
  24378. };
  24379. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  24380. var animations = this._animations;
  24381. for (var index = 0; index < animations.length; index++) {
  24382. if (animations[index].targetProperty === property) {
  24383. return animations[index];
  24384. }
  24385. }
  24386. return null;
  24387. };
  24388. Animatable.prototype.reset = function () {
  24389. var animations = this._animations;
  24390. for (var index = 0; index < animations.length; index++) {
  24391. animations[index].reset();
  24392. }
  24393. this._localDelayOffset = null;
  24394. this._pausedDelay = null;
  24395. };
  24396. Animatable.prototype.enableBlending = function (blendingSpeed) {
  24397. var animations = this._animations;
  24398. for (var index = 0; index < animations.length; index++) {
  24399. animations[index].enableBlending = true;
  24400. animations[index].blendingSpeed = blendingSpeed;
  24401. }
  24402. };
  24403. Animatable.prototype.disableBlending = function () {
  24404. var animations = this._animations;
  24405. for (var index = 0; index < animations.length; index++) {
  24406. animations[index].enableBlending = false;
  24407. }
  24408. };
  24409. Animatable.prototype.goToFrame = function (frame) {
  24410. var animations = this._animations;
  24411. for (var index = 0; index < animations.length; index++) {
  24412. animations[index].goToFrame(frame);
  24413. }
  24414. };
  24415. Animatable.prototype.pause = function () {
  24416. if (this._paused) {
  24417. return;
  24418. }
  24419. this._paused = true;
  24420. };
  24421. Animatable.prototype.restart = function () {
  24422. this._paused = false;
  24423. };
  24424. Animatable.prototype.stop = function () {
  24425. var index = this._scene._activeAnimatables.indexOf(this);
  24426. if (index > -1) {
  24427. this._scene._activeAnimatables.splice(index, 1);
  24428. var animations = this._animations;
  24429. for (var index = 0; index < animations.length; index++) {
  24430. animations[index].reset();
  24431. }
  24432. if (this.onAnimationEnd) {
  24433. this.onAnimationEnd();
  24434. }
  24435. }
  24436. };
  24437. Animatable.prototype._animate = function (delay) {
  24438. if (this._paused) {
  24439. this.animationStarted = false;
  24440. if (!this._pausedDelay) {
  24441. this._pausedDelay = delay;
  24442. }
  24443. return true;
  24444. }
  24445. if (!this._localDelayOffset) {
  24446. this._localDelayOffset = delay;
  24447. }
  24448. else if (this._pausedDelay) {
  24449. this._localDelayOffset += delay - this._pausedDelay;
  24450. this._pausedDelay = null;
  24451. }
  24452. // Animating
  24453. var running = false;
  24454. var animations = this._animations;
  24455. var index;
  24456. for (index = 0; index < animations.length; index++) {
  24457. var animation = animations[index];
  24458. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  24459. running = running || isRunning;
  24460. }
  24461. this.animationStarted = running;
  24462. if (!running) {
  24463. // Remove from active animatables
  24464. index = this._scene._activeAnimatables.indexOf(this);
  24465. this._scene._activeAnimatables.splice(index, 1);
  24466. }
  24467. if (!running && this.onAnimationEnd) {
  24468. this.onAnimationEnd();
  24469. this.onAnimationEnd = null;
  24470. }
  24471. return running;
  24472. };
  24473. return Animatable;
  24474. })();
  24475. BABYLON.Animatable = Animatable;
  24476. })(BABYLON || (BABYLON = {}));
  24477. var BABYLON;
  24478. (function (BABYLON) {
  24479. var EasingFunction = (function () {
  24480. function EasingFunction() {
  24481. // Properties
  24482. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  24483. }
  24484. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  24485. get: function () {
  24486. return EasingFunction._EASINGMODE_EASEIN;
  24487. },
  24488. enumerable: true,
  24489. configurable: true
  24490. });
  24491. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  24492. get: function () {
  24493. return EasingFunction._EASINGMODE_EASEOUT;
  24494. },
  24495. enumerable: true,
  24496. configurable: true
  24497. });
  24498. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  24499. get: function () {
  24500. return EasingFunction._EASINGMODE_EASEINOUT;
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. EasingFunction.prototype.setEasingMode = function (easingMode) {
  24506. var n = Math.min(Math.max(easingMode, 0), 2);
  24507. this._easingMode = n;
  24508. };
  24509. EasingFunction.prototype.getEasingMode = function () {
  24510. return this._easingMode;
  24511. };
  24512. EasingFunction.prototype.easeInCore = function (gradient) {
  24513. throw new Error('You must implement this method');
  24514. };
  24515. EasingFunction.prototype.ease = function (gradient) {
  24516. switch (this._easingMode) {
  24517. case EasingFunction.EASINGMODE_EASEIN:
  24518. return this.easeInCore(gradient);
  24519. case EasingFunction.EASINGMODE_EASEOUT:
  24520. return (1 - this.easeInCore(1 - gradient));
  24521. }
  24522. if (gradient >= 0.5) {
  24523. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  24524. }
  24525. return (this.easeInCore(gradient * 2) * 0.5);
  24526. };
  24527. //Statics
  24528. EasingFunction._EASINGMODE_EASEIN = 0;
  24529. EasingFunction._EASINGMODE_EASEOUT = 1;
  24530. EasingFunction._EASINGMODE_EASEINOUT = 2;
  24531. return EasingFunction;
  24532. })();
  24533. BABYLON.EasingFunction = EasingFunction;
  24534. var CircleEase = (function (_super) {
  24535. __extends(CircleEase, _super);
  24536. function CircleEase() {
  24537. _super.apply(this, arguments);
  24538. }
  24539. CircleEase.prototype.easeInCore = function (gradient) {
  24540. gradient = Math.max(0, Math.min(1, gradient));
  24541. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  24542. };
  24543. return CircleEase;
  24544. })(EasingFunction);
  24545. BABYLON.CircleEase = CircleEase;
  24546. var BackEase = (function (_super) {
  24547. __extends(BackEase, _super);
  24548. function BackEase(amplitude) {
  24549. if (amplitude === void 0) { amplitude = 1; }
  24550. _super.call(this);
  24551. this.amplitude = amplitude;
  24552. }
  24553. BackEase.prototype.easeInCore = function (gradient) {
  24554. var num = Math.max(0, this.amplitude);
  24555. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  24556. };
  24557. return BackEase;
  24558. })(EasingFunction);
  24559. BABYLON.BackEase = BackEase;
  24560. var BounceEase = (function (_super) {
  24561. __extends(BounceEase, _super);
  24562. function BounceEase(bounces, bounciness) {
  24563. if (bounces === void 0) { bounces = 3; }
  24564. if (bounciness === void 0) { bounciness = 2; }
  24565. _super.call(this);
  24566. this.bounces = bounces;
  24567. this.bounciness = bounciness;
  24568. }
  24569. BounceEase.prototype.easeInCore = function (gradient) {
  24570. var y = Math.max(0.0, this.bounces);
  24571. var bounciness = this.bounciness;
  24572. if (bounciness <= 1.0) {
  24573. bounciness = 1.001;
  24574. }
  24575. var num9 = Math.pow(bounciness, y);
  24576. var num5 = 1.0 - bounciness;
  24577. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  24578. var num15 = gradient * num4;
  24579. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  24580. var num3 = Math.floor(num65);
  24581. var num13 = num3 + 1.0;
  24582. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  24583. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  24584. var num7 = (num8 + num12) * 0.5;
  24585. var num6 = gradient - num7;
  24586. var num2 = num7 - num8;
  24587. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  24588. };
  24589. return BounceEase;
  24590. })(EasingFunction);
  24591. BABYLON.BounceEase = BounceEase;
  24592. var CubicEase = (function (_super) {
  24593. __extends(CubicEase, _super);
  24594. function CubicEase() {
  24595. _super.apply(this, arguments);
  24596. }
  24597. CubicEase.prototype.easeInCore = function (gradient) {
  24598. return (gradient * gradient * gradient);
  24599. };
  24600. return CubicEase;
  24601. })(EasingFunction);
  24602. BABYLON.CubicEase = CubicEase;
  24603. var ElasticEase = (function (_super) {
  24604. __extends(ElasticEase, _super);
  24605. function ElasticEase(oscillations, springiness) {
  24606. if (oscillations === void 0) { oscillations = 3; }
  24607. if (springiness === void 0) { springiness = 3; }
  24608. _super.call(this);
  24609. this.oscillations = oscillations;
  24610. this.springiness = springiness;
  24611. }
  24612. ElasticEase.prototype.easeInCore = function (gradient) {
  24613. var num2;
  24614. var num3 = Math.max(0.0, this.oscillations);
  24615. var num = Math.max(0.0, this.springiness);
  24616. if (num == 0) {
  24617. num2 = gradient;
  24618. }
  24619. else {
  24620. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  24621. }
  24622. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  24623. };
  24624. return ElasticEase;
  24625. })(EasingFunction);
  24626. BABYLON.ElasticEase = ElasticEase;
  24627. var ExponentialEase = (function (_super) {
  24628. __extends(ExponentialEase, _super);
  24629. function ExponentialEase(exponent) {
  24630. if (exponent === void 0) { exponent = 2; }
  24631. _super.call(this);
  24632. this.exponent = exponent;
  24633. }
  24634. ExponentialEase.prototype.easeInCore = function (gradient) {
  24635. if (this.exponent <= 0) {
  24636. return gradient;
  24637. }
  24638. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  24639. };
  24640. return ExponentialEase;
  24641. })(EasingFunction);
  24642. BABYLON.ExponentialEase = ExponentialEase;
  24643. var PowerEase = (function (_super) {
  24644. __extends(PowerEase, _super);
  24645. function PowerEase(power) {
  24646. if (power === void 0) { power = 2; }
  24647. _super.call(this);
  24648. this.power = power;
  24649. }
  24650. PowerEase.prototype.easeInCore = function (gradient) {
  24651. var y = Math.max(0.0, this.power);
  24652. return Math.pow(gradient, y);
  24653. };
  24654. return PowerEase;
  24655. })(EasingFunction);
  24656. BABYLON.PowerEase = PowerEase;
  24657. var QuadraticEase = (function (_super) {
  24658. __extends(QuadraticEase, _super);
  24659. function QuadraticEase() {
  24660. _super.apply(this, arguments);
  24661. }
  24662. QuadraticEase.prototype.easeInCore = function (gradient) {
  24663. return (gradient * gradient);
  24664. };
  24665. return QuadraticEase;
  24666. })(EasingFunction);
  24667. BABYLON.QuadraticEase = QuadraticEase;
  24668. var QuarticEase = (function (_super) {
  24669. __extends(QuarticEase, _super);
  24670. function QuarticEase() {
  24671. _super.apply(this, arguments);
  24672. }
  24673. QuarticEase.prototype.easeInCore = function (gradient) {
  24674. return (gradient * gradient * gradient * gradient);
  24675. };
  24676. return QuarticEase;
  24677. })(EasingFunction);
  24678. BABYLON.QuarticEase = QuarticEase;
  24679. var QuinticEase = (function (_super) {
  24680. __extends(QuinticEase, _super);
  24681. function QuinticEase() {
  24682. _super.apply(this, arguments);
  24683. }
  24684. QuinticEase.prototype.easeInCore = function (gradient) {
  24685. return (gradient * gradient * gradient * gradient * gradient);
  24686. };
  24687. return QuinticEase;
  24688. })(EasingFunction);
  24689. BABYLON.QuinticEase = QuinticEase;
  24690. var SineEase = (function (_super) {
  24691. __extends(SineEase, _super);
  24692. function SineEase() {
  24693. _super.apply(this, arguments);
  24694. }
  24695. SineEase.prototype.easeInCore = function (gradient) {
  24696. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  24697. };
  24698. return SineEase;
  24699. })(EasingFunction);
  24700. BABYLON.SineEase = SineEase;
  24701. var BezierCurveEase = (function (_super) {
  24702. __extends(BezierCurveEase, _super);
  24703. function BezierCurveEase(x1, y1, x2, y2) {
  24704. if (x1 === void 0) { x1 = 0; }
  24705. if (y1 === void 0) { y1 = 0; }
  24706. if (x2 === void 0) { x2 = 1; }
  24707. if (y2 === void 0) { y2 = 1; }
  24708. _super.call(this);
  24709. this.x1 = x1;
  24710. this.y1 = y1;
  24711. this.x2 = x2;
  24712. this.y2 = y2;
  24713. }
  24714. BezierCurveEase.prototype.easeInCore = function (gradient) {
  24715. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  24716. };
  24717. return BezierCurveEase;
  24718. })(EasingFunction);
  24719. BABYLON.BezierCurveEase = BezierCurveEase;
  24720. })(BABYLON || (BABYLON = {}));
  24721. var BABYLON;
  24722. (function (BABYLON) {
  24723. var Bone = (function (_super) {
  24724. __extends(Bone, _super);
  24725. function Bone(name, skeleton, parentBone, matrix, restPose) {
  24726. _super.call(this, name, skeleton.getScene());
  24727. this.name = name;
  24728. this.children = new Array();
  24729. this.animations = new Array();
  24730. this._worldTransform = new BABYLON.Matrix();
  24731. this._absoluteTransform = new BABYLON.Matrix();
  24732. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  24733. this._skeleton = skeleton;
  24734. this._matrix = matrix;
  24735. this._baseMatrix = matrix;
  24736. this._restPose = restPose ? restPose : matrix.clone();
  24737. skeleton.bones.push(this);
  24738. if (parentBone) {
  24739. this._parent = parentBone;
  24740. parentBone.children.push(this);
  24741. }
  24742. else {
  24743. this._parent = null;
  24744. }
  24745. this._updateDifferenceMatrix();
  24746. }
  24747. // Members
  24748. Bone.prototype.getParent = function () {
  24749. return this._parent;
  24750. };
  24751. Bone.prototype.getLocalMatrix = function () {
  24752. return this._matrix;
  24753. };
  24754. Bone.prototype.getBaseMatrix = function () {
  24755. return this._baseMatrix;
  24756. };
  24757. Bone.prototype.getRestPose = function () {
  24758. return this._restPose;
  24759. };
  24760. Bone.prototype.returnToRest = function () {
  24761. this.updateMatrix(this._restPose.clone());
  24762. };
  24763. Bone.prototype.getWorldMatrix = function () {
  24764. return this._worldTransform;
  24765. };
  24766. Bone.prototype.getInvertedAbsoluteTransform = function () {
  24767. return this._invertedAbsoluteTransform;
  24768. };
  24769. Bone.prototype.getAbsoluteTransform = function () {
  24770. return this._absoluteTransform;
  24771. };
  24772. // Methods
  24773. Bone.prototype.updateMatrix = function (matrix) {
  24774. this._baseMatrix = matrix.clone();
  24775. this._matrix = matrix.clone();
  24776. this._skeleton._markAsDirty();
  24777. this._updateDifferenceMatrix();
  24778. };
  24779. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  24780. if (!rootMatrix) {
  24781. rootMatrix = this._baseMatrix;
  24782. }
  24783. if (this._parent) {
  24784. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  24785. }
  24786. else {
  24787. this._absoluteTransform.copyFrom(rootMatrix);
  24788. }
  24789. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  24790. for (var index = 0; index < this.children.length; index++) {
  24791. this.children[index]._updateDifferenceMatrix();
  24792. }
  24793. };
  24794. Bone.prototype.markAsDirty = function () {
  24795. this._currentRenderId++;
  24796. this._skeleton._markAsDirty();
  24797. };
  24798. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  24799. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  24800. // all animation may be coming from a library skeleton, so may need to create animation
  24801. if (this.animations.length === 0) {
  24802. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  24803. this.animations[0].setKeys([]);
  24804. }
  24805. // get animation info / verify there is such a range from the source bone
  24806. var sourceRange = source.animations[0].getRange(rangeName);
  24807. if (!sourceRange) {
  24808. return false;
  24809. }
  24810. var from = sourceRange.from;
  24811. var to = sourceRange.to;
  24812. var sourceKeys = source.animations[0].getKeys();
  24813. // rescaling prep
  24814. var sourceBoneLength = source.length;
  24815. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  24816. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  24817. var destKeys = this.animations[0].getKeys();
  24818. // loop vars declaration / initialization
  24819. var orig;
  24820. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  24821. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  24822. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  24823. var mat;
  24824. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  24825. orig = sourceKeys[key];
  24826. if (orig.frame >= from && orig.frame <= to) {
  24827. if (scalingReqd) {
  24828. orig.value.decompose(origScale, origRotation, origTranslation);
  24829. origTranslation.scaleInPlace(ratio);
  24830. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  24831. }
  24832. else {
  24833. mat = orig.value;
  24834. }
  24835. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  24836. }
  24837. }
  24838. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  24839. return true;
  24840. };
  24841. return Bone;
  24842. })(BABYLON.Node);
  24843. BABYLON.Bone = Bone;
  24844. })(BABYLON || (BABYLON = {}));
  24845. var BABYLON;
  24846. (function (BABYLON) {
  24847. var Skeleton = (function () {
  24848. function Skeleton(name, id, scene) {
  24849. this.name = name;
  24850. this.id = id;
  24851. this.bones = new Array();
  24852. this.needInitialSkinMatrix = false;
  24853. this._isDirty = true;
  24854. this._meshesWithPoseMatrix = new Array();
  24855. this._identity = BABYLON.Matrix.Identity();
  24856. this._ranges = {};
  24857. this.bones = [];
  24858. this._scene = scene;
  24859. scene.skeletons.push(this);
  24860. //make sure it will recalculate the matrix next time prepare is called.
  24861. this._isDirty = true;
  24862. }
  24863. // Members
  24864. Skeleton.prototype.getTransformMatrices = function (mesh) {
  24865. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  24866. return mesh._bonesTransformMatrices;
  24867. }
  24868. return this._transformMatrices;
  24869. };
  24870. Skeleton.prototype.getScene = function () {
  24871. return this._scene;
  24872. };
  24873. // Methods
  24874. /**
  24875. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24876. */
  24877. Skeleton.prototype.toString = function (fullDetails) {
  24878. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  24879. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  24880. if (fullDetails) {
  24881. ret += ", Ranges: {";
  24882. var first = true;
  24883. for (var name in this._ranges) {
  24884. if (!first) {
  24885. ret + ", ";
  24886. first = false;
  24887. }
  24888. ret += name;
  24889. }
  24890. ret += "}";
  24891. }
  24892. return ret;
  24893. };
  24894. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  24895. // check name not already in use
  24896. if (!this._ranges[name]) {
  24897. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  24898. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24899. if (this.bones[i].animations[0]) {
  24900. this.bones[i].animations[0].createRange(name, from, to);
  24901. }
  24902. }
  24903. }
  24904. };
  24905. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  24906. if (deleteFrames === void 0) { deleteFrames = true; }
  24907. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24908. if (this.bones[i].animations[0]) {
  24909. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  24910. }
  24911. }
  24912. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  24913. };
  24914. Skeleton.prototype.getAnimationRange = function (name) {
  24915. return this._ranges[name];
  24916. };
  24917. /**
  24918. * Returns as an Array, all AnimationRanges defined on this skeleton
  24919. */
  24920. Skeleton.prototype.getAnimationRanges = function () {
  24921. var animationRanges = [];
  24922. var name;
  24923. var i = 0;
  24924. for (name in this._ranges) {
  24925. animationRanges[i] = this._ranges[name];
  24926. i++;
  24927. }
  24928. return animationRanges;
  24929. };
  24930. /**
  24931. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  24932. */
  24933. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  24934. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  24935. if (this._ranges[name] || !source.getAnimationRange(name)) {
  24936. return false;
  24937. }
  24938. var ret = true;
  24939. var frameOffset = this._getHighestAnimationFrame() + 1;
  24940. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  24941. var boneDict = {};
  24942. var sourceBones = source.bones;
  24943. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  24944. boneDict[sourceBones[i].name] = sourceBones[i];
  24945. }
  24946. if (this.bones.length !== sourceBones.length) {
  24947. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  24948. ret = false;
  24949. }
  24950. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24951. var boneName = this.bones[i].name;
  24952. var sourceBone = boneDict[boneName];
  24953. if (sourceBone) {
  24954. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  24955. }
  24956. else {
  24957. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  24958. ret = false;
  24959. }
  24960. }
  24961. // do not call createAnimationRange(), since it also is done to bones, which was already done
  24962. var range = source.getAnimationRange(name);
  24963. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  24964. return ret;
  24965. };
  24966. Skeleton.prototype.returnToRest = function () {
  24967. for (var index = 0; index < this.bones.length; index++) {
  24968. this.bones[index].returnToRest();
  24969. }
  24970. };
  24971. Skeleton.prototype._getHighestAnimationFrame = function () {
  24972. var ret = 0;
  24973. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24974. if (this.bones[i].animations[0]) {
  24975. var highest = this.bones[i].animations[0].getHighestFrame();
  24976. if (ret < highest) {
  24977. ret = highest;
  24978. }
  24979. }
  24980. }
  24981. return ret;
  24982. };
  24983. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  24984. var range = this.getAnimationRange(name);
  24985. if (!range) {
  24986. return null;
  24987. }
  24988. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  24989. };
  24990. Skeleton.prototype._markAsDirty = function () {
  24991. this._isDirty = true;
  24992. };
  24993. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  24994. this._meshesWithPoseMatrix.push(mesh);
  24995. };
  24996. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  24997. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  24998. if (index > -1) {
  24999. this._meshesWithPoseMatrix.splice(index, 1);
  25000. }
  25001. };
  25002. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  25003. for (var index = 0; index < this.bones.length; index++) {
  25004. var bone = this.bones[index];
  25005. var parentBone = bone.getParent();
  25006. if (parentBone) {
  25007. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  25008. }
  25009. else {
  25010. if (initialSkinMatrix) {
  25011. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  25012. }
  25013. else {
  25014. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  25015. }
  25016. }
  25017. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  25018. }
  25019. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  25020. };
  25021. Skeleton.prototype.prepare = function () {
  25022. if (!this._isDirty) {
  25023. return;
  25024. }
  25025. if (this.needInitialSkinMatrix) {
  25026. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  25027. var mesh = this._meshesWithPoseMatrix[index];
  25028. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  25029. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  25030. }
  25031. var poseMatrix = mesh.getPoseMatrix();
  25032. // Prepare bones
  25033. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  25034. var bone = this.bones[boneIndex];
  25035. if (!bone.getParent()) {
  25036. var matrix = bone.getBaseMatrix();
  25037. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  25038. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  25039. }
  25040. }
  25041. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  25042. }
  25043. }
  25044. else {
  25045. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  25046. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  25047. }
  25048. this._computeTransformMatrices(this._transformMatrices, null);
  25049. }
  25050. this._isDirty = false;
  25051. this._scene._activeBones += this.bones.length;
  25052. };
  25053. Skeleton.prototype.getAnimatables = function () {
  25054. if (!this._animatables || this._animatables.length !== this.bones.length) {
  25055. this._animatables = [];
  25056. for (var index = 0; index < this.bones.length; index++) {
  25057. this._animatables.push(this.bones[index]);
  25058. }
  25059. }
  25060. return this._animatables;
  25061. };
  25062. Skeleton.prototype.clone = function (name, id) {
  25063. var result = new Skeleton(name, id || name, this._scene);
  25064. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25065. for (var index = 0; index < this.bones.length; index++) {
  25066. var source = this.bones[index];
  25067. var parentBone = null;
  25068. if (source.getParent()) {
  25069. var parentIndex = this.bones.indexOf(source.getParent());
  25070. parentBone = result.bones[parentIndex];
  25071. }
  25072. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  25073. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  25074. }
  25075. if (this._ranges) {
  25076. result._ranges = {};
  25077. for (var rangeName in this._ranges) {
  25078. result._ranges[rangeName] = this._ranges[rangeName].clone();
  25079. }
  25080. }
  25081. this._isDirty = true;
  25082. return result;
  25083. };
  25084. Skeleton.prototype.dispose = function () {
  25085. this._meshesWithPoseMatrix = [];
  25086. // Animations
  25087. this.getScene().stopAnimation(this);
  25088. // Remove from scene
  25089. this.getScene().removeSkeleton(this);
  25090. };
  25091. Skeleton.prototype.serialize = function () {
  25092. var serializationObject = {};
  25093. serializationObject.name = this.name;
  25094. serializationObject.id = this.id;
  25095. serializationObject.bones = [];
  25096. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25097. for (var index = 0; index < this.bones.length; index++) {
  25098. var bone = this.bones[index];
  25099. var serializedBone = {
  25100. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  25101. name: bone.name,
  25102. matrix: bone.getLocalMatrix().toArray(),
  25103. rest: bone.getRestPose().toArray()
  25104. };
  25105. serializationObject.bones.push(serializedBone);
  25106. if (bone.length) {
  25107. serializedBone.length = bone.length;
  25108. }
  25109. if (bone.animations && bone.animations.length > 0) {
  25110. serializedBone.animation = bone.animations[0].serialize();
  25111. }
  25112. serializationObject.ranges = [];
  25113. for (var name in this._ranges) {
  25114. var range = {};
  25115. range.name = name;
  25116. range.from = this._ranges[name].from;
  25117. range.to = this._ranges[name].to;
  25118. serializationObject.ranges.push(range);
  25119. }
  25120. }
  25121. return serializationObject;
  25122. };
  25123. Skeleton.Parse = function (parsedSkeleton, scene) {
  25124. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  25125. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  25126. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  25127. var parsedBone = parsedSkeleton.bones[index];
  25128. var parentBone = null;
  25129. if (parsedBone.parentBoneIndex > -1) {
  25130. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  25131. }
  25132. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  25133. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  25134. if (parsedBone.length) {
  25135. bone.length = parsedBone.length;
  25136. }
  25137. if (parsedBone.animation) {
  25138. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  25139. }
  25140. }
  25141. // placed after bones, so createAnimationRange can cascade down
  25142. if (parsedSkeleton.ranges) {
  25143. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  25144. var data = parsedSkeleton.ranges[index];
  25145. skeleton.createAnimationRange(data.name, data.from, data.to);
  25146. }
  25147. }
  25148. return skeleton;
  25149. };
  25150. return Skeleton;
  25151. })();
  25152. BABYLON.Skeleton = Skeleton;
  25153. })(BABYLON || (BABYLON = {}));
  25154. var BABYLON;
  25155. (function (BABYLON) {
  25156. var PostProcess = (function () {
  25157. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  25158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  25159. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25160. this.name = name;
  25161. this.width = -1;
  25162. this.height = -1;
  25163. this._reusable = false;
  25164. this._textures = new BABYLON.SmartArray(2);
  25165. this._currentRenderTextureInd = 0;
  25166. if (camera != null) {
  25167. this._camera = camera;
  25168. this._scene = camera.getScene();
  25169. camera.attachPostProcess(this);
  25170. this._engine = this._scene.getEngine();
  25171. }
  25172. else {
  25173. this._engine = engine;
  25174. }
  25175. this._renderRatio = ratio;
  25176. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  25177. this._reusable = reusable || false;
  25178. this._textureType = textureType;
  25179. this._samplers = samplers || [];
  25180. this._samplers.push("textureSampler");
  25181. this._fragmentUrl = fragmentUrl;
  25182. this._parameters = parameters || [];
  25183. this.updateEffect(defines);
  25184. }
  25185. PostProcess.prototype.updateEffect = function (defines) {
  25186. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  25187. };
  25188. PostProcess.prototype.isReusable = function () {
  25189. return this._reusable;
  25190. };
  25191. PostProcess.prototype.activate = function (camera, sourceTexture) {
  25192. camera = camera || this._camera;
  25193. var scene = camera.getScene();
  25194. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  25195. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  25196. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  25197. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  25198. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  25199. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  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. this.width = desiredWidth;
  25207. this.height = desiredHeight;
  25208. 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 }));
  25209. if (this._reusable) {
  25210. 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 }));
  25211. }
  25212. if (this.onSizeChanged) {
  25213. this.onSizeChanged();
  25214. }
  25215. }
  25216. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  25217. if (this.onActivate) {
  25218. this.onActivate(camera);
  25219. }
  25220. // Clear
  25221. if (this.clearColor) {
  25222. this._engine.clear(this.clearColor, true, true);
  25223. }
  25224. else {
  25225. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  25226. }
  25227. if (this._reusable) {
  25228. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  25229. }
  25230. };
  25231. Object.defineProperty(PostProcess.prototype, "isSupported", {
  25232. get: function () {
  25233. return this._effect.isSupported;
  25234. },
  25235. enumerable: true,
  25236. configurable: true
  25237. });
  25238. PostProcess.prototype.apply = function () {
  25239. // Check
  25240. if (!this._effect.isReady())
  25241. return null;
  25242. // States
  25243. this._engine.enableEffect(this._effect);
  25244. this._engine.setState(false);
  25245. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25246. this._engine.setDepthBuffer(false);
  25247. this._engine.setDepthWrite(false);
  25248. // Texture
  25249. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  25250. // Parameters
  25251. if (this.onApply) {
  25252. this.onApply(this._effect);
  25253. }
  25254. return this._effect;
  25255. };
  25256. PostProcess.prototype.dispose = function (camera) {
  25257. camera = camera || this._camera;
  25258. if (this._textures.length > 0) {
  25259. for (var i = 0; i < this._textures.length; i++) {
  25260. this._engine._releaseTexture(this._textures.data[i]);
  25261. }
  25262. this._textures.reset();
  25263. }
  25264. if (!camera) {
  25265. return;
  25266. }
  25267. camera.detachPostProcess(this);
  25268. var index = camera._postProcesses.indexOf(this);
  25269. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  25270. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  25271. }
  25272. };
  25273. return PostProcess;
  25274. })();
  25275. BABYLON.PostProcess = PostProcess;
  25276. })(BABYLON || (BABYLON = {}));
  25277. var BABYLON;
  25278. (function (BABYLON) {
  25279. var PostProcessManager = (function () {
  25280. function PostProcessManager(scene) {
  25281. this._vertexDeclaration = [2];
  25282. this._vertexStrideSize = 2 * 4;
  25283. this._scene = scene;
  25284. }
  25285. PostProcessManager.prototype._prepareBuffers = function () {
  25286. if (this._vertexBuffer) {
  25287. return;
  25288. }
  25289. // VBO
  25290. var vertices = [];
  25291. vertices.push(1, 1);
  25292. vertices.push(-1, 1);
  25293. vertices.push(-1, -1);
  25294. vertices.push(1, -1);
  25295. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  25296. // Indices
  25297. var indices = [];
  25298. indices.push(0);
  25299. indices.push(1);
  25300. indices.push(2);
  25301. indices.push(0);
  25302. indices.push(2);
  25303. indices.push(3);
  25304. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  25305. };
  25306. // Methods
  25307. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  25308. var postProcesses = this._scene.activeCamera._postProcesses;
  25309. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  25310. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  25311. return false;
  25312. }
  25313. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  25314. return true;
  25315. };
  25316. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  25317. var engine = this._scene.getEngine();
  25318. for (var index = 0; index < postProcesses.length; index++) {
  25319. if (index < postProcesses.length - 1) {
  25320. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  25321. }
  25322. else {
  25323. if (targetTexture) {
  25324. engine.bindFramebuffer(targetTexture);
  25325. }
  25326. else {
  25327. engine.restoreDefaultFramebuffer();
  25328. }
  25329. }
  25330. var pp = postProcesses[index];
  25331. var effect = pp.apply();
  25332. if (effect) {
  25333. if (pp.onBeforeRender) {
  25334. pp.onBeforeRender(effect);
  25335. }
  25336. // VBOs
  25337. this._prepareBuffers();
  25338. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25339. // Draw order
  25340. engine.draw(true, 0, 6);
  25341. if (pp.onAfterRender) {
  25342. pp.onAfterRender(effect);
  25343. }
  25344. }
  25345. }
  25346. // Restore depth buffer
  25347. engine.setDepthBuffer(true);
  25348. engine.setDepthWrite(true);
  25349. };
  25350. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  25351. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  25352. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  25353. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  25354. return;
  25355. }
  25356. var engine = this._scene.getEngine();
  25357. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  25358. if (index < postProcessesTakenIndices.length - 1) {
  25359. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  25360. }
  25361. else {
  25362. if (targetTexture) {
  25363. engine.bindFramebuffer(targetTexture, faceIndex);
  25364. }
  25365. else {
  25366. engine.restoreDefaultFramebuffer();
  25367. }
  25368. }
  25369. if (doNotPresent) {
  25370. break;
  25371. }
  25372. var pp = postProcesses[postProcessesTakenIndices[index]];
  25373. var effect = pp.apply();
  25374. if (effect) {
  25375. if (pp.onBeforeRender) {
  25376. pp.onBeforeRender(effect);
  25377. }
  25378. // VBOs
  25379. this._prepareBuffers();
  25380. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25381. // Draw order
  25382. engine.draw(true, 0, 6);
  25383. if (pp.onAfterRender) {
  25384. pp.onAfterRender(effect);
  25385. }
  25386. }
  25387. }
  25388. // Restore depth buffer
  25389. engine.setDepthBuffer(true);
  25390. engine.setDepthWrite(true);
  25391. };
  25392. PostProcessManager.prototype.dispose = function () {
  25393. if (this._vertexBuffer) {
  25394. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25395. this._vertexBuffer = null;
  25396. }
  25397. if (this._indexBuffer) {
  25398. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25399. this._indexBuffer = null;
  25400. }
  25401. };
  25402. return PostProcessManager;
  25403. })();
  25404. BABYLON.PostProcessManager = PostProcessManager;
  25405. })(BABYLON || (BABYLON = {}));
  25406. var BABYLON;
  25407. (function (BABYLON) {
  25408. var PassPostProcess = (function (_super) {
  25409. __extends(PassPostProcess, _super);
  25410. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25411. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  25412. }
  25413. return PassPostProcess;
  25414. })(BABYLON.PostProcess);
  25415. BABYLON.PassPostProcess = PassPostProcess;
  25416. })(BABYLON || (BABYLON = {}));
  25417. var BABYLON;
  25418. (function (BABYLON) {
  25419. /**
  25420. * This is a holder class for the physics joint created by the physics plugin.
  25421. * It holds a set of functions to control the underlying joint.
  25422. */
  25423. var PhysicsJoint = (function () {
  25424. function PhysicsJoint(type, jointData) {
  25425. this.type = type;
  25426. this.jointData = jointData;
  25427. jointData.nativeParams = jointData.nativeParams || {};
  25428. }
  25429. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  25430. get: function () {
  25431. return this._physicsJoint;
  25432. },
  25433. set: function (newJoint) {
  25434. if (this._physicsJoint) {
  25435. }
  25436. this._physicsJoint = newJoint;
  25437. },
  25438. enumerable: true,
  25439. configurable: true
  25440. });
  25441. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  25442. set: function (physicsPlugin) {
  25443. this._physicsPlugin = physicsPlugin;
  25444. },
  25445. enumerable: true,
  25446. configurable: true
  25447. });
  25448. /**
  25449. * Execute a function that is physics-plugin specific.
  25450. * @param {Function} func the function that will be executed.
  25451. * It accepts two parameters: the physics world and the physics joint.
  25452. */
  25453. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  25454. func(this._physicsPlugin.world, this._physicsJoint);
  25455. };
  25456. //TODO check if the native joints are the same
  25457. //Joint Types
  25458. PhysicsJoint.DistanceJoint = 0;
  25459. PhysicsJoint.HingeJoint = 1;
  25460. PhysicsJoint.BallAndSocketJoint = 2;
  25461. PhysicsJoint.WheelJoint = 3;
  25462. PhysicsJoint.SliderJoint = 4;
  25463. //OIMO
  25464. PhysicsJoint.PrismaticJoint = 5;
  25465. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  25466. PhysicsJoint.UniversalJoint = 6;
  25467. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  25468. //Cannon
  25469. //Similar to a Ball-Joint. Different in params
  25470. //TODO check!!
  25471. PhysicsJoint.PointToPointJoint = 8;
  25472. //Cannon only at the moment
  25473. PhysicsJoint.SpringJoint = 9;
  25474. return PhysicsJoint;
  25475. })();
  25476. BABYLON.PhysicsJoint = PhysicsJoint;
  25477. /**
  25478. * A class representing a physics distance joint.
  25479. */
  25480. var DistanceJoint = (function (_super) {
  25481. __extends(DistanceJoint, _super);
  25482. function DistanceJoint(jointData) {
  25483. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  25484. }
  25485. /**
  25486. * Update the predefined distance.
  25487. */
  25488. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  25489. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  25490. };
  25491. return DistanceJoint;
  25492. })(PhysicsJoint);
  25493. BABYLON.DistanceJoint = DistanceJoint;
  25494. /**
  25495. * This class represents a single hinge physics joint
  25496. */
  25497. var HingeJoint = (function (_super) {
  25498. __extends(HingeJoint, _super);
  25499. function HingeJoint(jointData) {
  25500. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  25501. }
  25502. /**
  25503. * Set the motor values.
  25504. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25505. * @param {number} force the force to apply
  25506. * @param {number} maxForce max force for this motor.
  25507. */
  25508. HingeJoint.prototype.setMotor = function (force, maxForce) {
  25509. this._physicsPlugin.setMotor(this, force, maxForce);
  25510. };
  25511. /**
  25512. * Set the motor's limits.
  25513. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25514. */
  25515. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  25516. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  25517. };
  25518. return HingeJoint;
  25519. })(PhysicsJoint);
  25520. BABYLON.HingeJoint = HingeJoint;
  25521. /**
  25522. * This class represents a dual hinge physics joint (same as wheel joint)
  25523. */
  25524. var Hinge2Joint = (function (_super) {
  25525. __extends(Hinge2Joint, _super);
  25526. function Hinge2Joint(jointData) {
  25527. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  25528. }
  25529. /**
  25530. * Set the motor values.
  25531. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25532. * @param {number} force the force to apply
  25533. * @param {number} maxForce max force for this motor.
  25534. * @param {motorIndex} the motor's index, 0 or 1.
  25535. */
  25536. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  25537. if (motorIndex === void 0) { motorIndex = 0; }
  25538. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  25539. };
  25540. /**
  25541. * Set the motor limits.
  25542. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25543. * @param {number} upperLimit the upper limit
  25544. * @param {number} lowerLimit lower limit
  25545. * @param {motorIndex} the motor's index, 0 or 1.
  25546. */
  25547. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  25548. if (motorIndex === void 0) { motorIndex = 0; }
  25549. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  25550. };
  25551. return Hinge2Joint;
  25552. })(PhysicsJoint);
  25553. BABYLON.Hinge2Joint = Hinge2Joint;
  25554. })(BABYLON || (BABYLON = {}));
  25555. var BABYLON;
  25556. (function (BABYLON) {
  25557. var PhysicsImpostor = (function () {
  25558. function PhysicsImpostor(_mesh, type, _options) {
  25559. var _this = this;
  25560. if (_options === void 0) { _options = { mass: 0 }; }
  25561. this._mesh = _mesh;
  25562. this.type = type;
  25563. this._options = _options;
  25564. this._bodyUpdateRequired = false;
  25565. this._onBeforePhysicsStepCallbacks = new Array();
  25566. this._onAfterPhysicsStepCallbacks = new Array();
  25567. this._onPhysicsCollideCallbacks = [];
  25568. this._deltaPosition = BABYLON.Vector3.Zero();
  25569. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  25570. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  25571. /**
  25572. * this function is executed by the physics engine.
  25573. */
  25574. this.beforeStep = function () {
  25575. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  25576. //conjugate deltaRotation
  25577. if (_this._deltaRotationConjugated) {
  25578. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  25579. }
  25580. else {
  25581. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  25582. }
  25583. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  25584. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  25585. func(_this);
  25586. });
  25587. };
  25588. /**
  25589. * this function is executed by the physics engine.
  25590. */
  25591. this.afterStep = function () {
  25592. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  25593. func(_this);
  25594. });
  25595. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  25596. _this.mesh.position.addInPlace(_this._deltaPosition);
  25597. if (_this._deltaRotation) {
  25598. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  25599. }
  25600. };
  25601. //event and body object due to cannon's event-based architecture.
  25602. this.onCollide = function (e) {
  25603. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  25604. if (otherImpostor) {
  25605. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  25606. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  25607. }).forEach(function (obj) {
  25608. obj.callback(_this, otherImpostor);
  25609. });
  25610. }
  25611. };
  25612. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  25613. if (!this._physicsEngine) {
  25614. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  25615. }
  25616. else {
  25617. //default options params
  25618. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  25619. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  25620. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  25621. this._joints = [];
  25622. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  25623. if (!this._mesh.parent) {
  25624. this._init();
  25625. }
  25626. }
  25627. }
  25628. /**
  25629. * This function will completly initialize this impostor.
  25630. * It will create a new body - but only if this mesh has no parent.
  25631. * If it has, this impostor will not be used other than to define the impostor
  25632. * of the child mesh.
  25633. */
  25634. PhysicsImpostor.prototype._init = function () {
  25635. this._physicsEngine.removeImpostor(this);
  25636. this.physicsBody = null;
  25637. this._parent = this._parent || this._getPhysicsParent();
  25638. if (!this.parent) {
  25639. this._physicsEngine.addImpostor(this);
  25640. }
  25641. };
  25642. PhysicsImpostor.prototype._getPhysicsParent = function () {
  25643. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  25644. var parentMesh = this.mesh.parent;
  25645. return parentMesh.getPhysicsImpostor();
  25646. }
  25647. return;
  25648. };
  25649. /**
  25650. * Should a new body be generated.
  25651. */
  25652. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  25653. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  25654. };
  25655. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  25656. this.forceUpdate();
  25657. };
  25658. /**
  25659. * Force a regeneration of this or the parent's impostor's body.
  25660. * Use under cautious - This will remove all joints already implemented.
  25661. */
  25662. PhysicsImpostor.prototype.forceUpdate = function () {
  25663. this._init();
  25664. if (this.parent) {
  25665. this.parent.forceUpdate();
  25666. }
  25667. };
  25668. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  25669. get: function () {
  25670. return this._mesh;
  25671. },
  25672. enumerable: true,
  25673. configurable: true
  25674. });
  25675. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  25676. /**
  25677. * Gets the body that holds this impostor. Either its own, or its parent.
  25678. */
  25679. get: function () {
  25680. return this._parent ? this._parent.physicsBody : this._physicsBody;
  25681. },
  25682. /**
  25683. * Set the physics body. Used mainly by the physics engine/plugin
  25684. */
  25685. set: function (physicsBody) {
  25686. if (this._physicsBody) {
  25687. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  25688. }
  25689. this._physicsBody = physicsBody;
  25690. this.resetUpdateFlags();
  25691. },
  25692. enumerable: true,
  25693. configurable: true
  25694. });
  25695. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  25696. get: function () {
  25697. return this._parent;
  25698. },
  25699. enumerable: true,
  25700. configurable: true
  25701. });
  25702. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  25703. this._bodyUpdateRequired = false;
  25704. };
  25705. /**
  25706. * Get a specific parametes from the options parameter.
  25707. */
  25708. PhysicsImpostor.prototype.getParam = function (paramName) {
  25709. return this._options[paramName];
  25710. };
  25711. /**
  25712. * Sets a specific parameter in the options given to the physics plugin
  25713. */
  25714. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  25715. this._options[paramName] = value;
  25716. this._bodyUpdateRequired = true;
  25717. };
  25718. /**
  25719. * Specifically change the body's mass option. Won't recreate the physics body object
  25720. */
  25721. PhysicsImpostor.prototype.setMass = function (mass) {
  25722. if (this.getParam("mass") !== mass) {
  25723. this.setParam("mass", mass);
  25724. }
  25725. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  25726. };
  25727. PhysicsImpostor.prototype.getLinearVelocity = function () {
  25728. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  25729. };
  25730. /**
  25731. * Set the body's linear velocity.
  25732. */
  25733. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  25734. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  25735. };
  25736. PhysicsImpostor.prototype.getAngularVelocity = function () {
  25737. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  25738. };
  25739. /**
  25740. * Set the body's linear velocity.
  25741. */
  25742. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  25743. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  25744. };
  25745. /**
  25746. * Execute a function with the physics plugin native code.
  25747. * Provide a function the will have two variables - the world object and the physics body object.
  25748. */
  25749. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  25750. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  25751. };
  25752. /**
  25753. * Register a function that will be executed before the physics world is stepping forward.
  25754. */
  25755. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  25756. this._onBeforePhysicsStepCallbacks.push(func);
  25757. };
  25758. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  25759. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  25760. if (index > -1) {
  25761. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  25762. }
  25763. else {
  25764. BABYLON.Tools.Warn("Function to remove was not found");
  25765. }
  25766. };
  25767. /**
  25768. * Register a function that will be executed after the physics step
  25769. */
  25770. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  25771. this._onAfterPhysicsStepCallbacks.push(func);
  25772. };
  25773. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  25774. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  25775. if (index > -1) {
  25776. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  25777. }
  25778. else {
  25779. BABYLON.Tools.Warn("Function to remove was not found");
  25780. }
  25781. };
  25782. /**
  25783. * register a function that will be executed when this impostor collides against a different body.
  25784. */
  25785. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  25786. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  25787. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  25788. };
  25789. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  25790. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  25791. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  25792. if (index > -1) {
  25793. this._onPhysicsCollideCallbacks.splice(index, 1);
  25794. }
  25795. else {
  25796. BABYLON.Tools.Warn("Function to remove was not found");
  25797. }
  25798. };
  25799. /**
  25800. * Apply a force
  25801. */
  25802. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  25803. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  25804. };
  25805. /**
  25806. * Apply an impulse
  25807. */
  25808. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  25809. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  25810. };
  25811. /**
  25812. * A help function to create a joint.
  25813. */
  25814. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  25815. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  25816. this.addJoint(otherImpostor, joint);
  25817. };
  25818. /**
  25819. * Add a joint to this impostor with a different impostor.
  25820. */
  25821. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  25822. this._joints.push({
  25823. otherImpostor: otherImpostor,
  25824. joint: joint
  25825. });
  25826. this._physicsEngine.addJoint(this, otherImpostor, joint);
  25827. };
  25828. /**
  25829. * Will keep this body still, in a sleep mode.
  25830. */
  25831. PhysicsImpostor.prototype.sleep = function () {
  25832. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  25833. };
  25834. /**
  25835. * Wake the body up.
  25836. */
  25837. PhysicsImpostor.prototype.wakeUp = function () {
  25838. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  25839. };
  25840. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  25841. if (disposeChildren === void 0) { disposeChildren = true; }
  25842. this.physicsBody = null;
  25843. if (this.parent) {
  25844. this.parent.forceUpdate();
  25845. }
  25846. else {
  25847. this.mesh.getChildMeshes().forEach(function (mesh) {
  25848. if (mesh.physicsImpostor) {
  25849. if (disposeChildren) {
  25850. mesh.physicsImpostor.dispose();
  25851. mesh.physicsImpostor = null;
  25852. }
  25853. }
  25854. });
  25855. }
  25856. };
  25857. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  25858. this._deltaPosition.copyFrom(position);
  25859. };
  25860. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  25861. if (!this._deltaRotation) {
  25862. this._deltaRotation = new BABYLON.Quaternion();
  25863. }
  25864. this._deltaRotation.copyFrom(rotation);
  25865. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  25866. };
  25867. //Impostor types
  25868. PhysicsImpostor.NoImpostor = 0;
  25869. PhysicsImpostor.SphereImpostor = 1;
  25870. PhysicsImpostor.BoxImpostor = 2;
  25871. PhysicsImpostor.PlaneImpostor = 3;
  25872. PhysicsImpostor.MeshImpostor = 4;
  25873. PhysicsImpostor.CapsuleImpostor = 5;
  25874. PhysicsImpostor.ConeImpostor = 6;
  25875. PhysicsImpostor.CylinderImpostor = 7;
  25876. PhysicsImpostor.ConvexHullImpostor = 8;
  25877. PhysicsImpostor.HeightmapImpostor = 9;
  25878. return PhysicsImpostor;
  25879. })();
  25880. BABYLON.PhysicsImpostor = PhysicsImpostor;
  25881. })(BABYLON || (BABYLON = {}));
  25882. var BABYLON;
  25883. (function (BABYLON) {
  25884. var PhysicsEngine = (function () {
  25885. function PhysicsEngine(gravity, _physicsPlugin) {
  25886. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  25887. this._physicsPlugin = _physicsPlugin;
  25888. //new methods and parameters
  25889. this._impostors = [];
  25890. this._joints = [];
  25891. if (!this._physicsPlugin.isSupported()) {
  25892. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  25893. + "Please make sure it is included.");
  25894. }
  25895. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  25896. this.setGravity(gravity);
  25897. this.setTimeStep();
  25898. }
  25899. PhysicsEngine.prototype.setGravity = function (gravity) {
  25900. this.gravity = gravity;
  25901. this._physicsPlugin.setGravity(this.gravity);
  25902. };
  25903. /**
  25904. * Set the time step of the physics engine.
  25905. * default is 1/60.
  25906. * To slow it down, enter 1/600 for example.
  25907. * To speed it up, 1/30
  25908. * @param {number} newTimeStep the new timestep to apply to this world.
  25909. */
  25910. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  25911. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  25912. this._physicsPlugin.setTimeStep(newTimeStep);
  25913. };
  25914. PhysicsEngine.prototype.dispose = function () {
  25915. this._impostors.forEach(function (impostor) {
  25916. impostor.dispose();
  25917. });
  25918. this._physicsPlugin.dispose();
  25919. };
  25920. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  25921. return this._physicsPlugin.name;
  25922. };
  25923. /**
  25924. * Adding a new impostor for the impostor tracking.
  25925. * This will be done by the impostor itself.
  25926. * @param {PhysicsImpostor} impostor the impostor to add
  25927. */
  25928. PhysicsEngine.prototype.addImpostor = function (impostor) {
  25929. this._impostors.push(impostor);
  25930. //if no parent, generate the body
  25931. if (!impostor.parent) {
  25932. this._physicsPlugin.generatePhysicsBody(impostor);
  25933. }
  25934. };
  25935. /**
  25936. * Remove an impostor from the engine.
  25937. * This impostor and its mesh will not longer be updated by the physics engine.
  25938. * @param {PhysicsImpostor} impostor the impostor to remove
  25939. */
  25940. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  25941. var index = this._impostors.indexOf(impostor);
  25942. if (index > -1) {
  25943. var removed = this._impostors.splice(index, 1);
  25944. //Is it needed?
  25945. if (removed.length) {
  25946. //this will also remove it from the world.
  25947. removed[0].physicsBody = null;
  25948. }
  25949. }
  25950. };
  25951. /**
  25952. * Add a joint to the physics engine
  25953. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  25954. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  25955. * @param {PhysicsJoint} the joint that will connect both impostors.
  25956. */
  25957. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  25958. var impostorJoint = {
  25959. mainImpostor: mainImpostor,
  25960. connectedImpostor: connectedImpostor,
  25961. joint: joint
  25962. };
  25963. joint.physicsPlugin = this._physicsPlugin;
  25964. this._joints.push(impostorJoint);
  25965. this._physicsPlugin.generateJoint(impostorJoint);
  25966. };
  25967. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  25968. var matchingJoints = this._joints.filter(function (impostorJoint) {
  25969. return (impostorJoint.connectedImpostor === connectedImpostor
  25970. && impostorJoint.joint === joint
  25971. && impostorJoint.mainImpostor === mainImpostor);
  25972. });
  25973. if (matchingJoints.length) {
  25974. this._physicsPlugin.removeJoint(matchingJoints[0]);
  25975. }
  25976. };
  25977. /**
  25978. * Called by the scene. no need to call it.
  25979. */
  25980. PhysicsEngine.prototype._step = function (delta) {
  25981. var _this = this;
  25982. //check if any mesh has no body / requires an update
  25983. this._impostors.forEach(function (impostor) {
  25984. if (impostor.isBodyInitRequired()) {
  25985. _this._physicsPlugin.generatePhysicsBody(impostor);
  25986. }
  25987. });
  25988. if (delta > 0.1) {
  25989. delta = 0.1;
  25990. }
  25991. else if (delta <= 0) {
  25992. delta = 1.0 / 60.0;
  25993. }
  25994. this._physicsPlugin.executeStep(delta, this._impostors);
  25995. };
  25996. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  25997. return this._physicsPlugin;
  25998. };
  25999. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  26000. for (var i = 0; i < this._impostors.length; ++i) {
  26001. if (this._impostors[i].physicsBody === body) {
  26002. return this._impostors[i];
  26003. }
  26004. }
  26005. };
  26006. // Statics, Legacy support.
  26007. /**
  26008. * @Deprecated
  26009. *
  26010. */
  26011. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  26012. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  26013. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  26014. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  26015. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  26016. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  26017. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  26018. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  26019. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  26020. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  26021. PhysicsEngine.Epsilon = 0.001;
  26022. return PhysicsEngine;
  26023. })();
  26024. BABYLON.PhysicsEngine = PhysicsEngine;
  26025. })(BABYLON || (BABYLON = {}));
  26026. var BABYLON;
  26027. (function (BABYLON) {
  26028. var VertexData = (function () {
  26029. function VertexData() {
  26030. }
  26031. VertexData.prototype.set = function (data, kind) {
  26032. switch (kind) {
  26033. case BABYLON.VertexBuffer.PositionKind:
  26034. this.positions = data;
  26035. break;
  26036. case BABYLON.VertexBuffer.NormalKind:
  26037. this.normals = data;
  26038. break;
  26039. case BABYLON.VertexBuffer.UVKind:
  26040. this.uvs = data;
  26041. break;
  26042. case BABYLON.VertexBuffer.UV2Kind:
  26043. this.uvs2 = data;
  26044. break;
  26045. case BABYLON.VertexBuffer.UV3Kind:
  26046. this.uvs3 = data;
  26047. break;
  26048. case BABYLON.VertexBuffer.UV4Kind:
  26049. this.uvs4 = data;
  26050. break;
  26051. case BABYLON.VertexBuffer.UV5Kind:
  26052. this.uvs5 = data;
  26053. break;
  26054. case BABYLON.VertexBuffer.UV6Kind:
  26055. this.uvs6 = data;
  26056. break;
  26057. case BABYLON.VertexBuffer.ColorKind:
  26058. this.colors = data;
  26059. break;
  26060. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26061. this.matricesIndices = data;
  26062. break;
  26063. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26064. this.matricesWeights = data;
  26065. break;
  26066. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26067. this.matricesIndicesExtra = data;
  26068. break;
  26069. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26070. this.matricesWeightsExtra = data;
  26071. break;
  26072. }
  26073. };
  26074. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26075. this._applyTo(mesh, updatable);
  26076. };
  26077. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26078. this._applyTo(geometry, updatable);
  26079. };
  26080. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26081. this._update(mesh);
  26082. };
  26083. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26084. this._update(geometry);
  26085. };
  26086. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26087. if (this.positions) {
  26088. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26089. }
  26090. if (this.normals) {
  26091. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26092. }
  26093. if (this.uvs) {
  26094. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26095. }
  26096. if (this.uvs2) {
  26097. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26098. }
  26099. if (this.uvs3) {
  26100. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26101. }
  26102. if (this.uvs4) {
  26103. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26104. }
  26105. if (this.uvs5) {
  26106. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26107. }
  26108. if (this.uvs6) {
  26109. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26110. }
  26111. if (this.colors) {
  26112. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26113. }
  26114. if (this.matricesIndices) {
  26115. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26116. }
  26117. if (this.matricesWeights) {
  26118. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26119. }
  26120. if (this.matricesIndicesExtra) {
  26121. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26122. }
  26123. if (this.matricesWeightsExtra) {
  26124. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26125. }
  26126. if (this.indices) {
  26127. meshOrGeometry.setIndices(this.indices);
  26128. }
  26129. };
  26130. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26131. if (this.positions) {
  26132. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26133. }
  26134. if (this.normals) {
  26135. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26136. }
  26137. if (this.uvs) {
  26138. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26139. }
  26140. if (this.uvs2) {
  26141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26142. }
  26143. if (this.uvs3) {
  26144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26145. }
  26146. if (this.uvs4) {
  26147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26148. }
  26149. if (this.uvs5) {
  26150. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26151. }
  26152. if (this.uvs6) {
  26153. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26154. }
  26155. if (this.colors) {
  26156. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26157. }
  26158. if (this.matricesIndices) {
  26159. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26160. }
  26161. if (this.matricesWeights) {
  26162. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26163. }
  26164. if (this.matricesIndicesExtra) {
  26165. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26166. }
  26167. if (this.matricesWeightsExtra) {
  26168. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26169. }
  26170. if (this.indices) {
  26171. meshOrGeometry.setIndices(this.indices);
  26172. }
  26173. };
  26174. VertexData.prototype.transform = function (matrix) {
  26175. var transformed = BABYLON.Vector3.Zero();
  26176. var index;
  26177. if (this.positions) {
  26178. var position = BABYLON.Vector3.Zero();
  26179. for (index = 0; index < this.positions.length; index += 3) {
  26180. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26181. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26182. this.positions[index] = transformed.x;
  26183. this.positions[index + 1] = transformed.y;
  26184. this.positions[index + 2] = transformed.z;
  26185. }
  26186. }
  26187. if (this.normals) {
  26188. var normal = BABYLON.Vector3.Zero();
  26189. for (index = 0; index < this.normals.length; index += 3) {
  26190. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26191. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26192. this.normals[index] = transformed.x;
  26193. this.normals[index + 1] = transformed.y;
  26194. this.normals[index + 2] = transformed.z;
  26195. }
  26196. }
  26197. };
  26198. VertexData.prototype.merge = function (other) {
  26199. if (other.indices) {
  26200. if (!this.indices) {
  26201. this.indices = [];
  26202. }
  26203. var offset = this.positions ? this.positions.length / 3 : 0;
  26204. for (var index = 0; index < other.indices.length; index++) {
  26205. //TODO check type - if Int32Array!
  26206. this.indices.push(other.indices[index] + offset);
  26207. }
  26208. }
  26209. this.positions = this._mergeElement(this.positions, other.positions);
  26210. this.normals = this._mergeElement(this.normals, other.normals);
  26211. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26212. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26213. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26214. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26215. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26216. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26217. this.colors = this._mergeElement(this.colors, other.colors);
  26218. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26219. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26220. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26221. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26222. };
  26223. VertexData.prototype._mergeElement = function (source, other) {
  26224. if (!other)
  26225. return source;
  26226. if (!source)
  26227. return other;
  26228. var len = other.length + source.length;
  26229. var isSrcTypedArray = source instanceof Float32Array;
  26230. var isOthTypedArray = other instanceof Float32Array;
  26231. // use non-loop method when the source is Float32Array
  26232. if (isSrcTypedArray) {
  26233. var ret32 = new Float32Array(len);
  26234. ret32.set(source);
  26235. ret32.set(other, source.length);
  26236. return ret32;
  26237. }
  26238. else if (!isOthTypedArray) {
  26239. return source.concat(other);
  26240. }
  26241. else {
  26242. var ret = source.slice(0); // copy source to a separate array
  26243. for (var i = 0, len = other.length; i < len; i++) {
  26244. ret.push(other[i]);
  26245. }
  26246. return ret;
  26247. }
  26248. };
  26249. VertexData.prototype.serialize = function () {
  26250. var serializationObject = this.serialize();
  26251. if (this.positions) {
  26252. serializationObject.positions = this.positions;
  26253. }
  26254. if (this.normals) {
  26255. serializationObject.normals = this.normals;
  26256. }
  26257. if (this.uvs) {
  26258. serializationObject.uvs = this.uvs;
  26259. }
  26260. if (this.uvs2) {
  26261. serializationObject.uvs2 = this.uvs2;
  26262. }
  26263. if (this.uvs3) {
  26264. serializationObject.uvs3 = this.uvs3;
  26265. }
  26266. if (this.uvs4) {
  26267. serializationObject.uvs4 = this.uvs4;
  26268. }
  26269. if (this.uvs5) {
  26270. serializationObject.uvs5 = this.uvs5;
  26271. }
  26272. if (this.uvs6) {
  26273. serializationObject.uvs6 = this.uvs6;
  26274. }
  26275. if (this.colors) {
  26276. serializationObject.colors = this.colors;
  26277. }
  26278. if (this.matricesIndices) {
  26279. serializationObject.matricesIndices = this.matricesIndices;
  26280. serializationObject.matricesIndices._isExpanded = true;
  26281. }
  26282. if (this.matricesWeights) {
  26283. serializationObject.matricesWeights = this.matricesWeights;
  26284. }
  26285. if (this.matricesIndicesExtra) {
  26286. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26287. serializationObject.matricesIndicesExtra._isExpanded = true;
  26288. }
  26289. if (this.matricesWeightsExtra) {
  26290. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26291. }
  26292. serializationObject.indices = this.indices;
  26293. return serializationObject;
  26294. };
  26295. // Statics
  26296. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26297. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26298. };
  26299. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26300. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26301. };
  26302. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26303. var result = new VertexData();
  26304. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26305. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26306. }
  26307. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26308. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26309. }
  26310. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26311. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26312. }
  26313. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26314. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26315. }
  26316. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26317. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26318. }
  26319. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26320. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26321. }
  26322. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26323. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26324. }
  26325. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26326. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26327. }
  26328. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26329. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26330. }
  26331. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26332. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26333. }
  26334. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26335. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26336. }
  26337. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26338. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  26339. }
  26340. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26341. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  26342. }
  26343. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26344. return result;
  26345. };
  26346. VertexData.CreateRibbon = function (options) {
  26347. var pathArray = options.pathArray;
  26348. var closeArray = options.closeArray || false;
  26349. var closePath = options.closePath || false;
  26350. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26351. var offset = options.offset || defaultOffset;
  26352. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26353. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26354. var positions = [];
  26355. var indices = [];
  26356. var normals = [];
  26357. var uvs = [];
  26358. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26359. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26360. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26361. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26362. var minlg; // minimal length among all paths from pathArray
  26363. var lg = []; // array of path lengths : nb of vertex per path
  26364. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26365. var p; // path iterator
  26366. var i; // point iterator
  26367. var j; // point iterator
  26368. // if single path in pathArray
  26369. if (pathArray.length < 2) {
  26370. var ar1 = [];
  26371. var ar2 = [];
  26372. for (i = 0; i < pathArray[0].length - offset; i++) {
  26373. ar1.push(pathArray[0][i]);
  26374. ar2.push(pathArray[0][i + offset]);
  26375. }
  26376. pathArray = [ar1, ar2];
  26377. }
  26378. // positions and horizontal distances (u)
  26379. var idc = 0;
  26380. var closePathCorr = (closePath) ? 1 : 0;
  26381. var path;
  26382. var l;
  26383. minlg = pathArray[0].length;
  26384. var vectlg;
  26385. var dist;
  26386. for (p = 0; p < pathArray.length; p++) {
  26387. uTotalDistance[p] = 0;
  26388. us[p] = [0];
  26389. path = pathArray[p];
  26390. l = path.length;
  26391. minlg = (minlg < l) ? minlg : l;
  26392. j = 0;
  26393. while (j < l) {
  26394. positions.push(path[j].x, path[j].y, path[j].z);
  26395. if (j > 0) {
  26396. vectlg = path[j].subtract(path[j - 1]).length();
  26397. dist = vectlg + uTotalDistance[p];
  26398. us[p].push(dist);
  26399. uTotalDistance[p] = dist;
  26400. }
  26401. j++;
  26402. }
  26403. if (closePath) {
  26404. j--;
  26405. positions.push(path[0].x, path[0].y, path[0].z);
  26406. vectlg = path[j].subtract(path[0]).length();
  26407. dist = vectlg + uTotalDistance[p];
  26408. us[p].push(dist);
  26409. uTotalDistance[p] = dist;
  26410. }
  26411. lg[p] = l + closePathCorr;
  26412. idx[p] = idc;
  26413. idc += (l + closePathCorr);
  26414. }
  26415. // vertical distances (v)
  26416. var path1;
  26417. var path2;
  26418. var vertex1;
  26419. var vertex2;
  26420. for (i = 0; i < minlg + closePathCorr; i++) {
  26421. vTotalDistance[i] = 0;
  26422. vs[i] = [0];
  26423. for (p = 0; p < pathArray.length - 1; p++) {
  26424. path1 = pathArray[p];
  26425. path2 = pathArray[p + 1];
  26426. if (i === minlg) {
  26427. vertex1 = path1[0];
  26428. vertex2 = path2[0];
  26429. }
  26430. else {
  26431. vertex1 = path1[i];
  26432. vertex2 = path2[i];
  26433. }
  26434. vectlg = vertex2.subtract(vertex1).length();
  26435. dist = vectlg + vTotalDistance[i];
  26436. vs[i].push(dist);
  26437. vTotalDistance[i] = dist;
  26438. }
  26439. if (closeArray) {
  26440. path1 = pathArray[p];
  26441. path2 = pathArray[0];
  26442. if (i === minlg) {
  26443. vertex2 = path2[0];
  26444. }
  26445. vectlg = vertex2.subtract(vertex1).length();
  26446. dist = vectlg + vTotalDistance[i];
  26447. vTotalDistance[i] = dist;
  26448. }
  26449. }
  26450. // uvs
  26451. var u;
  26452. var v;
  26453. for (p = 0; p < pathArray.length; p++) {
  26454. for (i = 0; i < minlg + closePathCorr; i++) {
  26455. u = us[p][i] / uTotalDistance[p];
  26456. v = vs[i][p] / vTotalDistance[i];
  26457. uvs.push(u, v);
  26458. }
  26459. }
  26460. // indices
  26461. p = 0; // path index
  26462. var pi = 0; // positions array index
  26463. var l1 = lg[p] - 1; // path1 length
  26464. var l2 = lg[p + 1] - 1; // path2 length
  26465. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26466. var shft = idx[1] - idx[0]; // shift
  26467. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26468. while (pi <= min && p < path1nb) {
  26469. // 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
  26470. indices.push(pi, pi + shft, pi + 1);
  26471. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26472. pi += 1;
  26473. if (pi === min) {
  26474. p++;
  26475. if (p === lg.length - 1) {
  26476. shft = idx[0] - idx[p];
  26477. l1 = lg[p] - 1;
  26478. l2 = lg[0] - 1;
  26479. }
  26480. else {
  26481. shft = idx[p + 1] - idx[p];
  26482. l1 = lg[p] - 1;
  26483. l2 = lg[p + 1] - 1;
  26484. }
  26485. pi = idx[p];
  26486. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26487. }
  26488. }
  26489. // normals
  26490. VertexData.ComputeNormals(positions, indices, normals);
  26491. if (closePath) {
  26492. var indexFirst = 0;
  26493. var indexLast = 0;
  26494. for (p = 0; p < pathArray.length; p++) {
  26495. indexFirst = idx[p] * 3;
  26496. if (p + 1 < pathArray.length) {
  26497. indexLast = (idx[p + 1] - 1) * 3;
  26498. }
  26499. else {
  26500. indexLast = normals.length - 3;
  26501. }
  26502. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26503. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26504. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26505. normals[indexLast] = normals[indexFirst];
  26506. normals[indexLast + 1] = normals[indexFirst + 1];
  26507. normals[indexLast + 2] = normals[indexFirst + 2];
  26508. }
  26509. }
  26510. // sides
  26511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26512. // Result
  26513. var vertexData = new VertexData();
  26514. vertexData.indices = indices;
  26515. vertexData.positions = positions;
  26516. vertexData.normals = normals;
  26517. vertexData.uvs = uvs;
  26518. if (closePath) {
  26519. vertexData._idx = idx;
  26520. }
  26521. return vertexData;
  26522. };
  26523. VertexData.CreateBox = function (options) {
  26524. var normalsSource = [
  26525. new BABYLON.Vector3(0, 0, 1),
  26526. new BABYLON.Vector3(0, 0, -1),
  26527. new BABYLON.Vector3(1, 0, 0),
  26528. new BABYLON.Vector3(-1, 0, 0),
  26529. new BABYLON.Vector3(0, 1, 0),
  26530. new BABYLON.Vector3(0, -1, 0)
  26531. ];
  26532. var indices = [];
  26533. var positions = [];
  26534. var normals = [];
  26535. var uvs = [];
  26536. var width = options.width || options.size || 1;
  26537. var height = options.height || options.size || 1;
  26538. var depth = options.depth || options.size || 1;
  26539. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26540. var faceUV = options.faceUV || new Array(6);
  26541. var faceColors = options.faceColors;
  26542. var colors = [];
  26543. // default face colors and UV if undefined
  26544. for (var f = 0; f < 6; f++) {
  26545. if (faceUV[f] === undefined) {
  26546. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26547. }
  26548. if (faceColors && faceColors[f] === undefined) {
  26549. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26550. }
  26551. }
  26552. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26553. // Create each face in turn.
  26554. for (var index = 0; index < normalsSource.length; index++) {
  26555. var normal = normalsSource[index];
  26556. // Get two vectors perpendicular to the face normal and to each other.
  26557. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26558. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26559. // Six indices (two triangles) per face.
  26560. var verticesLength = positions.length / 3;
  26561. indices.push(verticesLength);
  26562. indices.push(verticesLength + 1);
  26563. indices.push(verticesLength + 2);
  26564. indices.push(verticesLength);
  26565. indices.push(verticesLength + 2);
  26566. indices.push(verticesLength + 3);
  26567. // Four vertices per face.
  26568. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26569. positions.push(vertex.x, vertex.y, vertex.z);
  26570. normals.push(normal.x, normal.y, normal.z);
  26571. uvs.push(faceUV[index].z, faceUV[index].w);
  26572. if (faceColors) {
  26573. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26574. }
  26575. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26576. positions.push(vertex.x, vertex.y, vertex.z);
  26577. normals.push(normal.x, normal.y, normal.z);
  26578. uvs.push(faceUV[index].x, faceUV[index].w);
  26579. if (faceColors) {
  26580. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26581. }
  26582. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26583. positions.push(vertex.x, vertex.y, vertex.z);
  26584. normals.push(normal.x, normal.y, normal.z);
  26585. uvs.push(faceUV[index].x, faceUV[index].y);
  26586. if (faceColors) {
  26587. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26588. }
  26589. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26590. positions.push(vertex.x, vertex.y, vertex.z);
  26591. normals.push(normal.x, normal.y, normal.z);
  26592. uvs.push(faceUV[index].z, faceUV[index].y);
  26593. if (faceColors) {
  26594. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26595. }
  26596. }
  26597. // sides
  26598. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26599. // Result
  26600. var vertexData = new VertexData();
  26601. vertexData.indices = indices;
  26602. vertexData.positions = positions;
  26603. vertexData.normals = normals;
  26604. vertexData.uvs = uvs;
  26605. if (faceColors) {
  26606. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26607. vertexData.colors = totalColors;
  26608. }
  26609. return vertexData;
  26610. };
  26611. VertexData.CreateSphere = function (options) {
  26612. var segments = options.segments || 32;
  26613. var diameterX = options.diameterX || options.diameter || 1;
  26614. var diameterY = options.diameterY || options.diameter || 1;
  26615. var diameterZ = options.diameterZ || options.diameter || 1;
  26616. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26617. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26618. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26619. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26620. var totalZRotationSteps = 2 + segments;
  26621. var totalYRotationSteps = 2 * totalZRotationSteps;
  26622. var indices = [];
  26623. var positions = [];
  26624. var normals = [];
  26625. var uvs = [];
  26626. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26627. var normalizedZ = zRotationStep / totalZRotationSteps;
  26628. var angleZ = normalizedZ * Math.PI * slice;
  26629. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26630. var normalizedY = yRotationStep / totalYRotationSteps;
  26631. var angleY = normalizedY * Math.PI * 2 * arc;
  26632. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26633. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26634. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26635. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26636. var vertex = complete.multiply(radius);
  26637. var normal = complete.divide(radius).normalize();
  26638. positions.push(vertex.x, vertex.y, vertex.z);
  26639. normals.push(normal.x, normal.y, normal.z);
  26640. uvs.push(normalizedY, normalizedZ);
  26641. }
  26642. if (zRotationStep > 0) {
  26643. var verticesCount = positions.length / 3;
  26644. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26645. indices.push((firstIndex));
  26646. indices.push((firstIndex + 1));
  26647. indices.push(firstIndex + totalYRotationSteps + 1);
  26648. indices.push((firstIndex + totalYRotationSteps + 1));
  26649. indices.push((firstIndex + 1));
  26650. indices.push((firstIndex + totalYRotationSteps + 2));
  26651. }
  26652. }
  26653. }
  26654. // Sides
  26655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26656. // Result
  26657. var vertexData = new VertexData();
  26658. vertexData.indices = indices;
  26659. vertexData.positions = positions;
  26660. vertexData.normals = normals;
  26661. vertexData.uvs = uvs;
  26662. return vertexData;
  26663. };
  26664. // Cylinder and cone
  26665. VertexData.CreateCylinder = function (options) {
  26666. var height = options.height || 2;
  26667. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26668. var diameterBottom = options.diameterBottom || options.diameter || 1;
  26669. var tessellation = options.tessellation || 24;
  26670. var subdivisions = options.subdivisions || 1;
  26671. var hasRings = options.hasRings;
  26672. var enclose = options.enclose;
  26673. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26674. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26675. var faceUV = options.faceUV || new Array(3);
  26676. var faceColors = options.faceColors;
  26677. // default face colors and UV if undefined
  26678. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26679. var ringNb = (hasRings) ? subdivisions : 1;
  26680. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26681. var f;
  26682. for (f = 0; f < surfaceNb; f++) {
  26683. if (faceColors && faceColors[f] === undefined) {
  26684. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26685. }
  26686. }
  26687. for (f = 0; f < surfaceNb; f++) {
  26688. if (faceUV && faceUV[f] === undefined) {
  26689. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26690. }
  26691. }
  26692. var indices = [];
  26693. var positions = [];
  26694. var normals = [];
  26695. var uvs = [];
  26696. var colors = [];
  26697. var angle_step = Math.PI * 2 * arc / tessellation;
  26698. var angle;
  26699. var h;
  26700. var radius;
  26701. var tan = (diameterBottom - diameterTop) / 2 / height;
  26702. var ringVertex = BABYLON.Vector3.Zero();
  26703. var ringNormal = BABYLON.Vector3.Zero();
  26704. var ringFirstVertex = BABYLON.Vector3.Zero();
  26705. var ringFirstNormal = BABYLON.Vector3.Zero();
  26706. var quadNormal = BABYLON.Vector3.Zero();
  26707. var Y = BABYLON.Axis.Y;
  26708. // positions, normals, uvs
  26709. var i;
  26710. var j;
  26711. var r;
  26712. var ringIdx = 1;
  26713. var s = 1; // surface index
  26714. var cs = 0;
  26715. var v = 0;
  26716. for (i = 0; i <= subdivisions; i++) {
  26717. h = i / subdivisions;
  26718. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26719. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26720. for (r = 0; r < ringIdx; r++) {
  26721. if (hasRings) {
  26722. s += r;
  26723. }
  26724. if (enclose) {
  26725. s += 2 * r;
  26726. }
  26727. for (j = 0; j <= tessellation; j++) {
  26728. angle = j * angle_step;
  26729. // position
  26730. ringVertex.x = Math.cos(-angle) * radius;
  26731. ringVertex.y = -height / 2 + h * height;
  26732. ringVertex.z = Math.sin(-angle) * radius;
  26733. // normal
  26734. if (diameterTop === 0 && i === subdivisions) {
  26735. // if no top cap, reuse former normals
  26736. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26737. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26738. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26739. }
  26740. else {
  26741. ringNormal.x = ringVertex.x;
  26742. ringNormal.z = ringVertex.z;
  26743. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26744. ringNormal.normalize();
  26745. }
  26746. // keep first ring vertex values for enclose
  26747. if (j === 0) {
  26748. ringFirstVertex.copyFrom(ringVertex);
  26749. ringFirstNormal.copyFrom(ringNormal);
  26750. }
  26751. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26752. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26753. if (hasRings) {
  26754. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26755. }
  26756. else {
  26757. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26758. }
  26759. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26760. if (faceColors) {
  26761. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26762. }
  26763. }
  26764. // if enclose, add four vertices and their dedicated normals
  26765. if (arc !== 1 && enclose) {
  26766. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26767. positions.push(0, ringVertex.y, 0);
  26768. positions.push(0, ringVertex.y, 0);
  26769. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26770. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26771. quadNormal.normalize();
  26772. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26773. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26774. quadNormal.normalize();
  26775. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26776. if (hasRings) {
  26777. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26778. }
  26779. else {
  26780. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26781. }
  26782. uvs.push(faceUV[s + 1].x, v);
  26783. uvs.push(faceUV[s + 1].z, v);
  26784. if (hasRings) {
  26785. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26786. }
  26787. else {
  26788. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26789. }
  26790. uvs.push(faceUV[s + 2].x, v);
  26791. uvs.push(faceUV[s + 2].z, v);
  26792. if (faceColors) {
  26793. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26794. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26795. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26796. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26797. }
  26798. }
  26799. if (cs !== s) {
  26800. cs = s;
  26801. }
  26802. }
  26803. }
  26804. // indices
  26805. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26806. var s;
  26807. i = 0;
  26808. for (s = 0; s < subdivisions; s++) {
  26809. for (j = 0; j < tessellation; j++) {
  26810. var i0 = i * (e + 1) + j;
  26811. var i1 = (i + 1) * (e + 1) + j;
  26812. var i2 = i * (e + 1) + (j + 1);
  26813. var i3 = (i + 1) * (e + 1) + (j + 1);
  26814. indices.push(i0, i1, i2);
  26815. indices.push(i3, i2, i1);
  26816. }
  26817. if (arc !== 1 && enclose) {
  26818. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26819. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26820. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26821. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26822. }
  26823. i = (hasRings) ? (i + 2) : (i + 1);
  26824. }
  26825. // Caps
  26826. var createCylinderCap = function (isTop) {
  26827. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26828. if (radius === 0) {
  26829. return;
  26830. }
  26831. // Cap positions, normals & uvs
  26832. var angle;
  26833. var circleVector;
  26834. var i;
  26835. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26836. var c;
  26837. if (faceColors) {
  26838. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26839. }
  26840. // cap center
  26841. var vbase = positions.length / 3;
  26842. var offset = isTop ? height / 2 : -height / 2;
  26843. var center = new BABYLON.Vector3(0, offset, 0);
  26844. positions.push(center.x, center.y, center.z);
  26845. normals.push(0, isTop ? 1 : -1, 0);
  26846. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26847. if (faceColors) {
  26848. colors.push(c.r, c.g, c.b, c.a);
  26849. }
  26850. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26851. for (i = 0; i <= tessellation; i++) {
  26852. angle = Math.PI * 2 * i * arc / tessellation;
  26853. var cos = Math.cos(-angle);
  26854. var sin = Math.sin(-angle);
  26855. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26856. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26857. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26858. normals.push(0, isTop ? 1 : -1, 0);
  26859. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26860. if (faceColors) {
  26861. colors.push(c.r, c.g, c.b, c.a);
  26862. }
  26863. }
  26864. // Cap indices
  26865. for (i = 0; i < tessellation; i++) {
  26866. if (!isTop) {
  26867. indices.push(vbase);
  26868. indices.push(vbase + (i + 1));
  26869. indices.push(vbase + (i + 2));
  26870. }
  26871. else {
  26872. indices.push(vbase);
  26873. indices.push(vbase + (i + 2));
  26874. indices.push(vbase + (i + 1));
  26875. }
  26876. }
  26877. };
  26878. // add caps to geometry
  26879. createCylinderCap(false);
  26880. createCylinderCap(true);
  26881. // Sides
  26882. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26883. var vertexData = new VertexData();
  26884. vertexData.indices = indices;
  26885. vertexData.positions = positions;
  26886. vertexData.normals = normals;
  26887. vertexData.uvs = uvs;
  26888. if (faceColors) {
  26889. vertexData.colors = colors;
  26890. }
  26891. return vertexData;
  26892. };
  26893. VertexData.CreateTorus = function (options) {
  26894. var indices = [];
  26895. var positions = [];
  26896. var normals = [];
  26897. var uvs = [];
  26898. var diameter = options.diameter || 1;
  26899. var thickness = options.thickness || 0.5;
  26900. var tessellation = options.tessellation || 16;
  26901. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26902. var stride = tessellation + 1;
  26903. for (var i = 0; i <= tessellation; i++) {
  26904. var u = i / tessellation;
  26905. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26906. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26907. for (var j = 0; j <= tessellation; j++) {
  26908. var v = 1 - j / tessellation;
  26909. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26910. var dx = Math.cos(innerAngle);
  26911. var dy = Math.sin(innerAngle);
  26912. // Create a vertex.
  26913. var normal = new BABYLON.Vector3(dx, dy, 0);
  26914. var position = normal.scale(thickness / 2);
  26915. var textureCoordinate = new BABYLON.Vector2(u, v);
  26916. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26917. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26918. positions.push(position.x, position.y, position.z);
  26919. normals.push(normal.x, normal.y, normal.z);
  26920. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26921. // And create indices for two triangles.
  26922. var nextI = (i + 1) % stride;
  26923. var nextJ = (j + 1) % stride;
  26924. indices.push(i * stride + j);
  26925. indices.push(i * stride + nextJ);
  26926. indices.push(nextI * stride + j);
  26927. indices.push(i * stride + nextJ);
  26928. indices.push(nextI * stride + nextJ);
  26929. indices.push(nextI * stride + j);
  26930. }
  26931. }
  26932. // Sides
  26933. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26934. // Result
  26935. var vertexData = new VertexData();
  26936. vertexData.indices = indices;
  26937. vertexData.positions = positions;
  26938. vertexData.normals = normals;
  26939. vertexData.uvs = uvs;
  26940. return vertexData;
  26941. };
  26942. VertexData.CreateLineSystem = function (options) {
  26943. var indices = [];
  26944. var positions = [];
  26945. var lines = options.lines;
  26946. var idx = 0;
  26947. for (var l = 0; l < lines.length; l++) {
  26948. var points = lines[l];
  26949. for (var index = 0; index < points.length; index++) {
  26950. positions.push(points[index].x, points[index].y, points[index].z);
  26951. if (index > 0) {
  26952. indices.push(idx - 1);
  26953. indices.push(idx);
  26954. }
  26955. idx++;
  26956. }
  26957. }
  26958. var vertexData = new VertexData();
  26959. vertexData.indices = indices;
  26960. vertexData.positions = positions;
  26961. return vertexData;
  26962. };
  26963. VertexData.CreateDashedLines = function (options) {
  26964. var dashSize = options.dashSize || 3;
  26965. var gapSize = options.gapSize || 1;
  26966. var dashNb = options.dashNb || 200;
  26967. var points = options.points;
  26968. var positions = new Array();
  26969. var indices = new Array();
  26970. var curvect = BABYLON.Vector3.Zero();
  26971. var lg = 0;
  26972. var nb = 0;
  26973. var shft = 0;
  26974. var dashshft = 0;
  26975. var curshft = 0;
  26976. var idx = 0;
  26977. var i = 0;
  26978. for (i = 0; i < points.length - 1; i++) {
  26979. points[i + 1].subtractToRef(points[i], curvect);
  26980. lg += curvect.length();
  26981. }
  26982. shft = lg / dashNb;
  26983. dashshft = dashSize * shft / (dashSize + gapSize);
  26984. for (i = 0; i < points.length - 1; i++) {
  26985. points[i + 1].subtractToRef(points[i], curvect);
  26986. nb = Math.floor(curvect.length() / shft);
  26987. curvect.normalize();
  26988. for (var j = 0; j < nb; j++) {
  26989. curshft = shft * j;
  26990. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26991. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26992. indices.push(idx, idx + 1);
  26993. idx += 2;
  26994. }
  26995. }
  26996. // Result
  26997. var vertexData = new VertexData();
  26998. vertexData.positions = positions;
  26999. vertexData.indices = indices;
  27000. return vertexData;
  27001. };
  27002. VertexData.CreateGround = function (options) {
  27003. var indices = [];
  27004. var positions = [];
  27005. var normals = [];
  27006. var uvs = [];
  27007. var row, col;
  27008. var width = options.width || 1;
  27009. var height = options.height || 1;
  27010. var subdivisions = options.subdivisions || 1;
  27011. for (row = 0; row <= subdivisions; row++) {
  27012. for (col = 0; col <= subdivisions; col++) {
  27013. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  27014. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27015. positions.push(position.x, position.y, position.z);
  27016. normals.push(normal.x, normal.y, normal.z);
  27017. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  27018. }
  27019. }
  27020. for (row = 0; row < subdivisions; row++) {
  27021. for (col = 0; col < subdivisions; col++) {
  27022. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27023. indices.push(col + 1 + row * (subdivisions + 1));
  27024. indices.push(col + row * (subdivisions + 1));
  27025. indices.push(col + (row + 1) * (subdivisions + 1));
  27026. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27027. indices.push(col + row * (subdivisions + 1));
  27028. }
  27029. }
  27030. // Result
  27031. var vertexData = new VertexData();
  27032. vertexData.indices = indices;
  27033. vertexData.positions = positions;
  27034. vertexData.normals = normals;
  27035. vertexData.uvs = uvs;
  27036. return vertexData;
  27037. };
  27038. VertexData.CreateTiledGround = function (options) {
  27039. var xmin = options.xmin;
  27040. var zmin = options.zmin;
  27041. var xmax = options.xmax;
  27042. var zmax = options.zmax;
  27043. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27044. var precision = options.precision || { w: 1, h: 1 };
  27045. var indices = [];
  27046. var positions = [];
  27047. var normals = [];
  27048. var uvs = [];
  27049. var row, col, tileRow, tileCol;
  27050. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  27051. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27052. precision.w = (precision.w < 1) ? 1 : precision.w;
  27053. precision.h = (precision.h < 1) ? 1 : precision.h;
  27054. var tileSize = {
  27055. 'w': (xmax - xmin) / subdivisions.w,
  27056. 'h': (zmax - zmin) / subdivisions.h
  27057. };
  27058. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27059. // Indices
  27060. var base = positions.length / 3;
  27061. var rowLength = precision.w + 1;
  27062. for (row = 0; row < precision.h; row++) {
  27063. for (col = 0; col < precision.w; col++) {
  27064. var square = [
  27065. base + col + row * rowLength,
  27066. base + (col + 1) + row * rowLength,
  27067. base + (col + 1) + (row + 1) * rowLength,
  27068. base + col + (row + 1) * rowLength
  27069. ];
  27070. indices.push(square[1]);
  27071. indices.push(square[2]);
  27072. indices.push(square[3]);
  27073. indices.push(square[0]);
  27074. indices.push(square[1]);
  27075. indices.push(square[3]);
  27076. }
  27077. }
  27078. // Position, normals and uvs
  27079. var position = BABYLON.Vector3.Zero();
  27080. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27081. for (row = 0; row <= precision.h; row++) {
  27082. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27083. for (col = 0; col <= precision.w; col++) {
  27084. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27085. position.y = 0;
  27086. positions.push(position.x, position.y, position.z);
  27087. normals.push(normal.x, normal.y, normal.z);
  27088. uvs.push(col / precision.w, row / precision.h);
  27089. }
  27090. }
  27091. }
  27092. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27093. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27094. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27095. }
  27096. }
  27097. // Result
  27098. var vertexData = new VertexData();
  27099. vertexData.indices = indices;
  27100. vertexData.positions = positions;
  27101. vertexData.normals = normals;
  27102. vertexData.uvs = uvs;
  27103. return vertexData;
  27104. };
  27105. VertexData.CreateGroundFromHeightMap = function (options) {
  27106. var indices = [];
  27107. var positions = [];
  27108. var normals = [];
  27109. var uvs = [];
  27110. var row, col;
  27111. // Vertices
  27112. for (row = 0; row <= options.subdivisions; row++) {
  27113. for (col = 0; col <= options.subdivisions; col++) {
  27114. 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));
  27115. // Compute height
  27116. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27117. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27118. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27119. var r = options.buffer[pos] / 255.0;
  27120. var g = options.buffer[pos + 1] / 255.0;
  27121. var b = options.buffer[pos + 2] / 255.0;
  27122. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27123. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27124. // Add vertex
  27125. positions.push(position.x, position.y, position.z);
  27126. normals.push(0, 0, 0);
  27127. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27128. }
  27129. }
  27130. // Indices
  27131. for (row = 0; row < options.subdivisions; row++) {
  27132. for (col = 0; col < options.subdivisions; col++) {
  27133. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27134. indices.push(col + 1 + row * (options.subdivisions + 1));
  27135. indices.push(col + row * (options.subdivisions + 1));
  27136. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27137. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27138. indices.push(col + row * (options.subdivisions + 1));
  27139. }
  27140. }
  27141. // Normals
  27142. VertexData.ComputeNormals(positions, indices, normals);
  27143. // Result
  27144. var vertexData = new VertexData();
  27145. vertexData.indices = indices;
  27146. vertexData.positions = positions;
  27147. vertexData.normals = normals;
  27148. vertexData.uvs = uvs;
  27149. return vertexData;
  27150. };
  27151. VertexData.CreatePlane = function (options) {
  27152. var indices = [];
  27153. var positions = [];
  27154. var normals = [];
  27155. var uvs = [];
  27156. var width = options.width || options.size || 1;
  27157. var height = options.height || options.size || 1;
  27158. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27159. // Vertices
  27160. var halfWidth = width / 2.0;
  27161. var halfHeight = height / 2.0;
  27162. positions.push(-halfWidth, -halfHeight, 0);
  27163. normals.push(0, 0, -1.0);
  27164. uvs.push(0.0, 0.0);
  27165. positions.push(halfWidth, -halfHeight, 0);
  27166. normals.push(0, 0, -1.0);
  27167. uvs.push(1.0, 0.0);
  27168. positions.push(halfWidth, halfHeight, 0);
  27169. normals.push(0, 0, -1.0);
  27170. uvs.push(1.0, 1.0);
  27171. positions.push(-halfWidth, halfHeight, 0);
  27172. normals.push(0, 0, -1.0);
  27173. uvs.push(0.0, 1.0);
  27174. // Indices
  27175. indices.push(0);
  27176. indices.push(1);
  27177. indices.push(2);
  27178. indices.push(0);
  27179. indices.push(2);
  27180. indices.push(3);
  27181. // Sides
  27182. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27183. // Result
  27184. var vertexData = new VertexData();
  27185. vertexData.indices = indices;
  27186. vertexData.positions = positions;
  27187. vertexData.normals = normals;
  27188. vertexData.uvs = uvs;
  27189. return vertexData;
  27190. };
  27191. VertexData.CreateDisc = function (options) {
  27192. var positions = [];
  27193. var indices = [];
  27194. var normals = [];
  27195. var uvs = [];
  27196. var radius = options.radius || 0.5;
  27197. var tessellation = options.tessellation || 64;
  27198. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27199. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27200. // positions and uvs
  27201. positions.push(0, 0, 0); // disc center first
  27202. uvs.push(0.5, 0.5);
  27203. var theta = Math.PI * 2 * arc;
  27204. var step = theta / tessellation;
  27205. for (var a = 0; a < theta; a += step) {
  27206. var x = Math.cos(a);
  27207. var y = Math.sin(a);
  27208. var u = (x + 1) / 2;
  27209. var v = (1 - y) / 2;
  27210. positions.push(radius * x, radius * y, 0);
  27211. uvs.push(u, v);
  27212. }
  27213. if (arc === 1) {
  27214. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27215. uvs.push(uvs[2], uvs[3]);
  27216. }
  27217. //indices
  27218. var vertexNb = positions.length / 3;
  27219. for (var i = 1; i < vertexNb - 1; i++) {
  27220. indices.push(i + 1, 0, i);
  27221. }
  27222. // result
  27223. VertexData.ComputeNormals(positions, indices, normals);
  27224. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27225. var vertexData = new VertexData();
  27226. vertexData.indices = indices;
  27227. vertexData.positions = positions;
  27228. vertexData.normals = normals;
  27229. vertexData.uvs = uvs;
  27230. return vertexData;
  27231. };
  27232. VertexData.CreateIcoSphere = function (options) {
  27233. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27234. var radius = options.radius || 1;
  27235. var flat = (options.flat === undefined) ? true : options.flat;
  27236. var subdivisions = options.subdivisions || 4;
  27237. var radiusX = options.radiusX || radius;
  27238. var radiusY = options.radiusY || radius;
  27239. var radiusZ = options.radiusZ || radius;
  27240. var t = (1 + Math.sqrt(5)) / 2;
  27241. // 12 vertex x,y,z
  27242. var ico_vertices = [
  27243. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27244. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27245. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27246. ];
  27247. // index of 3 vertex makes a face of icopshere
  27248. var ico_indices = [
  27249. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27250. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27251. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27252. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27253. ];
  27254. // vertex for uv have aliased position, not for UV
  27255. var vertices_unalias_id = [
  27256. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27257. // vertex alias
  27258. 0,
  27259. 2,
  27260. 3,
  27261. 3,
  27262. 3,
  27263. 4,
  27264. 7,
  27265. 8,
  27266. 9,
  27267. 9,
  27268. 10,
  27269. 11 // 23: B + 12
  27270. ];
  27271. // uv as integer step (not pixels !)
  27272. var ico_vertexuv = [
  27273. 5, 1, 3, 1, 6, 4, 0, 0,
  27274. 5, 3, 4, 2, 2, 2, 4, 0,
  27275. 2, 0, 1, 1, 6, 0, 6, 2,
  27276. // vertex alias (for same vertex on different faces)
  27277. 0, 4,
  27278. 3, 3,
  27279. 4, 4,
  27280. 3, 1,
  27281. 4, 2,
  27282. 4, 4,
  27283. 0, 2,
  27284. 1, 1,
  27285. 2, 2,
  27286. 3, 3,
  27287. 1, 3,
  27288. 2, 4 // 23: B + 12
  27289. ];
  27290. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27291. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27292. // First island of uv mapping
  27293. // v = 4h 3+ 2
  27294. // v = 3h 9+ 4
  27295. // v = 2h 9+ 5 B
  27296. // v = 1h 9 1 0
  27297. // v = 0h 3 8 7 A
  27298. // u = 0 1 2 3 4 5 6 *a
  27299. // Second island of uv mapping
  27300. // v = 4h 0+ B+ 4+
  27301. // v = 3h A+ 2+
  27302. // v = 2h 7+ 6 3+
  27303. // v = 1h 8+ 3+
  27304. // v = 0h
  27305. // u = 0 1 2 3 4 5 6 *a
  27306. // Face layout on texture UV mapping
  27307. // ============
  27308. // \ 4 /\ 16 / ======
  27309. // \ / \ / /\ 11 /
  27310. // \/ 7 \/ / \ /
  27311. // ======= / 10 \/
  27312. // /\ 17 /\ =======
  27313. // / \ / \ \ 15 /\
  27314. // / 8 \/ 12 \ \ / \
  27315. // ============ \/ 6 \
  27316. // \ 18 /\ ============
  27317. // \ / \ \ 5 /\ 0 /
  27318. // \/ 13 \ \ / \ /
  27319. // ======= \/ 1 \/
  27320. // =============
  27321. // /\ 19 /\ 2 /\
  27322. // / \ / \ / \
  27323. // / 14 \/ 9 \/ 3 \
  27324. // ===================
  27325. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27326. var ustep = 138 / 1024;
  27327. var vstep = 239 / 1024;
  27328. var uoffset = 60 / 1024;
  27329. var voffset = 26 / 1024;
  27330. // Second island should have margin, not to touch the first island
  27331. // avoid any borderline artefact in pixel rounding
  27332. var island_u_offset = -40 / 1024;
  27333. var island_v_offset = +20 / 1024;
  27334. // face is either island 0 or 1 :
  27335. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27336. var island = [
  27337. 0, 0, 0, 0, 1,
  27338. 0, 0, 1, 1, 0,
  27339. 0, 0, 1, 1, 0,
  27340. 0, 1, 1, 1, 0 // 15 - 19
  27341. ];
  27342. var indices = [];
  27343. var positions = [];
  27344. var normals = [];
  27345. var uvs = [];
  27346. var current_indice = 0;
  27347. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27348. var face_vertex_pos = new Array(3);
  27349. var face_vertex_uv = new Array(3);
  27350. var v012;
  27351. for (v012 = 0; v012 < 3; v012++) {
  27352. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27353. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27354. }
  27355. // create all with normals
  27356. for (var face = 0; face < 20; face++) {
  27357. // 3 vertex per face
  27358. for (v012 = 0; v012 < 3; v012++) {
  27359. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27360. var v_id = ico_indices[3 * face + v012];
  27361. // vertex have 3D position (x,y,z)
  27362. 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]);
  27363. // Normalize to get normal, then scale to radius
  27364. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27365. // uv Coordinates from vertex ID
  27366. 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);
  27367. }
  27368. // Subdivide the face (interpolate pos, norm, uv)
  27369. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27370. // - norm is linear interpolation of vertex corner normal
  27371. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27372. // - uv is linear interpolation
  27373. //
  27374. // Topology is as below for sub-divide by 2
  27375. // vertex shown as v0,v1,v2
  27376. // interp index is i1 to progress in range [v0,v1[
  27377. // interp index is i2 to progress in range [v0,v2[
  27378. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27379. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27380. //
  27381. //
  27382. // i2 v2
  27383. // ^ ^
  27384. // / / \
  27385. // / / \
  27386. // / / \
  27387. // / / (0,1) \
  27388. // / #---------\
  27389. // / / \ (0,0)'/ \
  27390. // / / \ / \
  27391. // / / \ / \
  27392. // / / (0,0) \ / (1,0) \
  27393. // / #---------#---------\
  27394. // v0 v1
  27395. //
  27396. // --------------------> i1
  27397. //
  27398. // interp of (i1,i2):
  27399. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27400. // along i1 : lerp(x0,x1, i1/(S-i2))
  27401. //
  27402. // centroid of triangle is needed to get help normal computation
  27403. // (c1,c2) are used for centroid location
  27404. var interp_vertex = function (i1, i2, c1, c2) {
  27405. // vertex is interpolated from
  27406. // - face_vertex_pos[0..2]
  27407. // - face_vertex_uv[0..2]
  27408. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27409. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27410. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27411. pos_interp.normalize();
  27412. var vertex_normal;
  27413. if (flat) {
  27414. // in flat mode, recalculate normal as face centroid normal
  27415. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27416. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27417. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27418. }
  27419. else {
  27420. // in smooth mode, recalculate normal from each single vertex position
  27421. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27422. }
  27423. // Vertex normal need correction due to X,Y,Z radius scaling
  27424. vertex_normal.x /= radiusX;
  27425. vertex_normal.y /= radiusY;
  27426. vertex_normal.z /= radiusZ;
  27427. vertex_normal.normalize();
  27428. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27429. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27430. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27431. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27432. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27433. uvs.push(uv_interp.x, uv_interp.y);
  27434. // push each vertex has member of a face
  27435. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27436. indices.push(current_indice);
  27437. current_indice++;
  27438. };
  27439. for (var i2 = 0; i2 < subdivisions; i2++) {
  27440. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27441. // face : (i1,i2) for /\ :
  27442. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27443. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27444. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27445. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27446. if (i1 + i2 + 1 < subdivisions) {
  27447. // face : (i1,i2)' for \/ :
  27448. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27449. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27450. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27451. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27452. }
  27453. }
  27454. }
  27455. }
  27456. // Sides
  27457. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27458. // Result
  27459. var vertexData = new VertexData();
  27460. vertexData.indices = indices;
  27461. vertexData.positions = positions;
  27462. vertexData.normals = normals;
  27463. vertexData.uvs = uvs;
  27464. return vertexData;
  27465. };
  27466. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27467. VertexData.CreatePolyhedron = function (options) {
  27468. // provided polyhedron types :
  27469. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27470. // 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)
  27471. var polyhedra = [];
  27472. 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]] };
  27473. 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]] };
  27474. polyhedra[2] = {
  27475. 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]],
  27476. 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]]
  27477. };
  27478. polyhedra[3] = {
  27479. 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]],
  27480. 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]]
  27481. };
  27482. polyhedra[4] = {
  27483. 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]],
  27484. 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]]
  27485. };
  27486. 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]] };
  27487. 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]] };
  27488. 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]] };
  27489. 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]] };
  27490. 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]] };
  27491. 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]] };
  27492. 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]] };
  27493. 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]] };
  27494. 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]] };
  27495. polyhedra[14] = {
  27496. 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]],
  27497. 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]]
  27498. };
  27499. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27500. var size = options.size;
  27501. var sizeX = options.sizeX || size || 1;
  27502. var sizeY = options.sizeY || size || 1;
  27503. var sizeZ = options.sizeZ || size || 1;
  27504. var data = options.custom || polyhedra[type];
  27505. var nbfaces = data.face.length;
  27506. var faceUV = options.faceUV || new Array(nbfaces);
  27507. var faceColors = options.faceColors;
  27508. var flat = (options.flat === undefined) ? true : options.flat;
  27509. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27510. var positions = [];
  27511. var indices = [];
  27512. var normals = [];
  27513. var uvs = [];
  27514. var colors = [];
  27515. var index = 0;
  27516. var faceIdx = 0; // face cursor in the array "indexes"
  27517. var indexes = [];
  27518. var i = 0;
  27519. var f = 0;
  27520. var u, v, ang, x, y, tmp;
  27521. // default face colors and UV if undefined
  27522. if (flat) {
  27523. for (f = 0; f < nbfaces; f++) {
  27524. if (faceColors && faceColors[f] === undefined) {
  27525. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27526. }
  27527. if (faceUV && faceUV[f] === undefined) {
  27528. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27529. }
  27530. }
  27531. }
  27532. if (!flat) {
  27533. for (i = 0; i < data.vertex.length; i++) {
  27534. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27535. uvs.push(0, 0);
  27536. }
  27537. for (f = 0; f < nbfaces; f++) {
  27538. for (i = 0; i < data.face[f].length - 2; i++) {
  27539. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27540. }
  27541. }
  27542. }
  27543. else {
  27544. for (f = 0; f < nbfaces; f++) {
  27545. var fl = data.face[f].length; // number of vertices of the current face
  27546. ang = 2 * Math.PI / fl;
  27547. x = 0.5 * Math.tan(ang / 2);
  27548. y = 0.5;
  27549. // positions, uvs, colors
  27550. for (i = 0; i < fl; i++) {
  27551. // positions
  27552. 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);
  27553. indexes.push(index);
  27554. index++;
  27555. // uvs
  27556. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27557. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27558. uvs.push(u, v);
  27559. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27560. y = x * Math.sin(ang) + y * Math.cos(ang);
  27561. x = tmp;
  27562. // colors
  27563. if (faceColors) {
  27564. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27565. }
  27566. }
  27567. // indices from indexes
  27568. for (i = 0; i < fl - 2; i++) {
  27569. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27570. }
  27571. faceIdx += fl;
  27572. }
  27573. }
  27574. VertexData.ComputeNormals(positions, indices, normals);
  27575. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27576. var vertexData = new VertexData();
  27577. vertexData.positions = positions;
  27578. vertexData.indices = indices;
  27579. vertexData.normals = normals;
  27580. vertexData.uvs = uvs;
  27581. if (faceColors && flat) {
  27582. vertexData.colors = colors;
  27583. }
  27584. return vertexData;
  27585. };
  27586. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27587. VertexData.CreateTorusKnot = function (options) {
  27588. var indices = [];
  27589. var positions = [];
  27590. var normals = [];
  27591. var uvs = [];
  27592. var radius = options.radius || 2;
  27593. var tube = options.tube || 0.5;
  27594. var radialSegments = options.radialSegments || 32;
  27595. var tubularSegments = options.tubularSegments || 32;
  27596. var p = options.p || 2;
  27597. var q = options.q || 3;
  27598. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27599. // Helper
  27600. var getPos = function (angle) {
  27601. var cu = Math.cos(angle);
  27602. var su = Math.sin(angle);
  27603. var quOverP = q / p * angle;
  27604. var cs = Math.cos(quOverP);
  27605. var tx = radius * (2 + cs) * 0.5 * cu;
  27606. var ty = radius * (2 + cs) * su * 0.5;
  27607. var tz = radius * Math.sin(quOverP) * 0.5;
  27608. return new BABYLON.Vector3(tx, ty, tz);
  27609. };
  27610. // Vertices
  27611. var i;
  27612. var j;
  27613. for (i = 0; i <= radialSegments; i++) {
  27614. var modI = i % radialSegments;
  27615. var u = modI / radialSegments * 2 * p * Math.PI;
  27616. var p1 = getPos(u);
  27617. var p2 = getPos(u + 0.01);
  27618. var tang = p2.subtract(p1);
  27619. var n = p2.add(p1);
  27620. var bitan = BABYLON.Vector3.Cross(tang, n);
  27621. n = BABYLON.Vector3.Cross(bitan, tang);
  27622. bitan.normalize();
  27623. n.normalize();
  27624. for (j = 0; j < tubularSegments; j++) {
  27625. var modJ = j % tubularSegments;
  27626. var v = modJ / tubularSegments * 2 * Math.PI;
  27627. var cx = -tube * Math.cos(v);
  27628. var cy = tube * Math.sin(v);
  27629. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27630. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27631. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27632. uvs.push(i / radialSegments);
  27633. uvs.push(j / tubularSegments);
  27634. }
  27635. }
  27636. for (i = 0; i < radialSegments; i++) {
  27637. for (j = 0; j < tubularSegments; j++) {
  27638. var jNext = (j + 1) % tubularSegments;
  27639. var a = i * tubularSegments + j;
  27640. var b = (i + 1) * tubularSegments + j;
  27641. var c = (i + 1) * tubularSegments + jNext;
  27642. var d = i * tubularSegments + jNext;
  27643. indices.push(d);
  27644. indices.push(b);
  27645. indices.push(a);
  27646. indices.push(d);
  27647. indices.push(c);
  27648. indices.push(b);
  27649. }
  27650. }
  27651. // Normals
  27652. VertexData.ComputeNormals(positions, indices, normals);
  27653. // Sides
  27654. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27655. // Result
  27656. var vertexData = new VertexData();
  27657. vertexData.indices = indices;
  27658. vertexData.positions = positions;
  27659. vertexData.normals = normals;
  27660. vertexData.uvs = uvs;
  27661. return vertexData;
  27662. };
  27663. // Tools
  27664. /**
  27665. * @param {any} - positions (number[] or Float32Array)
  27666. * @param {any} - indices (number[] or Uint16Array)
  27667. * @param {any} - normals (number[] or Float32Array)
  27668. */
  27669. VertexData.ComputeNormals = function (positions, indices, normals) {
  27670. var index = 0;
  27671. var p1p2x = 0.0;
  27672. var p1p2y = 0.0;
  27673. var p1p2z = 0.0;
  27674. var p3p2x = 0.0;
  27675. var p3p2y = 0.0;
  27676. var p3p2z = 0.0;
  27677. var faceNormalx = 0.0;
  27678. var faceNormaly = 0.0;
  27679. var faceNormalz = 0.0;
  27680. var length = 0.0;
  27681. var i1 = 0;
  27682. var i2 = 0;
  27683. var i3 = 0;
  27684. for (index = 0; index < positions.length; index++) {
  27685. normals[index] = 0.0;
  27686. }
  27687. // indice triplet = 1 face
  27688. var nbFaces = indices.length / 3;
  27689. for (index = 0; index < nbFaces; index++) {
  27690. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  27691. i2 = indices[index * 3 + 1];
  27692. i3 = indices[index * 3 + 2];
  27693. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  27694. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27695. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27696. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  27697. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27698. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27699. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  27700. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  27701. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  27702. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27703. length = (length === 0) ? 1.0 : length;
  27704. faceNormalx /= length; // normalize this normal
  27705. faceNormaly /= length;
  27706. faceNormalz /= length;
  27707. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  27708. normals[i1 * 3 + 1] += faceNormaly;
  27709. normals[i1 * 3 + 2] += faceNormalz;
  27710. normals[i2 * 3] += faceNormalx;
  27711. normals[i2 * 3 + 1] += faceNormaly;
  27712. normals[i2 * 3 + 2] += faceNormalz;
  27713. normals[i3 * 3] += faceNormalx;
  27714. normals[i3 * 3 + 1] += faceNormaly;
  27715. normals[i3 * 3 + 2] += faceNormalz;
  27716. }
  27717. // last normalization of each normal
  27718. for (index = 0; index < normals.length / 3; index++) {
  27719. faceNormalx = normals[index * 3];
  27720. faceNormaly = normals[index * 3 + 1];
  27721. faceNormalz = normals[index * 3 + 2];
  27722. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27723. length = (length === 0) ? 1.0 : length;
  27724. faceNormalx /= length;
  27725. faceNormaly /= length;
  27726. faceNormalz /= length;
  27727. normals[index * 3] = faceNormalx;
  27728. normals[index * 3 + 1] = faceNormaly;
  27729. normals[index * 3 + 2] = faceNormalz;
  27730. }
  27731. };
  27732. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27733. var li = indices.length;
  27734. var ln = normals.length;
  27735. var i;
  27736. var n;
  27737. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27738. switch (sideOrientation) {
  27739. case BABYLON.Mesh.FRONTSIDE:
  27740. // nothing changed
  27741. break;
  27742. case BABYLON.Mesh.BACKSIDE:
  27743. var tmp;
  27744. // indices
  27745. for (i = 0; i < li; i += 3) {
  27746. tmp = indices[i];
  27747. indices[i] = indices[i + 2];
  27748. indices[i + 2] = tmp;
  27749. }
  27750. // normals
  27751. for (n = 0; n < ln; n++) {
  27752. normals[n] = -normals[n];
  27753. }
  27754. break;
  27755. case BABYLON.Mesh.DOUBLESIDE:
  27756. // positions
  27757. var lp = positions.length;
  27758. var l = lp / 3;
  27759. for (var p = 0; p < lp; p++) {
  27760. positions[lp + p] = positions[p];
  27761. }
  27762. // indices
  27763. for (i = 0; i < li; i += 3) {
  27764. indices[i + li] = indices[i + 2] + l;
  27765. indices[i + 1 + li] = indices[i + 1] + l;
  27766. indices[i + 2 + li] = indices[i] + l;
  27767. }
  27768. // normals
  27769. for (n = 0; n < ln; n++) {
  27770. normals[ln + n] = -normals[n];
  27771. }
  27772. // uvs
  27773. var lu = uvs.length;
  27774. for (var u = 0; u < lu; u++) {
  27775. uvs[u + lu] = uvs[u];
  27776. }
  27777. break;
  27778. }
  27779. };
  27780. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27781. var vertexData = new VertexData();
  27782. // positions
  27783. var positions = parsedVertexData.positions;
  27784. if (positions) {
  27785. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27786. }
  27787. // normals
  27788. var normals = parsedVertexData.normals;
  27789. if (normals) {
  27790. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27791. }
  27792. // uvs
  27793. var uvs = parsedVertexData.uvs;
  27794. if (uvs) {
  27795. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27796. }
  27797. // uv2s
  27798. var uv2s = parsedVertexData.uv2s;
  27799. if (uv2s) {
  27800. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27801. }
  27802. // uv3s
  27803. var uv3s = parsedVertexData.uv3s;
  27804. if (uv3s) {
  27805. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27806. }
  27807. // uv4s
  27808. var uv4s = parsedVertexData.uv4s;
  27809. if (uv4s) {
  27810. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27811. }
  27812. // uv5s
  27813. var uv5s = parsedVertexData.uv5s;
  27814. if (uv5s) {
  27815. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27816. }
  27817. // uv6s
  27818. var uv6s = parsedVertexData.uv6s;
  27819. if (uv6s) {
  27820. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27821. }
  27822. // colors
  27823. var colors = parsedVertexData.colors;
  27824. if (colors) {
  27825. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27826. }
  27827. // matricesIndices
  27828. var matricesIndices = parsedVertexData.matricesIndices;
  27829. if (matricesIndices) {
  27830. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27831. }
  27832. // matricesWeights
  27833. var matricesWeights = parsedVertexData.matricesWeights;
  27834. if (matricesWeights) {
  27835. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27836. }
  27837. // indices
  27838. var indices = parsedVertexData.indices;
  27839. if (indices) {
  27840. vertexData.indices = indices;
  27841. }
  27842. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27843. };
  27844. return VertexData;
  27845. })();
  27846. BABYLON.VertexData = VertexData;
  27847. })(BABYLON || (BABYLON = {}));
  27848. var BABYLON;
  27849. (function (BABYLON) {
  27850. var Tags = (function () {
  27851. function Tags() {
  27852. }
  27853. Tags.EnableFor = function (obj) {
  27854. obj._tags = obj._tags || {};
  27855. obj.hasTags = function () {
  27856. return Tags.HasTags(obj);
  27857. };
  27858. obj.addTags = function (tagsString) {
  27859. return Tags.AddTagsTo(obj, tagsString);
  27860. };
  27861. obj.removeTags = function (tagsString) {
  27862. return Tags.RemoveTagsFrom(obj, tagsString);
  27863. };
  27864. obj.matchesTagsQuery = function (tagsQuery) {
  27865. return Tags.MatchesQuery(obj, tagsQuery);
  27866. };
  27867. };
  27868. Tags.DisableFor = function (obj) {
  27869. delete obj._tags;
  27870. delete obj.hasTags;
  27871. delete obj.addTags;
  27872. delete obj.removeTags;
  27873. delete obj.matchesTagsQuery;
  27874. };
  27875. Tags.HasTags = function (obj) {
  27876. if (!obj._tags) {
  27877. return false;
  27878. }
  27879. return !BABYLON.Tools.IsEmpty(obj._tags);
  27880. };
  27881. Tags.GetTags = function (obj, asString) {
  27882. if (asString === void 0) { asString = true; }
  27883. if (!obj._tags) {
  27884. return null;
  27885. }
  27886. if (asString) {
  27887. var tagsArray = [];
  27888. for (var tag in obj._tags) {
  27889. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  27890. tagsArray.push(tag);
  27891. }
  27892. }
  27893. return tagsArray.join(" ");
  27894. }
  27895. else {
  27896. return obj._tags;
  27897. }
  27898. };
  27899. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27900. // a tag cannot start with '||', '&&', and '!'
  27901. // it cannot contain whitespaces
  27902. Tags.AddTagsTo = function (obj, tagsString) {
  27903. if (!tagsString) {
  27904. return;
  27905. }
  27906. if (typeof tagsString !== "string") {
  27907. return;
  27908. }
  27909. var tags = tagsString.split(" ");
  27910. for (var t in tags) {
  27911. Tags._AddTagTo(obj, tags[t]);
  27912. }
  27913. };
  27914. Tags._AddTagTo = function (obj, tag) {
  27915. tag = tag.trim();
  27916. if (tag === "" || tag === "true" || tag === "false") {
  27917. return;
  27918. }
  27919. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27920. return;
  27921. }
  27922. Tags.EnableFor(obj);
  27923. obj._tags[tag] = true;
  27924. };
  27925. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27926. if (!Tags.HasTags(obj)) {
  27927. return;
  27928. }
  27929. var tags = tagsString.split(" ");
  27930. for (var t in tags) {
  27931. Tags._RemoveTagFrom(obj, tags[t]);
  27932. }
  27933. };
  27934. Tags._RemoveTagFrom = function (obj, tag) {
  27935. delete obj._tags[tag];
  27936. };
  27937. Tags.MatchesQuery = function (obj, tagsQuery) {
  27938. if (tagsQuery === undefined) {
  27939. return true;
  27940. }
  27941. if (tagsQuery === "") {
  27942. return Tags.HasTags(obj);
  27943. }
  27944. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27945. };
  27946. return Tags;
  27947. })();
  27948. BABYLON.Tags = Tags;
  27949. })(BABYLON || (BABYLON = {}));
  27950. var BABYLON;
  27951. (function (BABYLON) {
  27952. var Internals;
  27953. (function (Internals) {
  27954. var AndOrNotEvaluator = (function () {
  27955. function AndOrNotEvaluator() {
  27956. }
  27957. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27958. if (!query.match(/\([^\(\)]*\)/g)) {
  27959. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27960. }
  27961. else {
  27962. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27963. // remove parenthesis
  27964. r = r.slice(1, r.length - 1);
  27965. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27966. });
  27967. }
  27968. if (query === "true") {
  27969. return true;
  27970. }
  27971. if (query === "false") {
  27972. return false;
  27973. }
  27974. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27975. };
  27976. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27977. evaluateCallback = evaluateCallback || (function (r) {
  27978. return r === "true" ? true : false;
  27979. });
  27980. var result;
  27981. var or = parenthesisContent.split("||");
  27982. for (var i in or) {
  27983. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27984. var and = ori.split("&&");
  27985. if (and.length > 1) {
  27986. for (var j = 0; j < and.length; ++j) {
  27987. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27988. if (andj !== "true" && andj !== "false") {
  27989. if (andj[0] === "!") {
  27990. result = !evaluateCallback(andj.substring(1));
  27991. }
  27992. else {
  27993. result = evaluateCallback(andj);
  27994. }
  27995. }
  27996. else {
  27997. result = andj === "true" ? true : false;
  27998. }
  27999. if (!result) {
  28000. ori = "false";
  28001. break;
  28002. }
  28003. }
  28004. }
  28005. if (result || ori === "true") {
  28006. result = true;
  28007. break;
  28008. }
  28009. // result equals false (or undefined)
  28010. if (ori !== "true" && ori !== "false") {
  28011. if (ori[0] === "!") {
  28012. result = !evaluateCallback(ori.substring(1));
  28013. }
  28014. else {
  28015. result = evaluateCallback(ori);
  28016. }
  28017. }
  28018. else {
  28019. result = ori === "true" ? true : false;
  28020. }
  28021. }
  28022. // the whole parenthesis scope is replaced by 'true' or 'false'
  28023. return result ? "true" : "false";
  28024. };
  28025. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  28026. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  28027. // remove whitespaces
  28028. r = r.replace(/[\s]/g, function () { return ""; });
  28029. return r.length % 2 ? "!" : "";
  28030. });
  28031. booleanString = booleanString.trim();
  28032. if (booleanString === "!true") {
  28033. booleanString = "false";
  28034. }
  28035. else if (booleanString === "!false") {
  28036. booleanString = "true";
  28037. }
  28038. return booleanString;
  28039. };
  28040. return AndOrNotEvaluator;
  28041. })();
  28042. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  28043. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28044. })(BABYLON || (BABYLON = {}));
  28045. var BABYLON;
  28046. (function (BABYLON) {
  28047. var PostProcessRenderPass = (function () {
  28048. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  28049. this._enabled = true;
  28050. this._refCount = 0;
  28051. this._name = name;
  28052. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  28053. this.setRenderList(renderList);
  28054. this._renderTexture.onBeforeRender = beforeRender;
  28055. this._renderTexture.onAfterRender = afterRender;
  28056. this._scene = scene;
  28057. this._renderList = renderList;
  28058. }
  28059. // private
  28060. PostProcessRenderPass.prototype._incRefCount = function () {
  28061. if (this._refCount === 0) {
  28062. this._scene.customRenderTargets.push(this._renderTexture);
  28063. }
  28064. return ++this._refCount;
  28065. };
  28066. PostProcessRenderPass.prototype._decRefCount = function () {
  28067. this._refCount--;
  28068. if (this._refCount <= 0) {
  28069. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  28070. }
  28071. return this._refCount;
  28072. };
  28073. PostProcessRenderPass.prototype._update = function () {
  28074. this.setRenderList(this._renderList);
  28075. };
  28076. // public
  28077. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  28078. this._renderTexture.renderList = renderList;
  28079. };
  28080. PostProcessRenderPass.prototype.getRenderTexture = function () {
  28081. return this._renderTexture;
  28082. };
  28083. return PostProcessRenderPass;
  28084. })();
  28085. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  28086. })(BABYLON || (BABYLON = {}));
  28087. var BABYLON;
  28088. (function (BABYLON) {
  28089. var PostProcessRenderEffect = (function () {
  28090. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  28091. this._engine = engine;
  28092. this._name = name;
  28093. this._singleInstance = singleInstance || true;
  28094. this._getPostProcess = getPostProcess;
  28095. this._cameras = [];
  28096. this._indicesForCamera = [];
  28097. this._postProcesses = {};
  28098. this._renderPasses = {};
  28099. this._renderEffectAsPasses = {};
  28100. }
  28101. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  28102. get: function () {
  28103. for (var index in this._postProcesses) {
  28104. if (!this._postProcesses[index].isSupported) {
  28105. return false;
  28106. }
  28107. }
  28108. return true;
  28109. },
  28110. enumerable: true,
  28111. configurable: true
  28112. });
  28113. PostProcessRenderEffect.prototype._update = function () {
  28114. for (var renderPassName in this._renderPasses) {
  28115. this._renderPasses[renderPassName]._update();
  28116. }
  28117. };
  28118. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  28119. this._renderPasses[renderPass._name] = renderPass;
  28120. this._linkParameters();
  28121. };
  28122. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  28123. delete this._renderPasses[renderPass._name];
  28124. this._linkParameters();
  28125. };
  28126. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  28127. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  28128. this._linkParameters();
  28129. };
  28130. PostProcessRenderEffect.prototype.getPass = function (passName) {
  28131. for (var renderPassName in this._renderPasses) {
  28132. if (renderPassName === passName) {
  28133. return this._renderPasses[passName];
  28134. }
  28135. }
  28136. };
  28137. PostProcessRenderEffect.prototype.emptyPasses = function () {
  28138. this._renderPasses = {};
  28139. this._linkParameters();
  28140. };
  28141. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  28142. var cameraKey;
  28143. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28144. for (var i = 0; i < _cam.length; i++) {
  28145. var camera = _cam[i];
  28146. var cameraName = camera.name;
  28147. if (this._singleInstance) {
  28148. cameraKey = 0;
  28149. }
  28150. else {
  28151. cameraKey = cameraName;
  28152. }
  28153. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  28154. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  28155. if (!this._indicesForCamera[cameraName]) {
  28156. this._indicesForCamera[cameraName] = [];
  28157. }
  28158. this._indicesForCamera[cameraName].push(index);
  28159. if (this._cameras.indexOf(camera) === -1) {
  28160. this._cameras[cameraName] = camera;
  28161. }
  28162. for (var passName in this._renderPasses) {
  28163. this._renderPasses[passName]._incRefCount();
  28164. }
  28165. }
  28166. this._linkParameters();
  28167. };
  28168. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  28169. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28170. for (var i = 0; i < _cam.length; i++) {
  28171. var camera = _cam[i];
  28172. var cameraName = camera.name;
  28173. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28174. var index = this._cameras.indexOf(cameraName);
  28175. this._indicesForCamera.splice(index, 1);
  28176. this._cameras.splice(index, 1);
  28177. for (var passName in this._renderPasses) {
  28178. this._renderPasses[passName]._decRefCount();
  28179. }
  28180. }
  28181. };
  28182. PostProcessRenderEffect.prototype._enable = function (cameras) {
  28183. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28184. for (var i = 0; i < _cam.length; i++) {
  28185. var camera = _cam[i];
  28186. var cameraName = camera.name;
  28187. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  28188. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  28189. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  28190. }
  28191. }
  28192. for (var passName in this._renderPasses) {
  28193. this._renderPasses[passName]._incRefCount();
  28194. }
  28195. }
  28196. };
  28197. PostProcessRenderEffect.prototype._disable = function (cameras) {
  28198. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28199. for (var i = 0; i < _cam.length; i++) {
  28200. var camera = _cam[i];
  28201. var cameraName = camera.Name;
  28202. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28203. for (var passName in this._renderPasses) {
  28204. this._renderPasses[passName]._decRefCount();
  28205. }
  28206. }
  28207. };
  28208. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  28209. if (this._singleInstance) {
  28210. return this._postProcesses[0];
  28211. }
  28212. else {
  28213. return this._postProcesses[camera.name];
  28214. }
  28215. };
  28216. PostProcessRenderEffect.prototype._linkParameters = function () {
  28217. var _this = this;
  28218. for (var index in this._postProcesses) {
  28219. if (this.applyParameters) {
  28220. this.applyParameters(this._postProcesses[index]);
  28221. }
  28222. this._postProcesses[index].onBeforeRender = function (effect) {
  28223. _this._linkTextures(effect);
  28224. };
  28225. }
  28226. };
  28227. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  28228. for (var renderPassName in this._renderPasses) {
  28229. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  28230. }
  28231. for (var renderEffectName in this._renderEffectAsPasses) {
  28232. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  28233. }
  28234. };
  28235. return PostProcessRenderEffect;
  28236. })();
  28237. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  28238. })(BABYLON || (BABYLON = {}));
  28239. var BABYLON;
  28240. (function (BABYLON) {
  28241. var PostProcessRenderPipeline = (function () {
  28242. function PostProcessRenderPipeline(engine, name) {
  28243. this._engine = engine;
  28244. this._name = name;
  28245. this._renderEffects = {};
  28246. this._renderEffectsForIsolatedPass = {};
  28247. this._cameras = [];
  28248. }
  28249. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  28250. get: function () {
  28251. for (var renderEffectName in this._renderEffects) {
  28252. if (!this._renderEffects[renderEffectName].isSupported) {
  28253. return false;
  28254. }
  28255. }
  28256. return true;
  28257. },
  28258. enumerable: true,
  28259. configurable: true
  28260. });
  28261. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  28262. this._renderEffects[renderEffect._name] = renderEffect;
  28263. };
  28264. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  28265. var renderEffects = this._renderEffects[renderEffectName];
  28266. if (!renderEffects) {
  28267. return;
  28268. }
  28269. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28270. };
  28271. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  28272. var renderEffects = this._renderEffects[renderEffectName];
  28273. if (!renderEffects) {
  28274. return;
  28275. }
  28276. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28277. };
  28278. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  28279. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28280. var indicesToDelete = [];
  28281. var i;
  28282. for (i = 0; i < _cam.length; i++) {
  28283. var camera = _cam[i];
  28284. var cameraName = camera.name;
  28285. if (this._cameras.indexOf(camera) === -1) {
  28286. this._cameras[cameraName] = camera;
  28287. }
  28288. else if (unique) {
  28289. indicesToDelete.push(i);
  28290. }
  28291. }
  28292. for (i = 0; i < indicesToDelete.length; i++) {
  28293. cameras.splice(indicesToDelete[i], 1);
  28294. }
  28295. for (var renderEffectName in this._renderEffects) {
  28296. this._renderEffects[renderEffectName]._attachCameras(_cam);
  28297. }
  28298. };
  28299. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  28300. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28301. for (var renderEffectName in this._renderEffects) {
  28302. this._renderEffects[renderEffectName]._detachCameras(_cam);
  28303. }
  28304. for (var i = 0; i < _cam.length; i++) {
  28305. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  28306. }
  28307. };
  28308. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  28309. var _this = this;
  28310. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28311. var pass = null;
  28312. var renderEffectName;
  28313. for (renderEffectName in this._renderEffects) {
  28314. pass = this._renderEffects[renderEffectName].getPass(passName);
  28315. if (pass != null) {
  28316. break;
  28317. }
  28318. }
  28319. if (pass === null) {
  28320. return;
  28321. }
  28322. for (renderEffectName in this._renderEffects) {
  28323. this._renderEffects[renderEffectName]._disable(_cam);
  28324. }
  28325. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  28326. for (var i = 0; i < _cam.length; i++) {
  28327. var camera = _cam[i];
  28328. var cameraName = camera.name;
  28329. 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); });
  28330. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  28331. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  28332. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  28333. }
  28334. };
  28335. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  28336. var _this = this;
  28337. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28338. for (var i = 0; i < _cam.length; i++) {
  28339. var camera = _cam[i];
  28340. var cameraName = camera.name;
  28341. 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); });
  28342. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  28343. }
  28344. for (var renderEffectName in this._renderEffects) {
  28345. this._renderEffects[renderEffectName]._enable(_cam);
  28346. }
  28347. };
  28348. PostProcessRenderPipeline.prototype._update = function () {
  28349. for (var renderEffectName in this._renderEffects) {
  28350. this._renderEffects[renderEffectName]._update();
  28351. }
  28352. for (var i = 0; i < this._cameras.length; i++) {
  28353. var cameraName = this._cameras[i].name;
  28354. if (this._renderEffectsForIsolatedPass[cameraName]) {
  28355. this._renderEffectsForIsolatedPass[cameraName]._update();
  28356. }
  28357. }
  28358. };
  28359. PostProcessRenderPipeline.prototype.dispose = function () {
  28360. // Must be implemented by children
  28361. };
  28362. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  28363. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  28364. return PostProcessRenderPipeline;
  28365. })();
  28366. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  28367. })(BABYLON || (BABYLON = {}));
  28368. var BABYLON;
  28369. (function (BABYLON) {
  28370. var PostProcessRenderPipelineManager = (function () {
  28371. function PostProcessRenderPipelineManager() {
  28372. this._renderPipelines = {};
  28373. }
  28374. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  28375. this._renderPipelines[renderPipeline._name] = renderPipeline;
  28376. };
  28377. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  28378. var renderPipeline = this._renderPipelines[renderPipelineName];
  28379. if (!renderPipeline) {
  28380. return;
  28381. }
  28382. renderPipeline._attachCameras(cameras, unique);
  28383. };
  28384. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  28385. var renderPipeline = this._renderPipelines[renderPipelineName];
  28386. if (!renderPipeline) {
  28387. return;
  28388. }
  28389. renderPipeline._detachCameras(cameras);
  28390. };
  28391. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28392. var renderPipeline = this._renderPipelines[renderPipelineName];
  28393. if (!renderPipeline) {
  28394. return;
  28395. }
  28396. renderPipeline._enableEffect(renderEffectName, cameras);
  28397. };
  28398. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28399. var renderPipeline = this._renderPipelines[renderPipelineName];
  28400. if (!renderPipeline) {
  28401. return;
  28402. }
  28403. renderPipeline._disableEffect(renderEffectName, cameras);
  28404. };
  28405. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  28406. var renderPipeline = this._renderPipelines[renderPipelineName];
  28407. if (!renderPipeline) {
  28408. return;
  28409. }
  28410. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  28411. };
  28412. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  28413. var renderPipeline = this._renderPipelines[renderPipelineName];
  28414. if (!renderPipeline) {
  28415. return;
  28416. }
  28417. renderPipeline._disableDisplayOnlyPass(cameras);
  28418. };
  28419. PostProcessRenderPipelineManager.prototype.update = function () {
  28420. for (var renderPipelineName in this._renderPipelines) {
  28421. var pipeline = this._renderPipelines[renderPipelineName];
  28422. if (!pipeline.isSupported) {
  28423. pipeline.dispose();
  28424. delete this._renderPipelines[renderPipelineName];
  28425. }
  28426. else {
  28427. pipeline._update();
  28428. }
  28429. }
  28430. };
  28431. return PostProcessRenderPipelineManager;
  28432. })();
  28433. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  28434. })(BABYLON || (BABYLON = {}));
  28435. var BABYLON;
  28436. (function (BABYLON) {
  28437. var BoundingBoxRenderer = (function () {
  28438. function BoundingBoxRenderer(scene) {
  28439. this.frontColor = new BABYLON.Color3(1, 1, 1);
  28440. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  28441. this.showBackLines = true;
  28442. this.renderList = new BABYLON.SmartArray(32);
  28443. this._scene = scene;
  28444. }
  28445. BoundingBoxRenderer.prototype._prepareRessources = function () {
  28446. if (this._colorShader) {
  28447. return;
  28448. }
  28449. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  28450. attributes: ["position"],
  28451. uniforms: ["worldViewProjection", "color"]
  28452. });
  28453. var engine = this._scene.getEngine();
  28454. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  28455. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  28456. 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]);
  28457. };
  28458. BoundingBoxRenderer.prototype.reset = function () {
  28459. this.renderList.reset();
  28460. };
  28461. BoundingBoxRenderer.prototype.render = function () {
  28462. if (this.renderList.length === 0) {
  28463. return;
  28464. }
  28465. this._prepareRessources();
  28466. if (!this._colorShader.isReady()) {
  28467. return;
  28468. }
  28469. var engine = this._scene.getEngine();
  28470. engine.setDepthWrite(false);
  28471. this._colorShader._preBind();
  28472. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  28473. var boundingBox = this.renderList.data[boundingBoxIndex];
  28474. var min = boundingBox.minimum;
  28475. var max = boundingBox.maximum;
  28476. var diff = max.subtract(min);
  28477. var median = min.add(diff.scale(0.5));
  28478. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  28479. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  28480. .multiply(boundingBox.getWorldMatrix());
  28481. // VBOs
  28482. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  28483. if (this.showBackLines) {
  28484. // Back
  28485. engine.setDepthFunctionToGreaterOrEqual();
  28486. this._scene.resetCachedMaterial();
  28487. this._colorShader.setColor4("color", this.backColor.toColor4());
  28488. this._colorShader.bind(worldMatrix);
  28489. // Draw order
  28490. engine.draw(false, 0, 24);
  28491. }
  28492. // Front
  28493. engine.setDepthFunctionToLess();
  28494. this._scene.resetCachedMaterial();
  28495. this._colorShader.setColor4("color", this.frontColor.toColor4());
  28496. this._colorShader.bind(worldMatrix);
  28497. // Draw order
  28498. engine.draw(false, 0, 24);
  28499. }
  28500. this._colorShader.unbind();
  28501. engine.setDepthFunctionToLessOrEqual();
  28502. engine.setDepthWrite(true);
  28503. };
  28504. BoundingBoxRenderer.prototype.dispose = function () {
  28505. if (!this._colorShader) {
  28506. return;
  28507. }
  28508. this._colorShader.dispose();
  28509. this._vb.dispose();
  28510. this._scene.getEngine()._releaseBuffer(this._ib);
  28511. };
  28512. return BoundingBoxRenderer;
  28513. })();
  28514. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  28515. })(BABYLON || (BABYLON = {}));
  28516. var BABYLON;
  28517. (function (BABYLON) {
  28518. var Condition = (function () {
  28519. function Condition(actionManager) {
  28520. this._actionManager = actionManager;
  28521. }
  28522. Condition.prototype.isValid = function () {
  28523. return true;
  28524. };
  28525. Condition.prototype._getProperty = function (propertyPath) {
  28526. return this._actionManager._getProperty(propertyPath);
  28527. };
  28528. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  28529. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28530. };
  28531. return Condition;
  28532. })();
  28533. BABYLON.Condition = Condition;
  28534. var ValueCondition = (function (_super) {
  28535. __extends(ValueCondition, _super);
  28536. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  28537. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  28538. _super.call(this, actionManager);
  28539. this.propertyPath = propertyPath;
  28540. this.value = value;
  28541. this.operator = operator;
  28542. this._target = this._getEffectiveTarget(target, this.propertyPath);
  28543. this._property = this._getProperty(this.propertyPath);
  28544. }
  28545. Object.defineProperty(ValueCondition, "IsEqual", {
  28546. get: function () {
  28547. return ValueCondition._IsEqual;
  28548. },
  28549. enumerable: true,
  28550. configurable: true
  28551. });
  28552. Object.defineProperty(ValueCondition, "IsDifferent", {
  28553. get: function () {
  28554. return ValueCondition._IsDifferent;
  28555. },
  28556. enumerable: true,
  28557. configurable: true
  28558. });
  28559. Object.defineProperty(ValueCondition, "IsGreater", {
  28560. get: function () {
  28561. return ValueCondition._IsGreater;
  28562. },
  28563. enumerable: true,
  28564. configurable: true
  28565. });
  28566. Object.defineProperty(ValueCondition, "IsLesser", {
  28567. get: function () {
  28568. return ValueCondition._IsLesser;
  28569. },
  28570. enumerable: true,
  28571. configurable: true
  28572. });
  28573. // Methods
  28574. ValueCondition.prototype.isValid = function () {
  28575. switch (this.operator) {
  28576. case ValueCondition.IsGreater:
  28577. return this._target[this._property] > this.value;
  28578. case ValueCondition.IsLesser:
  28579. return this._target[this._property] < this.value;
  28580. case ValueCondition.IsEqual:
  28581. case ValueCondition.IsDifferent:
  28582. var check;
  28583. if (this.value.equals) {
  28584. check = this.value.equals(this._target[this._property]);
  28585. }
  28586. else {
  28587. check = this.value === this._target[this._property];
  28588. }
  28589. return this.operator === ValueCondition.IsEqual ? check : !check;
  28590. }
  28591. return false;
  28592. };
  28593. // Statics
  28594. ValueCondition._IsEqual = 0;
  28595. ValueCondition._IsDifferent = 1;
  28596. ValueCondition._IsGreater = 2;
  28597. ValueCondition._IsLesser = 3;
  28598. return ValueCondition;
  28599. })(Condition);
  28600. BABYLON.ValueCondition = ValueCondition;
  28601. var PredicateCondition = (function (_super) {
  28602. __extends(PredicateCondition, _super);
  28603. function PredicateCondition(actionManager, predicate) {
  28604. _super.call(this, actionManager);
  28605. this.predicate = predicate;
  28606. }
  28607. PredicateCondition.prototype.isValid = function () {
  28608. return this.predicate();
  28609. };
  28610. return PredicateCondition;
  28611. })(Condition);
  28612. BABYLON.PredicateCondition = PredicateCondition;
  28613. var StateCondition = (function (_super) {
  28614. __extends(StateCondition, _super);
  28615. function StateCondition(actionManager, target, value) {
  28616. _super.call(this, actionManager);
  28617. this.value = value;
  28618. this._target = target;
  28619. }
  28620. // Methods
  28621. StateCondition.prototype.isValid = function () {
  28622. return this._target.state === this.value;
  28623. };
  28624. return StateCondition;
  28625. })(Condition);
  28626. BABYLON.StateCondition = StateCondition;
  28627. })(BABYLON || (BABYLON = {}));
  28628. var BABYLON;
  28629. (function (BABYLON) {
  28630. var Action = (function () {
  28631. function Action(triggerOptions, condition) {
  28632. this.triggerOptions = triggerOptions;
  28633. if (triggerOptions.parameter) {
  28634. this.trigger = triggerOptions.trigger;
  28635. this._triggerParameter = triggerOptions.parameter;
  28636. }
  28637. else {
  28638. this.trigger = triggerOptions;
  28639. }
  28640. this._nextActiveAction = this;
  28641. this._condition = condition;
  28642. }
  28643. // Methods
  28644. Action.prototype._prepare = function () {
  28645. };
  28646. Action.prototype.getTriggerParameter = function () {
  28647. return this._triggerParameter;
  28648. };
  28649. Action.prototype._executeCurrent = function (evt) {
  28650. if (this._nextActiveAction._condition) {
  28651. var condition = this._nextActiveAction._condition;
  28652. var currentRenderId = this._actionManager.getScene().getRenderId();
  28653. // We cache the current evaluation for the current frame
  28654. if (condition._evaluationId === currentRenderId) {
  28655. if (!condition._currentResult) {
  28656. return;
  28657. }
  28658. }
  28659. else {
  28660. condition._evaluationId = currentRenderId;
  28661. if (!condition.isValid()) {
  28662. condition._currentResult = false;
  28663. return;
  28664. }
  28665. condition._currentResult = true;
  28666. }
  28667. }
  28668. this._nextActiveAction.execute(evt);
  28669. this.skipToNextActiveAction();
  28670. };
  28671. Action.prototype.execute = function (evt) {
  28672. };
  28673. Action.prototype.skipToNextActiveAction = function () {
  28674. if (this._nextActiveAction._child) {
  28675. if (!this._nextActiveAction._child._actionManager) {
  28676. this._nextActiveAction._child._actionManager = this._actionManager;
  28677. }
  28678. this._nextActiveAction = this._nextActiveAction._child;
  28679. }
  28680. else {
  28681. this._nextActiveAction = this;
  28682. }
  28683. };
  28684. Action.prototype.then = function (action) {
  28685. this._child = action;
  28686. action._actionManager = this._actionManager;
  28687. action._prepare();
  28688. return action;
  28689. };
  28690. Action.prototype._getProperty = function (propertyPath) {
  28691. return this._actionManager._getProperty(propertyPath);
  28692. };
  28693. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28694. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28695. };
  28696. return Action;
  28697. })();
  28698. BABYLON.Action = Action;
  28699. })(BABYLON || (BABYLON = {}));
  28700. var BABYLON;
  28701. (function (BABYLON) {
  28702. /**
  28703. * ActionEvent is the event beint sent when an action is triggered.
  28704. */
  28705. var ActionEvent = (function () {
  28706. /**
  28707. * @constructor
  28708. * @param source The mesh or sprite that triggered the action.
  28709. * @param pointerX The X mouse cursor position at the time of the event
  28710. * @param pointerY The Y mouse cursor position at the time of the event
  28711. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28712. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28713. */
  28714. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28715. this.source = source;
  28716. this.pointerX = pointerX;
  28717. this.pointerY = pointerY;
  28718. this.meshUnderPointer = meshUnderPointer;
  28719. this.sourceEvent = sourceEvent;
  28720. this.additionalData = additionalData;
  28721. }
  28722. /**
  28723. * Helper function to auto-create an ActionEvent from a source mesh.
  28724. * @param source The source mesh that triggered the event
  28725. * @param evt {Event} The original (browser) event
  28726. */
  28727. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28728. var scene = source.getScene();
  28729. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28730. };
  28731. /**
  28732. * Helper function to auto-create an ActionEvent from a source mesh.
  28733. * @param source The source sprite that triggered the event
  28734. * @param scene Scene associated with the sprite
  28735. * @param evt {Event} The original (browser) event
  28736. */
  28737. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  28738. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28739. };
  28740. /**
  28741. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28742. * @param scene the scene where the event occurred
  28743. * @param evt {Event} The original (browser) event
  28744. */
  28745. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28746. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28747. };
  28748. return ActionEvent;
  28749. })();
  28750. BABYLON.ActionEvent = ActionEvent;
  28751. /**
  28752. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28753. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28754. */
  28755. var ActionManager = (function () {
  28756. function ActionManager(scene) {
  28757. // Members
  28758. this.actions = new Array();
  28759. this._scene = scene;
  28760. scene._actionManagers.push(this);
  28761. }
  28762. Object.defineProperty(ActionManager, "NothingTrigger", {
  28763. get: function () {
  28764. return ActionManager._NothingTrigger;
  28765. },
  28766. enumerable: true,
  28767. configurable: true
  28768. });
  28769. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28770. get: function () {
  28771. return ActionManager._OnPickTrigger;
  28772. },
  28773. enumerable: true,
  28774. configurable: true
  28775. });
  28776. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28777. get: function () {
  28778. return ActionManager._OnLeftPickTrigger;
  28779. },
  28780. enumerable: true,
  28781. configurable: true
  28782. });
  28783. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28784. get: function () {
  28785. return ActionManager._OnRightPickTrigger;
  28786. },
  28787. enumerable: true,
  28788. configurable: true
  28789. });
  28790. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28791. get: function () {
  28792. return ActionManager._OnCenterPickTrigger;
  28793. },
  28794. enumerable: true,
  28795. configurable: true
  28796. });
  28797. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  28798. get: function () {
  28799. return ActionManager._OnPickDownTrigger;
  28800. },
  28801. enumerable: true,
  28802. configurable: true
  28803. });
  28804. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28805. get: function () {
  28806. return ActionManager._OnPickUpTrigger;
  28807. },
  28808. enumerable: true,
  28809. configurable: true
  28810. });
  28811. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  28812. /// This trigger will only be raised if you also declared a OnPickDown
  28813. get: function () {
  28814. return ActionManager._OnPickOutTrigger;
  28815. },
  28816. enumerable: true,
  28817. configurable: true
  28818. });
  28819. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  28820. get: function () {
  28821. return ActionManager._OnLongPressTrigger;
  28822. },
  28823. enumerable: true,
  28824. configurable: true
  28825. });
  28826. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28827. get: function () {
  28828. return ActionManager._OnPointerOverTrigger;
  28829. },
  28830. enumerable: true,
  28831. configurable: true
  28832. });
  28833. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28834. get: function () {
  28835. return ActionManager._OnPointerOutTrigger;
  28836. },
  28837. enumerable: true,
  28838. configurable: true
  28839. });
  28840. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28841. get: function () {
  28842. return ActionManager._OnEveryFrameTrigger;
  28843. },
  28844. enumerable: true,
  28845. configurable: true
  28846. });
  28847. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28848. get: function () {
  28849. return ActionManager._OnIntersectionEnterTrigger;
  28850. },
  28851. enumerable: true,
  28852. configurable: true
  28853. });
  28854. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28855. get: function () {
  28856. return ActionManager._OnIntersectionExitTrigger;
  28857. },
  28858. enumerable: true,
  28859. configurable: true
  28860. });
  28861. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28862. get: function () {
  28863. return ActionManager._OnKeyDownTrigger;
  28864. },
  28865. enumerable: true,
  28866. configurable: true
  28867. });
  28868. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28869. get: function () {
  28870. return ActionManager._OnKeyUpTrigger;
  28871. },
  28872. enumerable: true,
  28873. configurable: true
  28874. });
  28875. // Methods
  28876. ActionManager.prototype.dispose = function () {
  28877. var index = this._scene._actionManagers.indexOf(this);
  28878. if (index > -1) {
  28879. this._scene._actionManagers.splice(index, 1);
  28880. }
  28881. };
  28882. ActionManager.prototype.getScene = function () {
  28883. return this._scene;
  28884. };
  28885. /**
  28886. * Does this action manager handles actions of any of the given triggers
  28887. * @param {number[]} triggers - the triggers to be tested
  28888. * @return {boolean} whether one (or more) of the triggers is handeled
  28889. */
  28890. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28891. for (var index = 0; index < this.actions.length; index++) {
  28892. var action = this.actions[index];
  28893. if (triggers.indexOf(action.trigger) > -1) {
  28894. return true;
  28895. }
  28896. }
  28897. return false;
  28898. };
  28899. /**
  28900. * Does this action manager handles actions of a given trigger
  28901. * @param {number} trigger - the trigger to be tested
  28902. * @return {boolean} whether the trigger is handeled
  28903. */
  28904. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28905. for (var index = 0; index < this.actions.length; index++) {
  28906. var action = this.actions[index];
  28907. if (action.trigger === trigger) {
  28908. return true;
  28909. }
  28910. }
  28911. return false;
  28912. };
  28913. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28914. /**
  28915. * Does this action manager has pointer triggers
  28916. * @return {boolean} whether or not it has pointer triggers
  28917. */
  28918. get: function () {
  28919. for (var index = 0; index < this.actions.length; index++) {
  28920. var action = this.actions[index];
  28921. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28922. return true;
  28923. }
  28924. }
  28925. return false;
  28926. },
  28927. enumerable: true,
  28928. configurable: true
  28929. });
  28930. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28931. /**
  28932. * Does this action manager has pick triggers
  28933. * @return {boolean} whether or not it has pick triggers
  28934. */
  28935. get: function () {
  28936. for (var index = 0; index < this.actions.length; index++) {
  28937. var action = this.actions[index];
  28938. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  28939. return true;
  28940. }
  28941. }
  28942. return false;
  28943. },
  28944. enumerable: true,
  28945. configurable: true
  28946. });
  28947. /**
  28948. * Registers an action to this action manager
  28949. * @param {BABYLON.Action} action - the action to be registered
  28950. * @return {BABYLON.Action} the action amended (prepared) after registration
  28951. */
  28952. ActionManager.prototype.registerAction = function (action) {
  28953. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28954. if (this.getScene().actionManager !== this) {
  28955. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28956. return null;
  28957. }
  28958. }
  28959. this.actions.push(action);
  28960. action._actionManager = this;
  28961. action._prepare();
  28962. return action;
  28963. };
  28964. /**
  28965. * Process a specific trigger
  28966. * @param {number} trigger - the trigger to process
  28967. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28968. */
  28969. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28970. for (var index = 0; index < this.actions.length; index++) {
  28971. var action = this.actions[index];
  28972. if (action.trigger === trigger) {
  28973. if (trigger === ActionManager.OnKeyUpTrigger
  28974. || trigger === ActionManager.OnKeyDownTrigger) {
  28975. var parameter = action.getTriggerParameter();
  28976. if (parameter) {
  28977. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28978. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28979. if (actualkey !== parameter.toLowerCase()) {
  28980. continue;
  28981. }
  28982. }
  28983. }
  28984. action._executeCurrent(evt);
  28985. }
  28986. }
  28987. };
  28988. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28989. var properties = propertyPath.split(".");
  28990. for (var index = 0; index < properties.length - 1; index++) {
  28991. target = target[properties[index]];
  28992. }
  28993. return target;
  28994. };
  28995. ActionManager.prototype._getProperty = function (propertyPath) {
  28996. var properties = propertyPath.split(".");
  28997. return properties[properties.length - 1];
  28998. };
  28999. ActionManager.Parse = function (parsedActions, object, scene) {
  29000. var actionManager = new BABYLON.ActionManager(scene);
  29001. if (object === null)
  29002. scene.actionManager = actionManager;
  29003. else
  29004. object.actionManager = actionManager;
  29005. // instanciate a new object
  29006. var instanciate = function (name, params) {
  29007. var newInstance = Object.create(BABYLON[name].prototype);
  29008. newInstance.constructor.apply(newInstance, params);
  29009. return newInstance;
  29010. };
  29011. var parseParameter = function (name, value, target, propertyPath) {
  29012. if (propertyPath === null) {
  29013. // String, boolean or float
  29014. var floatValue = parseFloat(value);
  29015. if (value === "true" || value === "false")
  29016. return value === "true";
  29017. else
  29018. return isNaN(floatValue) ? value : floatValue;
  29019. }
  29020. var effectiveTarget = propertyPath.split(".");
  29021. var values = value.split(",");
  29022. // Get effective Target
  29023. for (var i = 0; i < effectiveTarget.length; i++) {
  29024. target = target[effectiveTarget[i]];
  29025. }
  29026. // Return appropriate value with its type
  29027. if (typeof (target) === "boolean")
  29028. return values[0] === "true";
  29029. if (typeof (target) === "string")
  29030. return values[0];
  29031. // Parameters with multiple values such as Vector3 etc.
  29032. var split = new Array();
  29033. for (var i = 0; i < values.length; i++)
  29034. split.push(parseFloat(values[i]));
  29035. if (target instanceof BABYLON.Vector3)
  29036. return BABYLON.Vector3.FromArray(split);
  29037. if (target instanceof BABYLON.Vector4)
  29038. return BABYLON.Vector4.FromArray(split);
  29039. if (target instanceof BABYLON.Color3)
  29040. return BABYLON.Color3.FromArray(split);
  29041. if (target instanceof BABYLON.Color4)
  29042. return BABYLON.Color4.FromArray(split);
  29043. return parseFloat(values[0]);
  29044. };
  29045. // traverse graph per trigger
  29046. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  29047. if (combineArray === void 0) { combineArray = null; }
  29048. if (parsedAction.detached)
  29049. return;
  29050. var parameters = new Array();
  29051. var target = null;
  29052. var propertyPath = null;
  29053. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  29054. // Parameters
  29055. if (parsedAction.type === 2)
  29056. parameters.push(actionManager);
  29057. else
  29058. parameters.push(trigger);
  29059. if (combine) {
  29060. var actions = new Array();
  29061. for (var j = 0; j < parsedAction.combine.length; j++) {
  29062. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  29063. }
  29064. parameters.push(actions);
  29065. }
  29066. else {
  29067. for (var i = 0; i < parsedAction.properties.length; i++) {
  29068. var value = parsedAction.properties[i].value;
  29069. var name = parsedAction.properties[i].name;
  29070. var targetType = parsedAction.properties[i].targetType;
  29071. if (name === "target")
  29072. if (targetType !== null && targetType === "SceneProperties")
  29073. value = target = scene;
  29074. else
  29075. value = target = scene.getNodeByName(value);
  29076. else if (name === "parent")
  29077. value = scene.getNodeByName(value);
  29078. else if (name === "sound")
  29079. value = scene.getSoundByName(value);
  29080. else if (name !== "propertyPath") {
  29081. if (parsedAction.type === 2 && name === "operator")
  29082. value = BABYLON.ValueCondition[value];
  29083. else
  29084. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  29085. }
  29086. else {
  29087. propertyPath = value;
  29088. }
  29089. parameters.push(value);
  29090. }
  29091. }
  29092. if (combineArray === null) {
  29093. parameters.push(condition);
  29094. }
  29095. else {
  29096. parameters.push(null);
  29097. }
  29098. // If interpolate value action
  29099. if (parsedAction.name === "InterpolateValueAction") {
  29100. var param = parameters[parameters.length - 2];
  29101. parameters[parameters.length - 1] = param;
  29102. parameters[parameters.length - 2] = condition;
  29103. }
  29104. // Action or condition(s) and not CombineAction
  29105. var newAction = instanciate(parsedAction.name, parameters);
  29106. if (newAction instanceof BABYLON.Condition && condition !== null) {
  29107. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  29108. if (action)
  29109. action.then(nothing);
  29110. else
  29111. actionManager.registerAction(nothing);
  29112. action = nothing;
  29113. }
  29114. if (combineArray === null) {
  29115. if (newAction instanceof BABYLON.Condition) {
  29116. condition = newAction;
  29117. newAction = action;
  29118. }
  29119. else {
  29120. condition = null;
  29121. if (action)
  29122. action.then(newAction);
  29123. else
  29124. actionManager.registerAction(newAction);
  29125. }
  29126. }
  29127. else {
  29128. combineArray.push(newAction);
  29129. }
  29130. for (var i = 0; i < parsedAction.children.length; i++)
  29131. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  29132. };
  29133. // triggers
  29134. for (var i = 0; i < parsedActions.children.length; i++) {
  29135. var triggerParams;
  29136. var trigger = parsedActions.children[i];
  29137. if (trigger.properties.length > 0) {
  29138. var param = trigger.properties[0].value;
  29139. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  29140. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  29141. }
  29142. else
  29143. triggerParams = BABYLON.ActionManager[trigger.name];
  29144. for (var j = 0; j < trigger.children.length; j++) {
  29145. if (!trigger.detached)
  29146. traverse(trigger.children[j], triggerParams, null, null);
  29147. }
  29148. }
  29149. };
  29150. // Statics
  29151. ActionManager._NothingTrigger = 0;
  29152. ActionManager._OnPickTrigger = 1;
  29153. ActionManager._OnLeftPickTrigger = 2;
  29154. ActionManager._OnRightPickTrigger = 3;
  29155. ActionManager._OnCenterPickTrigger = 4;
  29156. ActionManager._OnPickDownTrigger = 5;
  29157. ActionManager._OnPickUpTrigger = 6;
  29158. ActionManager._OnLongPressTrigger = 7;
  29159. ActionManager._OnPointerOverTrigger = 8;
  29160. ActionManager._OnPointerOutTrigger = 9;
  29161. ActionManager._OnEveryFrameTrigger = 10;
  29162. ActionManager._OnIntersectionEnterTrigger = 11;
  29163. ActionManager._OnIntersectionExitTrigger = 12;
  29164. ActionManager._OnKeyDownTrigger = 13;
  29165. ActionManager._OnKeyUpTrigger = 14;
  29166. ActionManager._OnPickOutTrigger = 15;
  29167. ActionManager.DragMovementThreshold = 10; // in pixels
  29168. ActionManager.LongPressDelay = 500; // in milliseconds
  29169. return ActionManager;
  29170. })();
  29171. BABYLON.ActionManager = ActionManager;
  29172. })(BABYLON || (BABYLON = {}));
  29173. var BABYLON;
  29174. (function (BABYLON) {
  29175. var InterpolateValueAction = (function (_super) {
  29176. __extends(InterpolateValueAction, _super);
  29177. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  29178. if (duration === void 0) { duration = 1000; }
  29179. _super.call(this, triggerOptions, condition);
  29180. this.propertyPath = propertyPath;
  29181. this.value = value;
  29182. this.duration = duration;
  29183. this.stopOtherAnimations = stopOtherAnimations;
  29184. this.onInterpolationDone = onInterpolationDone;
  29185. this._target = target;
  29186. }
  29187. InterpolateValueAction.prototype._prepare = function () {
  29188. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29189. this._property = this._getProperty(this.propertyPath);
  29190. };
  29191. InterpolateValueAction.prototype.execute = function () {
  29192. var scene = this._actionManager.getScene();
  29193. var keys = [
  29194. {
  29195. frame: 0,
  29196. value: this._target[this._property]
  29197. }, {
  29198. frame: 100,
  29199. value: this.value
  29200. }
  29201. ];
  29202. var dataType;
  29203. if (typeof this.value === "number") {
  29204. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  29205. }
  29206. else if (this.value instanceof BABYLON.Color3) {
  29207. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  29208. }
  29209. else if (this.value instanceof BABYLON.Vector3) {
  29210. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  29211. }
  29212. else if (this.value instanceof BABYLON.Matrix) {
  29213. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  29214. }
  29215. else if (this.value instanceof BABYLON.Quaternion) {
  29216. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  29217. }
  29218. else {
  29219. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  29220. return;
  29221. }
  29222. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  29223. animation.setKeys(keys);
  29224. if (this.stopOtherAnimations) {
  29225. scene.stopAnimation(this._target);
  29226. }
  29227. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  29228. };
  29229. return InterpolateValueAction;
  29230. })(BABYLON.Action);
  29231. BABYLON.InterpolateValueAction = InterpolateValueAction;
  29232. })(BABYLON || (BABYLON = {}));
  29233. var BABYLON;
  29234. (function (BABYLON) {
  29235. var SwitchBooleanAction = (function (_super) {
  29236. __extends(SwitchBooleanAction, _super);
  29237. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  29238. _super.call(this, triggerOptions, condition);
  29239. this.propertyPath = propertyPath;
  29240. this._target = target;
  29241. }
  29242. SwitchBooleanAction.prototype._prepare = function () {
  29243. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29244. this._property = this._getProperty(this.propertyPath);
  29245. };
  29246. SwitchBooleanAction.prototype.execute = function () {
  29247. this._target[this._property] = !this._target[this._property];
  29248. };
  29249. return SwitchBooleanAction;
  29250. })(BABYLON.Action);
  29251. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  29252. var SetStateAction = (function (_super) {
  29253. __extends(SetStateAction, _super);
  29254. function SetStateAction(triggerOptions, target, value, condition) {
  29255. _super.call(this, triggerOptions, condition);
  29256. this.value = value;
  29257. this._target = target;
  29258. }
  29259. SetStateAction.prototype.execute = function () {
  29260. this._target.state = this.value;
  29261. };
  29262. return SetStateAction;
  29263. })(BABYLON.Action);
  29264. BABYLON.SetStateAction = SetStateAction;
  29265. var SetValueAction = (function (_super) {
  29266. __extends(SetValueAction, _super);
  29267. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  29268. _super.call(this, triggerOptions, condition);
  29269. this.propertyPath = propertyPath;
  29270. this.value = value;
  29271. this._target = target;
  29272. }
  29273. SetValueAction.prototype._prepare = function () {
  29274. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29275. this._property = this._getProperty(this.propertyPath);
  29276. };
  29277. SetValueAction.prototype.execute = function () {
  29278. this._target[this._property] = this.value;
  29279. };
  29280. return SetValueAction;
  29281. })(BABYLON.Action);
  29282. BABYLON.SetValueAction = SetValueAction;
  29283. var IncrementValueAction = (function (_super) {
  29284. __extends(IncrementValueAction, _super);
  29285. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  29286. _super.call(this, triggerOptions, condition);
  29287. this.propertyPath = propertyPath;
  29288. this.value = value;
  29289. this._target = target;
  29290. }
  29291. IncrementValueAction.prototype._prepare = function () {
  29292. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29293. this._property = this._getProperty(this.propertyPath);
  29294. if (typeof this._target[this._property] !== "number") {
  29295. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  29296. }
  29297. };
  29298. IncrementValueAction.prototype.execute = function () {
  29299. this._target[this._property] += this.value;
  29300. };
  29301. return IncrementValueAction;
  29302. })(BABYLON.Action);
  29303. BABYLON.IncrementValueAction = IncrementValueAction;
  29304. var PlayAnimationAction = (function (_super) {
  29305. __extends(PlayAnimationAction, _super);
  29306. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  29307. _super.call(this, triggerOptions, condition);
  29308. this.from = from;
  29309. this.to = to;
  29310. this.loop = loop;
  29311. this._target = target;
  29312. }
  29313. PlayAnimationAction.prototype._prepare = function () {
  29314. };
  29315. PlayAnimationAction.prototype.execute = function () {
  29316. var scene = this._actionManager.getScene();
  29317. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  29318. };
  29319. return PlayAnimationAction;
  29320. })(BABYLON.Action);
  29321. BABYLON.PlayAnimationAction = PlayAnimationAction;
  29322. var StopAnimationAction = (function (_super) {
  29323. __extends(StopAnimationAction, _super);
  29324. function StopAnimationAction(triggerOptions, target, condition) {
  29325. _super.call(this, triggerOptions, condition);
  29326. this._target = target;
  29327. }
  29328. StopAnimationAction.prototype._prepare = function () {
  29329. };
  29330. StopAnimationAction.prototype.execute = function () {
  29331. var scene = this._actionManager.getScene();
  29332. scene.stopAnimation(this._target);
  29333. };
  29334. return StopAnimationAction;
  29335. })(BABYLON.Action);
  29336. BABYLON.StopAnimationAction = StopAnimationAction;
  29337. var DoNothingAction = (function (_super) {
  29338. __extends(DoNothingAction, _super);
  29339. function DoNothingAction(triggerOptions, condition) {
  29340. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  29341. _super.call(this, triggerOptions, condition);
  29342. }
  29343. DoNothingAction.prototype.execute = function () {
  29344. };
  29345. return DoNothingAction;
  29346. })(BABYLON.Action);
  29347. BABYLON.DoNothingAction = DoNothingAction;
  29348. var CombineAction = (function (_super) {
  29349. __extends(CombineAction, _super);
  29350. function CombineAction(triggerOptions, children, condition) {
  29351. _super.call(this, triggerOptions, condition);
  29352. this.children = children;
  29353. }
  29354. CombineAction.prototype._prepare = function () {
  29355. for (var index = 0; index < this.children.length; index++) {
  29356. this.children[index]._actionManager = this._actionManager;
  29357. this.children[index]._prepare();
  29358. }
  29359. };
  29360. CombineAction.prototype.execute = function (evt) {
  29361. for (var index = 0; index < this.children.length; index++) {
  29362. this.children[index].execute(evt);
  29363. }
  29364. };
  29365. return CombineAction;
  29366. })(BABYLON.Action);
  29367. BABYLON.CombineAction = CombineAction;
  29368. var ExecuteCodeAction = (function (_super) {
  29369. __extends(ExecuteCodeAction, _super);
  29370. function ExecuteCodeAction(triggerOptions, func, condition) {
  29371. _super.call(this, triggerOptions, condition);
  29372. this.func = func;
  29373. }
  29374. ExecuteCodeAction.prototype.execute = function (evt) {
  29375. this.func(evt);
  29376. };
  29377. return ExecuteCodeAction;
  29378. })(BABYLON.Action);
  29379. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  29380. var SetParentAction = (function (_super) {
  29381. __extends(SetParentAction, _super);
  29382. function SetParentAction(triggerOptions, target, parent, condition) {
  29383. _super.call(this, triggerOptions, condition);
  29384. this._target = target;
  29385. this._parent = parent;
  29386. }
  29387. SetParentAction.prototype._prepare = function () {
  29388. };
  29389. SetParentAction.prototype.execute = function () {
  29390. if (this._target.parent === this._parent) {
  29391. return;
  29392. }
  29393. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  29394. invertParentWorldMatrix.invert();
  29395. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  29396. this._target.parent = this._parent;
  29397. };
  29398. return SetParentAction;
  29399. })(BABYLON.Action);
  29400. BABYLON.SetParentAction = SetParentAction;
  29401. var PlaySoundAction = (function (_super) {
  29402. __extends(PlaySoundAction, _super);
  29403. function PlaySoundAction(triggerOptions, sound, condition) {
  29404. _super.call(this, triggerOptions, condition);
  29405. this._sound = sound;
  29406. }
  29407. PlaySoundAction.prototype._prepare = function () {
  29408. };
  29409. PlaySoundAction.prototype.execute = function () {
  29410. if (this._sound !== undefined)
  29411. this._sound.play();
  29412. };
  29413. return PlaySoundAction;
  29414. })(BABYLON.Action);
  29415. BABYLON.PlaySoundAction = PlaySoundAction;
  29416. var StopSoundAction = (function (_super) {
  29417. __extends(StopSoundAction, _super);
  29418. function StopSoundAction(triggerOptions, sound, condition) {
  29419. _super.call(this, triggerOptions, condition);
  29420. this._sound = sound;
  29421. }
  29422. StopSoundAction.prototype._prepare = function () {
  29423. };
  29424. StopSoundAction.prototype.execute = function () {
  29425. if (this._sound !== undefined)
  29426. this._sound.stop();
  29427. };
  29428. return StopSoundAction;
  29429. })(BABYLON.Action);
  29430. BABYLON.StopSoundAction = StopSoundAction;
  29431. })(BABYLON || (BABYLON = {}));
  29432. var BABYLON;
  29433. (function (BABYLON) {
  29434. var Geometry = (function () {
  29435. function Geometry(id, scene, vertexData, updatable, mesh) {
  29436. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29437. this._totalVertices = 0;
  29438. this._isDisposed = false;
  29439. this.id = id;
  29440. this._engine = scene.getEngine();
  29441. this._meshes = [];
  29442. this._scene = scene;
  29443. //Init vertex buffer cache
  29444. this._vertexBuffers = {};
  29445. this._indices = [];
  29446. // vertexData
  29447. if (vertexData) {
  29448. this.setAllVerticesData(vertexData, updatable);
  29449. }
  29450. else {
  29451. this._totalVertices = 0;
  29452. this._indices = [];
  29453. }
  29454. // applyToMesh
  29455. if (mesh) {
  29456. this.applyToMesh(mesh);
  29457. mesh.computeWorldMatrix(true);
  29458. }
  29459. }
  29460. Object.defineProperty(Geometry.prototype, "extend", {
  29461. get: function () {
  29462. return this._extend;
  29463. },
  29464. enumerable: true,
  29465. configurable: true
  29466. });
  29467. Geometry.prototype.getScene = function () {
  29468. return this._scene;
  29469. };
  29470. Geometry.prototype.getEngine = function () {
  29471. return this._engine;
  29472. };
  29473. Geometry.prototype.isReady = function () {
  29474. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29475. };
  29476. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29477. vertexData.applyToGeometry(this, updatable);
  29478. this.notifyUpdate();
  29479. };
  29480. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29481. if (this._vertexBuffers[kind]) {
  29482. this._vertexBuffers[kind].dispose();
  29483. }
  29484. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29485. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29486. stride = this._vertexBuffers[kind].getStrideSize();
  29487. this._totalVertices = data.length / stride;
  29488. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29489. var meshes = this._meshes;
  29490. var numOfMeshes = meshes.length;
  29491. for (var index = 0; index < numOfMeshes; index++) {
  29492. var mesh = meshes[index];
  29493. mesh._resetPointsArrayCache();
  29494. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29495. mesh._createGlobalSubMesh();
  29496. mesh.computeWorldMatrix(true);
  29497. }
  29498. }
  29499. this.notifyUpdate(kind);
  29500. };
  29501. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29502. var vertexBuffer = this.getVertexBuffer(kind);
  29503. if (!vertexBuffer) {
  29504. return;
  29505. }
  29506. vertexBuffer.updateDirectly(data, offset);
  29507. this.notifyUpdate(kind);
  29508. };
  29509. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29510. var vertexBuffer = this.getVertexBuffer(kind);
  29511. if (!vertexBuffer) {
  29512. return;
  29513. }
  29514. vertexBuffer.update(data);
  29515. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29516. var stride = vertexBuffer.getStrideSize();
  29517. this._totalVertices = data.length / stride;
  29518. if (updateExtends) {
  29519. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29520. }
  29521. var meshes = this._meshes;
  29522. var numOfMeshes = meshes.length;
  29523. for (var index = 0; index < numOfMeshes; index++) {
  29524. var mesh = meshes[index];
  29525. mesh._resetPointsArrayCache();
  29526. if (updateExtends) {
  29527. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29528. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29529. var subMesh = mesh.subMeshes[subIndex];
  29530. subMesh.refreshBoundingInfo();
  29531. }
  29532. }
  29533. }
  29534. }
  29535. this.notifyUpdate(kind);
  29536. };
  29537. Geometry.prototype.getTotalVertices = function () {
  29538. if (!this.isReady()) {
  29539. return 0;
  29540. }
  29541. return this._totalVertices;
  29542. };
  29543. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  29544. var vertexBuffer = this.getVertexBuffer(kind);
  29545. if (!vertexBuffer) {
  29546. return null;
  29547. }
  29548. var orig = vertexBuffer.getData();
  29549. if (!copyWhenShared || this._meshes.length === 1) {
  29550. return orig;
  29551. }
  29552. else {
  29553. var len = orig.length;
  29554. var copy = [];
  29555. for (var i = 0; i < len; i++) {
  29556. copy.push(orig[i]);
  29557. }
  29558. return copy;
  29559. }
  29560. };
  29561. Geometry.prototype.getVertexBuffer = function (kind) {
  29562. if (!this.isReady()) {
  29563. return null;
  29564. }
  29565. return this._vertexBuffers[kind];
  29566. };
  29567. Geometry.prototype.getVertexBuffers = function () {
  29568. if (!this.isReady()) {
  29569. return null;
  29570. }
  29571. return this._vertexBuffers;
  29572. };
  29573. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29574. if (!this._vertexBuffers) {
  29575. if (this._delayInfo) {
  29576. return this._delayInfo.indexOf(kind) !== -1;
  29577. }
  29578. return false;
  29579. }
  29580. return this._vertexBuffers[kind] !== undefined;
  29581. };
  29582. Geometry.prototype.getVerticesDataKinds = function () {
  29583. var result = [];
  29584. var kind;
  29585. if (!this._vertexBuffers && this._delayInfo) {
  29586. for (kind in this._delayInfo) {
  29587. result.push(kind);
  29588. }
  29589. }
  29590. else {
  29591. for (kind in this._vertexBuffers) {
  29592. result.push(kind);
  29593. }
  29594. }
  29595. return result;
  29596. };
  29597. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29598. if (this._indexBuffer) {
  29599. this._engine._releaseBuffer(this._indexBuffer);
  29600. }
  29601. this._indices = indices;
  29602. if (this._meshes.length !== 0 && this._indices) {
  29603. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29604. }
  29605. if (totalVertices !== undefined) {
  29606. this._totalVertices = totalVertices;
  29607. }
  29608. var meshes = this._meshes;
  29609. var numOfMeshes = meshes.length;
  29610. for (var index = 0; index < numOfMeshes; index++) {
  29611. meshes[index]._createGlobalSubMesh();
  29612. }
  29613. this.notifyUpdate();
  29614. };
  29615. Geometry.prototype.getTotalIndices = function () {
  29616. if (!this.isReady()) {
  29617. return 0;
  29618. }
  29619. return this._indices.length;
  29620. };
  29621. Geometry.prototype.getIndices = function (copyWhenShared) {
  29622. if (!this.isReady()) {
  29623. return null;
  29624. }
  29625. var orig = this._indices;
  29626. if (!copyWhenShared || this._meshes.length === 1) {
  29627. return orig;
  29628. }
  29629. else {
  29630. var len = orig.length;
  29631. var copy = [];
  29632. for (var i = 0; i < len; i++) {
  29633. copy.push(orig[i]);
  29634. }
  29635. return copy;
  29636. }
  29637. };
  29638. Geometry.prototype.getIndexBuffer = function () {
  29639. if (!this.isReady()) {
  29640. return null;
  29641. }
  29642. return this._indexBuffer;
  29643. };
  29644. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29645. var meshes = this._meshes;
  29646. var index = meshes.indexOf(mesh);
  29647. if (index === -1) {
  29648. return;
  29649. }
  29650. for (var kind in this._vertexBuffers) {
  29651. this._vertexBuffers[kind].dispose();
  29652. }
  29653. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  29654. this._indexBuffer = null;
  29655. }
  29656. meshes.splice(index, 1);
  29657. mesh._geometry = null;
  29658. if (meshes.length === 0 && shouldDispose) {
  29659. this.dispose();
  29660. }
  29661. };
  29662. Geometry.prototype.applyToMesh = function (mesh) {
  29663. if (mesh._geometry === this) {
  29664. return;
  29665. }
  29666. var previousGeometry = mesh._geometry;
  29667. if (previousGeometry) {
  29668. previousGeometry.releaseForMesh(mesh);
  29669. }
  29670. var meshes = this._meshes;
  29671. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29672. mesh._geometry = this;
  29673. this._scene.pushGeometry(this);
  29674. meshes.push(mesh);
  29675. if (this.isReady()) {
  29676. this._applyToMesh(mesh);
  29677. }
  29678. else {
  29679. mesh._boundingInfo = this._boundingInfo;
  29680. }
  29681. };
  29682. Geometry.prototype._applyToMesh = function (mesh) {
  29683. var numOfMeshes = this._meshes.length;
  29684. // vertexBuffers
  29685. for (var kind in this._vertexBuffers) {
  29686. if (numOfMeshes === 1) {
  29687. this._vertexBuffers[kind].create();
  29688. }
  29689. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  29690. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29691. mesh._resetPointsArrayCache();
  29692. if (!this._extend) {
  29693. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  29694. }
  29695. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29696. mesh._createGlobalSubMesh();
  29697. //bounding info was just created again, world matrix should be applied again.
  29698. mesh._updateBoundingInfo();
  29699. }
  29700. }
  29701. // indexBuffer
  29702. if (numOfMeshes === 1 && this._indices) {
  29703. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29704. }
  29705. if (this._indexBuffer) {
  29706. this._indexBuffer.references = numOfMeshes;
  29707. }
  29708. };
  29709. Geometry.prototype.notifyUpdate = function (kind) {
  29710. if (this.onGeometryUpdated) {
  29711. this.onGeometryUpdated(this, kind);
  29712. }
  29713. };
  29714. Geometry.prototype.load = function (scene, onLoaded) {
  29715. var _this = this;
  29716. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29717. return;
  29718. }
  29719. if (this.isReady()) {
  29720. if (onLoaded) {
  29721. onLoaded();
  29722. }
  29723. return;
  29724. }
  29725. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29726. scene._addPendingData(this);
  29727. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29728. _this._delayLoadingFunction(JSON.parse(data), _this);
  29729. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29730. _this._delayInfo = [];
  29731. scene._removePendingData(_this);
  29732. var meshes = _this._meshes;
  29733. var numOfMeshes = meshes.length;
  29734. for (var index = 0; index < numOfMeshes; index++) {
  29735. _this._applyToMesh(meshes[index]);
  29736. }
  29737. if (onLoaded) {
  29738. onLoaded();
  29739. }
  29740. }, function () { }, scene.database);
  29741. };
  29742. Geometry.prototype.isDisposed = function () {
  29743. return this._isDisposed;
  29744. };
  29745. Geometry.prototype.dispose = function () {
  29746. var meshes = this._meshes;
  29747. var numOfMeshes = meshes.length;
  29748. var index;
  29749. for (index = 0; index < numOfMeshes; index++) {
  29750. this.releaseForMesh(meshes[index]);
  29751. }
  29752. this._meshes = [];
  29753. for (var kind in this._vertexBuffers) {
  29754. this._vertexBuffers[kind].dispose();
  29755. }
  29756. this._vertexBuffers = [];
  29757. this._totalVertices = 0;
  29758. if (this._indexBuffer) {
  29759. this._engine._releaseBuffer(this._indexBuffer);
  29760. }
  29761. this._indexBuffer = null;
  29762. this._indices = [];
  29763. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29764. this.delayLoadingFile = null;
  29765. this._delayLoadingFunction = null;
  29766. this._delayInfo = [];
  29767. this._boundingInfo = null;
  29768. this._scene.removeGeometry(this);
  29769. this._isDisposed = true;
  29770. };
  29771. Geometry.prototype.copy = function (id) {
  29772. var vertexData = new BABYLON.VertexData();
  29773. vertexData.indices = [];
  29774. var indices = this.getIndices();
  29775. for (var index = 0; index < indices.length; index++) {
  29776. vertexData.indices.push(indices[index]);
  29777. }
  29778. var updatable = false;
  29779. var stopChecking = false;
  29780. var kind;
  29781. for (kind in this._vertexBuffers) {
  29782. // using slice() to make a copy of the array and not just reference it
  29783. var data = this.getVerticesData(kind);
  29784. if (data instanceof Float32Array) {
  29785. vertexData.set(new Float32Array(data), kind);
  29786. }
  29787. else {
  29788. vertexData.set(data.slice(0), kind);
  29789. }
  29790. if (!stopChecking) {
  29791. updatable = this.getVertexBuffer(kind).isUpdatable();
  29792. stopChecking = !updatable;
  29793. }
  29794. }
  29795. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29796. geometry.delayLoadState = this.delayLoadState;
  29797. geometry.delayLoadingFile = this.delayLoadingFile;
  29798. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29799. for (kind in this._delayInfo) {
  29800. geometry._delayInfo = geometry._delayInfo || [];
  29801. geometry._delayInfo.push(kind);
  29802. }
  29803. // Bounding info
  29804. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29805. return geometry;
  29806. };
  29807. Geometry.prototype.serialize = function () {
  29808. var serializationObject = {};
  29809. serializationObject.id = this.id;
  29810. if (BABYLON.Tags.HasTags(this)) {
  29811. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29812. }
  29813. return serializationObject;
  29814. };
  29815. Geometry.prototype.serializeVerticeData = function () {
  29816. var serializationObject = this.serialize();
  29817. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29818. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29819. }
  29820. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29821. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29822. }
  29823. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29824. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29825. }
  29826. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29827. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29828. }
  29829. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29830. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29831. }
  29832. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29833. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29834. }
  29835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29836. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29837. }
  29838. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29839. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29840. }
  29841. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29842. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29843. }
  29844. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29845. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29846. serializationObject.matricesIndices._isExpanded = true;
  29847. }
  29848. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29849. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29850. }
  29851. serializationObject.indices = this.getIndices();
  29852. return serializationObject;
  29853. };
  29854. // Statics
  29855. Geometry.ExtractFromMesh = function (mesh, id) {
  29856. var geometry = mesh._geometry;
  29857. if (!geometry) {
  29858. return null;
  29859. }
  29860. return geometry.copy(id);
  29861. };
  29862. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29863. // be aware Math.random() could cause collisions
  29864. Geometry.RandomId = function () {
  29865. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  29866. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  29867. return v.toString(16);
  29868. });
  29869. };
  29870. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29871. var scene = mesh.getScene();
  29872. // Geometry
  29873. var geometryId = parsedGeometry.geometryId;
  29874. if (geometryId) {
  29875. var geometry = scene.getGeometryByID(geometryId);
  29876. if (geometry) {
  29877. geometry.applyToMesh(mesh);
  29878. }
  29879. }
  29880. else if (parsedGeometry instanceof ArrayBuffer) {
  29881. var binaryInfo = mesh._binaryInfo;
  29882. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29883. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29884. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29885. }
  29886. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29887. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29888. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29889. }
  29890. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29891. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29892. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29893. }
  29894. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29895. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29896. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29897. }
  29898. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29899. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29900. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29901. }
  29902. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29903. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29904. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29905. }
  29906. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29907. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29908. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29909. }
  29910. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29911. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29912. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29913. }
  29914. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29915. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29916. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29917. }
  29918. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29919. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29920. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29921. }
  29922. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29923. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29924. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29925. }
  29926. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29927. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29928. mesh.setIndices(indicesData);
  29929. }
  29930. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29931. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29932. mesh.subMeshes = [];
  29933. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29934. var materialIndex = subMeshesData[(i * 5) + 0];
  29935. var verticesStart = subMeshesData[(i * 5) + 1];
  29936. var verticesCount = subMeshesData[(i * 5) + 2];
  29937. var indexStart = subMeshesData[(i * 5) + 3];
  29938. var indexCount = subMeshesData[(i * 5) + 4];
  29939. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29940. }
  29941. }
  29942. }
  29943. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29944. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  29945. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  29946. if (parsedGeometry.uvs) {
  29947. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  29948. }
  29949. if (parsedGeometry.uvs2) {
  29950. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  29951. }
  29952. if (parsedGeometry.uvs3) {
  29953. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  29954. }
  29955. if (parsedGeometry.uvs4) {
  29956. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  29957. }
  29958. if (parsedGeometry.uvs5) {
  29959. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  29960. }
  29961. if (parsedGeometry.uvs6) {
  29962. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  29963. }
  29964. if (parsedGeometry.colors) {
  29965. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  29966. }
  29967. if (parsedGeometry.matricesIndices) {
  29968. if (!parsedGeometry.matricesIndices._isExpanded) {
  29969. var floatIndices = [];
  29970. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29971. var matricesIndex = parsedGeometry.matricesIndices[i];
  29972. floatIndices.push(matricesIndex & 0x000000FF);
  29973. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29974. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29975. floatIndices.push(matricesIndex >> 24);
  29976. }
  29977. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  29978. }
  29979. else {
  29980. delete parsedGeometry.matricesIndices._isExpanded;
  29981. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  29982. }
  29983. }
  29984. if (parsedGeometry.matricesIndicesExtra) {
  29985. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29986. var floatIndices = [];
  29987. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29988. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29989. floatIndices.push(matricesIndex & 0x000000FF);
  29990. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29991. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29992. floatIndices.push(matricesIndex >> 24);
  29993. }
  29994. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  29995. }
  29996. else {
  29997. delete parsedGeometry.matricesIndices._isExpanded;
  29998. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  29999. }
  30000. }
  30001. if (parsedGeometry.matricesWeights) {
  30002. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  30003. }
  30004. if (parsedGeometry.matricesWeightsExtra) {
  30005. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  30006. }
  30007. mesh.setIndices(parsedGeometry.indices);
  30008. }
  30009. // SubMeshes
  30010. if (parsedGeometry.subMeshes) {
  30011. mesh.subMeshes = [];
  30012. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30013. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30014. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30015. }
  30016. }
  30017. // Flat shading
  30018. if (mesh._shouldGenerateFlatShading) {
  30019. mesh.convertToFlatShadedMesh();
  30020. delete mesh._shouldGenerateFlatShading;
  30021. }
  30022. // Update
  30023. mesh.computeWorldMatrix(true);
  30024. // Octree
  30025. if (scene['_selectionOctree']) {
  30026. scene['_selectionOctree'].addMesh(mesh);
  30027. }
  30028. };
  30029. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  30030. if (scene.getGeometryByID(parsedVertexData.id)) {
  30031. return null; // null since geometry could be something else than a box...
  30032. }
  30033. var geometry = new Geometry(parsedVertexData.id, scene);
  30034. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  30035. if (parsedVertexData.delayLoadingFile) {
  30036. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30037. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  30038. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  30039. geometry._delayInfo = [];
  30040. if (parsedVertexData.hasUVs) {
  30041. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30042. }
  30043. if (parsedVertexData.hasUVs2) {
  30044. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30045. }
  30046. if (parsedVertexData.hasUVs3) {
  30047. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30048. }
  30049. if (parsedVertexData.hasUVs4) {
  30050. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30051. }
  30052. if (parsedVertexData.hasUVs5) {
  30053. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30054. }
  30055. if (parsedVertexData.hasUVs6) {
  30056. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30057. }
  30058. if (parsedVertexData.hasColors) {
  30059. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30060. }
  30061. if (parsedVertexData.hasMatricesIndices) {
  30062. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30063. }
  30064. if (parsedVertexData.hasMatricesWeights) {
  30065. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30066. }
  30067. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  30068. }
  30069. else {
  30070. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  30071. }
  30072. scene.pushGeometry(geometry, true);
  30073. return geometry;
  30074. };
  30075. return Geometry;
  30076. })();
  30077. BABYLON.Geometry = Geometry;
  30078. /////// Primitives //////////////////////////////////////////////
  30079. var Geometry;
  30080. (function (Geometry) {
  30081. var Primitives;
  30082. (function (Primitives) {
  30083. /// Abstract class
  30084. var _Primitive = (function (_super) {
  30085. __extends(_Primitive, _super);
  30086. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  30087. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  30088. this._canBeRegenerated = _canBeRegenerated;
  30089. this._beingRegenerated = true;
  30090. this.regenerate();
  30091. this._beingRegenerated = false;
  30092. }
  30093. _Primitive.prototype.canBeRegenerated = function () {
  30094. return this._canBeRegenerated;
  30095. };
  30096. _Primitive.prototype.regenerate = function () {
  30097. if (!this._canBeRegenerated) {
  30098. return;
  30099. }
  30100. this._beingRegenerated = true;
  30101. this.setAllVerticesData(this._regenerateVertexData(), false);
  30102. this._beingRegenerated = false;
  30103. };
  30104. _Primitive.prototype.asNewGeometry = function (id) {
  30105. return _super.prototype.copy.call(this, id);
  30106. };
  30107. // overrides
  30108. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  30109. if (!this._beingRegenerated) {
  30110. return;
  30111. }
  30112. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  30113. };
  30114. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  30115. if (!this._beingRegenerated) {
  30116. return;
  30117. }
  30118. _super.prototype.setVerticesData.call(this, kind, data, false);
  30119. };
  30120. // to override
  30121. // protected
  30122. _Primitive.prototype._regenerateVertexData = function () {
  30123. throw new Error("Abstract method");
  30124. };
  30125. _Primitive.prototype.copy = function (id) {
  30126. throw new Error("Must be overriden in sub-classes.");
  30127. };
  30128. _Primitive.prototype.serialize = function () {
  30129. var serializationObject = _super.prototype.serialize.call(this);
  30130. serializationObject.canBeRegenerated = this.canBeRegenerated();
  30131. return serializationObject;
  30132. };
  30133. return _Primitive;
  30134. })(Geometry);
  30135. Primitives._Primitive = _Primitive;
  30136. var Ribbon = (function (_super) {
  30137. __extends(Ribbon, _super);
  30138. // Members
  30139. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  30140. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30141. _super.call(this, id, scene, canBeRegenerated, mesh);
  30142. this.pathArray = pathArray;
  30143. this.closeArray = closeArray;
  30144. this.closePath = closePath;
  30145. this.offset = offset;
  30146. this.side = side;
  30147. }
  30148. Ribbon.prototype._regenerateVertexData = function () {
  30149. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  30150. };
  30151. Ribbon.prototype.copy = function (id) {
  30152. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  30153. };
  30154. return Ribbon;
  30155. })(_Primitive);
  30156. Primitives.Ribbon = Ribbon;
  30157. var Box = (function (_super) {
  30158. __extends(Box, _super);
  30159. // Members
  30160. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  30161. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30162. _super.call(this, id, scene, canBeRegenerated, mesh);
  30163. this.size = size;
  30164. this.side = side;
  30165. }
  30166. Box.prototype._regenerateVertexData = function () {
  30167. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  30168. };
  30169. Box.prototype.copy = function (id) {
  30170. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30171. };
  30172. Box.prototype.serialize = function () {
  30173. var serializationObject = _super.prototype.serialize.call(this);
  30174. serializationObject.size = this.size;
  30175. return serializationObject;
  30176. };
  30177. Box.Parse = function (parsedBox, scene) {
  30178. if (scene.getGeometryByID(parsedBox.id)) {
  30179. return null; // null since geometry could be something else than a box...
  30180. }
  30181. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  30182. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30183. scene.pushGeometry(box, true);
  30184. return box;
  30185. };
  30186. return Box;
  30187. })(_Primitive);
  30188. Primitives.Box = Box;
  30189. var Sphere = (function (_super) {
  30190. __extends(Sphere, _super);
  30191. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30192. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30193. _super.call(this, id, scene, canBeRegenerated, mesh);
  30194. this.segments = segments;
  30195. this.diameter = diameter;
  30196. this.side = side;
  30197. }
  30198. Sphere.prototype._regenerateVertexData = function () {
  30199. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30200. };
  30201. Sphere.prototype.copy = function (id) {
  30202. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30203. };
  30204. Sphere.prototype.serialize = function () {
  30205. var serializationObject = _super.prototype.serialize.call(this);
  30206. serializationObject.segments = this.segments;
  30207. serializationObject.diameter = this.diameter;
  30208. return serializationObject;
  30209. };
  30210. Sphere.Parse = function (parsedSphere, scene) {
  30211. if (scene.getGeometryByID(parsedSphere.id)) {
  30212. return null; // null since geometry could be something else than a sphere...
  30213. }
  30214. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30215. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30216. scene.pushGeometry(sphere, true);
  30217. return sphere;
  30218. };
  30219. return Sphere;
  30220. })(_Primitive);
  30221. Primitives.Sphere = Sphere;
  30222. var Disc = (function (_super) {
  30223. __extends(Disc, _super);
  30224. // Members
  30225. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30226. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30227. _super.call(this, id, scene, canBeRegenerated, mesh);
  30228. this.radius = radius;
  30229. this.tessellation = tessellation;
  30230. this.side = side;
  30231. }
  30232. Disc.prototype._regenerateVertexData = function () {
  30233. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30234. };
  30235. Disc.prototype.copy = function (id) {
  30236. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30237. };
  30238. return Disc;
  30239. })(_Primitive);
  30240. Primitives.Disc = Disc;
  30241. var Cylinder = (function (_super) {
  30242. __extends(Cylinder, _super);
  30243. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30244. if (subdivisions === void 0) { subdivisions = 1; }
  30245. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30246. _super.call(this, id, scene, canBeRegenerated, mesh);
  30247. this.height = height;
  30248. this.diameterTop = diameterTop;
  30249. this.diameterBottom = diameterBottom;
  30250. this.tessellation = tessellation;
  30251. this.subdivisions = subdivisions;
  30252. this.side = side;
  30253. }
  30254. Cylinder.prototype._regenerateVertexData = function () {
  30255. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30256. };
  30257. Cylinder.prototype.copy = function (id) {
  30258. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30259. };
  30260. Cylinder.prototype.serialize = function () {
  30261. var serializationObject = _super.prototype.serialize.call(this);
  30262. serializationObject.height = this.height;
  30263. serializationObject.diameterTop = this.diameterTop;
  30264. serializationObject.diameterBottom = this.diameterBottom;
  30265. serializationObject.tessellation = this.tessellation;
  30266. return serializationObject;
  30267. };
  30268. Cylinder.Parse = function (parsedCylinder, scene) {
  30269. if (scene.getGeometryByID(parsedCylinder.id)) {
  30270. return null; // null since geometry could be something else than a cylinder...
  30271. }
  30272. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30273. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30274. scene.pushGeometry(cylinder, true);
  30275. return cylinder;
  30276. };
  30277. return Cylinder;
  30278. })(_Primitive);
  30279. Primitives.Cylinder = Cylinder;
  30280. var Torus = (function (_super) {
  30281. __extends(Torus, _super);
  30282. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30283. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30284. _super.call(this, id, scene, canBeRegenerated, mesh);
  30285. this.diameter = diameter;
  30286. this.thickness = thickness;
  30287. this.tessellation = tessellation;
  30288. this.side = side;
  30289. }
  30290. Torus.prototype._regenerateVertexData = function () {
  30291. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30292. };
  30293. Torus.prototype.copy = function (id) {
  30294. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30295. };
  30296. Torus.prototype.serialize = function () {
  30297. var serializationObject = _super.prototype.serialize.call(this);
  30298. serializationObject.diameter = this.diameter;
  30299. serializationObject.thickness = this.thickness;
  30300. serializationObject.tessellation = this.tessellation;
  30301. return serializationObject;
  30302. };
  30303. Torus.Parse = function (parsedTorus, scene) {
  30304. if (scene.getGeometryByID(parsedTorus.id)) {
  30305. return null; // null since geometry could be something else than a torus...
  30306. }
  30307. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30308. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30309. scene.pushGeometry(torus, true);
  30310. return torus;
  30311. };
  30312. return Torus;
  30313. })(_Primitive);
  30314. Primitives.Torus = Torus;
  30315. var Ground = (function (_super) {
  30316. __extends(Ground, _super);
  30317. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30318. _super.call(this, id, scene, canBeRegenerated, mesh);
  30319. this.width = width;
  30320. this.height = height;
  30321. this.subdivisions = subdivisions;
  30322. }
  30323. Ground.prototype._regenerateVertexData = function () {
  30324. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30325. };
  30326. Ground.prototype.copy = function (id) {
  30327. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30328. };
  30329. Ground.prototype.serialize = function () {
  30330. var serializationObject = _super.prototype.serialize.call(this);
  30331. serializationObject.width = this.width;
  30332. serializationObject.height = this.height;
  30333. serializationObject.subdivisions = this.subdivisions;
  30334. return serializationObject;
  30335. };
  30336. Ground.Parse = function (parsedGround, scene) {
  30337. if (scene.getGeometryByID(parsedGround.id)) {
  30338. return null; // null since geometry could be something else than a ground...
  30339. }
  30340. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30341. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30342. scene.pushGeometry(ground, true);
  30343. return ground;
  30344. };
  30345. return Ground;
  30346. })(_Primitive);
  30347. Primitives.Ground = Ground;
  30348. var TiledGround = (function (_super) {
  30349. __extends(TiledGround, _super);
  30350. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30351. _super.call(this, id, scene, canBeRegenerated, mesh);
  30352. this.xmin = xmin;
  30353. this.zmin = zmin;
  30354. this.xmax = xmax;
  30355. this.zmax = zmax;
  30356. this.subdivisions = subdivisions;
  30357. this.precision = precision;
  30358. }
  30359. TiledGround.prototype._regenerateVertexData = function () {
  30360. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30361. };
  30362. TiledGround.prototype.copy = function (id) {
  30363. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30364. };
  30365. return TiledGround;
  30366. })(_Primitive);
  30367. Primitives.TiledGround = TiledGround;
  30368. var Plane = (function (_super) {
  30369. __extends(Plane, _super);
  30370. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30371. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30372. _super.call(this, id, scene, canBeRegenerated, mesh);
  30373. this.size = size;
  30374. this.side = side;
  30375. }
  30376. Plane.prototype._regenerateVertexData = function () {
  30377. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30378. };
  30379. Plane.prototype.copy = function (id) {
  30380. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30381. };
  30382. Plane.prototype.serialize = function () {
  30383. var serializationObject = _super.prototype.serialize.call(this);
  30384. serializationObject.size = this.size;
  30385. return serializationObject;
  30386. };
  30387. Plane.Parse = function (parsedPlane, scene) {
  30388. if (scene.getGeometryByID(parsedPlane.id)) {
  30389. return null; // null since geometry could be something else than a ground...
  30390. }
  30391. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30392. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30393. scene.pushGeometry(plane, true);
  30394. return plane;
  30395. };
  30396. return Plane;
  30397. })(_Primitive);
  30398. Primitives.Plane = Plane;
  30399. var TorusKnot = (function (_super) {
  30400. __extends(TorusKnot, _super);
  30401. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30402. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30403. _super.call(this, id, scene, canBeRegenerated, mesh);
  30404. this.radius = radius;
  30405. this.tube = tube;
  30406. this.radialSegments = radialSegments;
  30407. this.tubularSegments = tubularSegments;
  30408. this.p = p;
  30409. this.q = q;
  30410. this.side = side;
  30411. }
  30412. TorusKnot.prototype._regenerateVertexData = function () {
  30413. 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 });
  30414. };
  30415. TorusKnot.prototype.copy = function (id) {
  30416. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30417. };
  30418. TorusKnot.prototype.serialize = function () {
  30419. var serializationObject = _super.prototype.serialize.call(this);
  30420. serializationObject.radius = this.radius;
  30421. serializationObject.tube = this.tube;
  30422. serializationObject.radialSegments = this.radialSegments;
  30423. serializationObject.tubularSegments = this.tubularSegments;
  30424. serializationObject.p = this.p;
  30425. serializationObject.q = this.q;
  30426. return serializationObject;
  30427. };
  30428. ;
  30429. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30430. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30431. return null; // null since geometry could be something else than a ground...
  30432. }
  30433. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30434. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30435. scene.pushGeometry(torusKnot, true);
  30436. return torusKnot;
  30437. };
  30438. return TorusKnot;
  30439. })(_Primitive);
  30440. Primitives.TorusKnot = TorusKnot;
  30441. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30442. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30443. })(BABYLON || (BABYLON = {}));
  30444. var BABYLON;
  30445. (function (BABYLON) {
  30446. var GroundMesh = (function (_super) {
  30447. __extends(GroundMesh, _super);
  30448. function GroundMesh(name, scene) {
  30449. _super.call(this, name, scene);
  30450. this.generateOctree = false;
  30451. this._worldInverse = new BABYLON.Matrix();
  30452. }
  30453. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  30454. get: function () {
  30455. return this._subdivisions;
  30456. },
  30457. enumerable: true,
  30458. configurable: true
  30459. });
  30460. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  30461. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  30462. this._subdivisions = chunksCount;
  30463. this.subdivide(this._subdivisions);
  30464. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  30465. };
  30466. /**
  30467. * Returns a height (y) value in the Worl system :
  30468. * the ground altitude at the coordinates (x, z) expressed in the World system.
  30469. * Returns the ground y position if (x, z) are outside the ground surface.
  30470. * Not pertinent if the ground is rotated.
  30471. */
  30472. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  30473. // express x and y in the ground local system
  30474. x -= this.position.x;
  30475. z -= this.position.z;
  30476. x /= this.scaling.x;
  30477. z /= this.scaling.z;
  30478. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  30479. return this.position.y;
  30480. }
  30481. if (!this._heightQuads || this._heightQuads.length == 0) {
  30482. this._initHeightQuads();
  30483. this._computeHeightQuads();
  30484. }
  30485. var facet = this._getFacetAt(x, z);
  30486. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  30487. // return y in the World system
  30488. return y * this.scaling.y + this.position.y;
  30489. };
  30490. /**
  30491. * Returns a normalized vector (Vector3) orthogonal to the ground
  30492. * at the ground coordinates (x, z) expressed in the World system.
  30493. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  30494. * Not pertinent if the ground is rotated.
  30495. */
  30496. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  30497. var normal = new BABYLON.Vector3(0, 1, 0);
  30498. this.getNormalAtCoordinatesToRef(x, z, normal);
  30499. return normal;
  30500. };
  30501. /**
  30502. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  30503. * at the ground coordinates (x, z) expressed in the World system.
  30504. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  30505. * Not pertinent if the ground is rotated.
  30506. */
  30507. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  30508. // express x and y in the ground local system
  30509. x -= this.position.x;
  30510. z -= this.position.z;
  30511. x /= this.scaling.x;
  30512. z /= this.scaling.z;
  30513. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  30514. return;
  30515. }
  30516. if (!this._heightQuads || this._heightQuads.length == 0) {
  30517. this._initHeightQuads();
  30518. this._computeHeightQuads();
  30519. }
  30520. var facet = this._getFacetAt(x, z);
  30521. ref.x = facet.x;
  30522. ref.y = facet.y;
  30523. ref.z = facet.z;
  30524. };
  30525. /**
  30526. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  30527. * if the ground has been updated.
  30528. * This can be used in the render loop
  30529. */
  30530. GroundMesh.prototype.updateCoordinateHeights = function () {
  30531. if (!this._heightQuads || this._heightQuads.length == 0) {
  30532. this._initHeightQuads();
  30533. }
  30534. this._computeHeightQuads();
  30535. };
  30536. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  30537. GroundMesh.prototype._getFacetAt = function (x, z) {
  30538. // retrieve col and row from x, z coordinates in the ground local system
  30539. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  30540. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  30541. var quad = this._heightQuads[row * this._subdivisions + col];
  30542. var facet;
  30543. if (z < quad.slope.x * x + quad.slope.y) {
  30544. facet = quad.facet1;
  30545. }
  30546. else {
  30547. facet = quad.facet2;
  30548. }
  30549. return facet;
  30550. };
  30551. // Creates and populates the heightMap array with "facet" elements :
  30552. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  30553. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  30554. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  30555. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  30556. GroundMesh.prototype._initHeightQuads = function () {
  30557. this._heightQuads = new Array();
  30558. for (var row = 0; row < this._subdivisions; row++) {
  30559. for (var col = 0; col < this._subdivisions; col++) {
  30560. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  30561. this._heightQuads[row * this._subdivisions + col] = quad;
  30562. }
  30563. }
  30564. };
  30565. // Compute each quad element values and update the the heightMap array :
  30566. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  30567. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  30568. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  30569. GroundMesh.prototype._computeHeightQuads = function () {
  30570. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30571. var v1 = BABYLON.Tmp.Vector3[0];
  30572. var v2 = BABYLON.Tmp.Vector3[1];
  30573. var v3 = BABYLON.Tmp.Vector3[2];
  30574. var v4 = BABYLON.Tmp.Vector3[3];
  30575. var v1v2 = BABYLON.Tmp.Vector3[4];
  30576. var v1v3 = BABYLON.Tmp.Vector3[5];
  30577. var v1v4 = BABYLON.Tmp.Vector3[6];
  30578. var norm1 = BABYLON.Tmp.Vector3[7];
  30579. var norm2 = BABYLON.Tmp.Vector3[8];
  30580. var i = 0;
  30581. var j = 0;
  30582. var k = 0;
  30583. var cd = 0; // 2D slope coefficient : z = cd * x + h
  30584. var h = 0;
  30585. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  30586. var d2 = 0;
  30587. for (var row = 0; row < this._subdivisions; row++) {
  30588. for (var col = 0; col < this._subdivisions; col++) {
  30589. i = col * 3;
  30590. j = row * (this._subdivisions + 1) * 3;
  30591. k = (row + 1) * (this._subdivisions + 1) * 3;
  30592. v1.x = positions[j + i];
  30593. v1.y = positions[j + i + 1];
  30594. v1.z = positions[j + i + 2];
  30595. v2.x = positions[j + i + 3];
  30596. v2.y = positions[j + i + 4];
  30597. v2.z = positions[j + i + 5];
  30598. v3.x = positions[k + i];
  30599. v3.y = positions[k + i + 1];
  30600. v3.z = positions[k + i + 2];
  30601. v4.x = positions[k + i + 3];
  30602. v4.y = positions[k + i + 4];
  30603. v4.z = positions[k + i + 5];
  30604. // 2D slope V1V4
  30605. cd = (v4.z - v1.z) / (v4.x - v1.x);
  30606. h = v1.z - cd * v1.x; // v1 belongs to the slope
  30607. // facet equations :
  30608. // we compute each facet normal vector
  30609. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  30610. // we compute the value d by applying the equation to v1 which belongs to the plane
  30611. // then we store the facet equation in a Vector4
  30612. v2.subtractToRef(v1, v1v2);
  30613. v3.subtractToRef(v1, v1v3);
  30614. v4.subtractToRef(v1, v1v4);
  30615. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  30616. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  30617. norm1.normalize();
  30618. norm2.normalize();
  30619. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  30620. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  30621. var quad = this._heightQuads[row * this._subdivisions + col];
  30622. quad.slope.copyFromFloats(cd, h);
  30623. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  30624. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  30625. }
  30626. }
  30627. };
  30628. return GroundMesh;
  30629. })(BABYLON.Mesh);
  30630. BABYLON.GroundMesh = GroundMesh;
  30631. })(BABYLON || (BABYLON = {}));
  30632. var BABYLON;
  30633. (function (BABYLON) {
  30634. var LinesMesh = (function (_super) {
  30635. __extends(LinesMesh, _super);
  30636. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  30637. if (parent === void 0) { parent = null; }
  30638. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  30639. this.color = new BABYLON.Color3(1, 1, 1);
  30640. this.alpha = 1;
  30641. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  30642. attributes: ["position"],
  30643. uniforms: ["worldViewProjection", "color"],
  30644. needAlphaBlending: true
  30645. });
  30646. }
  30647. Object.defineProperty(LinesMesh.prototype, "material", {
  30648. get: function () {
  30649. return this._colorShader;
  30650. },
  30651. enumerable: true,
  30652. configurable: true
  30653. });
  30654. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  30655. get: function () {
  30656. return false;
  30657. },
  30658. enumerable: true,
  30659. configurable: true
  30660. });
  30661. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  30662. get: function () {
  30663. return false;
  30664. },
  30665. enumerable: true,
  30666. configurable: true
  30667. });
  30668. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  30669. var engine = this.getScene().getEngine();
  30670. var indexToBind = this._geometry.getIndexBuffer();
  30671. // VBOs
  30672. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  30673. // Color
  30674. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  30675. };
  30676. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  30677. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  30678. return;
  30679. }
  30680. var engine = this.getScene().getEngine();
  30681. // Draw order
  30682. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  30683. };
  30684. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  30685. return null;
  30686. };
  30687. LinesMesh.prototype.dispose = function (doNotRecurse) {
  30688. this._colorShader.dispose();
  30689. _super.prototype.dispose.call(this, doNotRecurse);
  30690. };
  30691. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  30692. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  30693. };
  30694. return LinesMesh;
  30695. })(BABYLON.Mesh);
  30696. BABYLON.LinesMesh = LinesMesh;
  30697. })(BABYLON || (BABYLON = {}));
  30698. var BABYLON;
  30699. (function (BABYLON) {
  30700. var DebugLayer = (function () {
  30701. function DebugLayer(scene) {
  30702. var _this = this;
  30703. this._transformationMatrix = BABYLON.Matrix.Identity();
  30704. this._enabled = false;
  30705. this._labelsEnabled = false;
  30706. this._displayStatistics = true;
  30707. this._displayTree = false;
  30708. this._displayLogs = false;
  30709. this._skeletonViewers = new Array();
  30710. this._identityMatrix = BABYLON.Matrix.Identity();
  30711. this.axisRatio = 0.02;
  30712. this.accentColor = "orange";
  30713. this._scene = scene;
  30714. this._syncPositions = function () {
  30715. var engine = _this._scene.getEngine();
  30716. var canvasRect = engine.getRenderingCanvasClientRect();
  30717. if (_this._showUI) {
  30718. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30719. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30720. _this._statsDiv.style.width = "400px";
  30721. _this._statsDiv.style.height = "auto";
  30722. _this._statsSubsetDiv.style.maxHeight = "240px";
  30723. _this._optionsDiv.style.left = "0px";
  30724. _this._optionsDiv.style.top = "10px";
  30725. _this._optionsDiv.style.width = "200px";
  30726. _this._optionsDiv.style.height = "auto";
  30727. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30728. _this._logDiv.style.left = "0px";
  30729. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30730. _this._logDiv.style.width = "600px";
  30731. _this._logDiv.style.height = "160px";
  30732. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30733. _this._treeDiv.style.top = "10px";
  30734. _this._treeDiv.style.width = "300px";
  30735. _this._treeDiv.style.height = "auto";
  30736. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30737. }
  30738. _this._globalDiv.style.left = canvasRect.left + "px";
  30739. _this._globalDiv.style.top = canvasRect.top + "px";
  30740. _this._drawingCanvas.style.left = "0px";
  30741. _this._drawingCanvas.style.top = "0px";
  30742. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30743. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30744. var devicePixelRatio = window.devicePixelRatio || 1;
  30745. var context = _this._drawingContext;
  30746. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30747. context.mozBackingStorePixelRatio ||
  30748. context.msBackingStorePixelRatio ||
  30749. context.oBackingStorePixelRatio ||
  30750. context.backingStorePixelRatio || 1;
  30751. _this._ratio = devicePixelRatio / backingStoreRatio;
  30752. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30753. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30754. };
  30755. this._onCanvasClick = function (evt) {
  30756. _this._clickPosition = {
  30757. x: evt.clientX * _this._ratio,
  30758. y: evt.clientY * _this._ratio
  30759. };
  30760. };
  30761. this._syncUI = function () {
  30762. if (_this._showUI) {
  30763. if (_this._displayStatistics) {
  30764. _this._displayStats();
  30765. _this._statsDiv.style.display = "";
  30766. }
  30767. else {
  30768. _this._statsDiv.style.display = "none";
  30769. }
  30770. if (_this._displayLogs) {
  30771. _this._logDiv.style.display = "";
  30772. }
  30773. else {
  30774. _this._logDiv.style.display = "none";
  30775. }
  30776. if (_this._displayTree) {
  30777. _this._treeDiv.style.display = "";
  30778. if (_this._needToRefreshMeshesTree) {
  30779. _this._needToRefreshMeshesTree = false;
  30780. _this._refreshMeshesTreeContent();
  30781. }
  30782. }
  30783. else {
  30784. _this._treeDiv.style.display = "none";
  30785. }
  30786. }
  30787. };
  30788. this._syncData = function () {
  30789. if (_this._labelsEnabled || !_this._showUI) {
  30790. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30791. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30792. var engine = _this._scene.getEngine();
  30793. var viewport = _this._camera.viewport;
  30794. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  30795. // Meshes
  30796. var meshes = _this._camera.getActiveMeshes();
  30797. var index;
  30798. var projectedPosition;
  30799. for (index = 0; index < meshes.length; index++) {
  30800. var mesh = meshes.data[index];
  30801. var position = mesh.getBoundingInfo().boundingSphere.center;
  30802. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30803. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30804. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30805. }
  30806. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30807. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30808. }
  30809. }
  30810. // Cameras
  30811. var cameras = _this._scene.cameras;
  30812. for (index = 0; index < cameras.length; index++) {
  30813. var camera = cameras[index];
  30814. if (camera === _this._camera) {
  30815. continue;
  30816. }
  30817. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30818. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30819. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30820. _this._camera.detachControl(engine.getRenderingCanvas());
  30821. _this._camera = camera;
  30822. _this._camera.attachControl(engine.getRenderingCanvas());
  30823. }, function () { return "purple"; });
  30824. }
  30825. }
  30826. // Lights
  30827. var lights = _this._scene.lights;
  30828. for (index = 0; index < lights.length; index++) {
  30829. var light = lights[index];
  30830. if (light.position) {
  30831. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30832. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30833. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30834. light.setEnabled(!light.isEnabled());
  30835. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30836. }
  30837. }
  30838. }
  30839. }
  30840. _this._clickPosition = undefined;
  30841. };
  30842. }
  30843. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30844. while (this._treeSubsetDiv.hasChildNodes()) {
  30845. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30846. }
  30847. // Add meshes
  30848. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30849. sortedArray.sort(function (a, b) {
  30850. if (a.name === b.name) {
  30851. return 0;
  30852. }
  30853. return (a.name > b.name) ? 1 : -1;
  30854. });
  30855. for (var index = 0; index < sortedArray.length; index++) {
  30856. var mesh = sortedArray[index];
  30857. if (!mesh.isEnabled()) {
  30858. continue;
  30859. }
  30860. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30861. m.isVisible = element.checked;
  30862. }, mesh);
  30863. }
  30864. };
  30865. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30866. this._drawingContext.beginPath();
  30867. this._drawingContext.moveTo(zero.x, zero.y);
  30868. this._drawingContext.lineTo(unit.x, unit.y);
  30869. this._drawingContext.strokeStyle = color;
  30870. this._drawingContext.lineWidth = 4;
  30871. this._drawingContext.stroke();
  30872. this._drawingContext.font = "normal 14px Segoe UI";
  30873. this._drawingContext.fillStyle = color;
  30874. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30875. };
  30876. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30877. var position = mesh.getBoundingInfo().boundingSphere.center;
  30878. var worldMatrix = mesh.getWorldMatrix();
  30879. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30880. var unit = (unprojectedVector.subtract(position)).length();
  30881. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30882. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30883. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30884. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30885. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30886. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30887. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30888. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30889. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30890. };
  30891. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30892. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30893. this._drawingContext.font = "normal 12px Segoe UI";
  30894. var textMetrics = this._drawingContext.measureText(text);
  30895. var centerX = projectedPosition.x - textMetrics.width / 2;
  30896. var centerY = projectedPosition.y;
  30897. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30898. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30899. onClick();
  30900. }
  30901. this._drawingContext.beginPath();
  30902. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30903. this._drawingContext.fillStyle = getFillStyle();
  30904. this._drawingContext.globalAlpha = 0.5;
  30905. this._drawingContext.fill();
  30906. this._drawingContext.globalAlpha = 1.0;
  30907. this._drawingContext.strokeStyle = '#FFFFFF';
  30908. this._drawingContext.lineWidth = 1;
  30909. this._drawingContext.stroke();
  30910. this._drawingContext.fillStyle = "#FFFFFF";
  30911. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30912. this._drawingContext.beginPath();
  30913. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30914. this._drawingContext.fill();
  30915. }
  30916. };
  30917. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30918. if (!this._clickPosition) {
  30919. return false;
  30920. }
  30921. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30922. return false;
  30923. }
  30924. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30925. return false;
  30926. }
  30927. return true;
  30928. };
  30929. DebugLayer.prototype.isVisible = function () {
  30930. return this._enabled;
  30931. };
  30932. DebugLayer.prototype.hide = function () {
  30933. if (!this._enabled) {
  30934. return;
  30935. }
  30936. this._enabled = false;
  30937. var engine = this._scene.getEngine();
  30938. this._scene.unregisterBeforeRender(this._syncData);
  30939. this._scene.unregisterAfterRender(this._syncUI);
  30940. this._rootElement.removeChild(this._globalDiv);
  30941. this._scene.forceShowBoundingBoxes = false;
  30942. this._scene.forceWireframe = false;
  30943. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30944. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30945. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30946. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30947. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30948. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30949. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30950. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  30951. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  30952. this._scene.shadowsEnabled = true;
  30953. this._scene.particlesEnabled = true;
  30954. this._scene.postProcessesEnabled = true;
  30955. this._scene.collisionsEnabled = true;
  30956. this._scene.lightsEnabled = true;
  30957. this._scene.texturesEnabled = true;
  30958. this._scene.lensFlaresEnabled = true;
  30959. this._scene.proceduralTexturesEnabled = true;
  30960. this._scene.renderTargetsEnabled = true;
  30961. this._scene.probesEnabled = true;
  30962. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30963. this._clearSkeletonViewers();
  30964. };
  30965. DebugLayer.prototype._clearSkeletonViewers = function () {
  30966. for (var index = 0; index < this._skeletonViewers.length; index++) {
  30967. this._skeletonViewers[index].dispose();
  30968. }
  30969. this._skeletonViewers = [];
  30970. };
  30971. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  30972. if (showUI === void 0) { showUI = true; }
  30973. if (camera === void 0) { camera = null; }
  30974. if (rootElement === void 0) { rootElement = null; }
  30975. if (this._enabled) {
  30976. return;
  30977. }
  30978. this._enabled = true;
  30979. if (camera) {
  30980. this._camera = camera;
  30981. }
  30982. else {
  30983. this._camera = this._scene.activeCamera;
  30984. }
  30985. this._showUI = showUI;
  30986. var engine = this._scene.getEngine();
  30987. this._globalDiv = document.createElement("div");
  30988. this._rootElement = rootElement || document.body;
  30989. this._rootElement.appendChild(this._globalDiv);
  30990. this._generateDOMelements();
  30991. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30992. this._syncPositions();
  30993. this._scene.registerBeforeRender(this._syncData);
  30994. this._scene.registerAfterRender(this._syncUI);
  30995. };
  30996. DebugLayer.prototype._clearLabels = function () {
  30997. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30998. for (var index = 0; index < this._scene.meshes.length; index++) {
  30999. var mesh = this._scene.meshes[index];
  31000. mesh.renderOverlay = false;
  31001. }
  31002. };
  31003. DebugLayer.prototype._generateheader = function (root, text) {
  31004. var header = document.createElement("div");
  31005. header.innerHTML = text + "&nbsp;";
  31006. header.style.textAlign = "right";
  31007. header.style.width = "100%";
  31008. header.style.color = "white";
  31009. header.style.backgroundColor = "Black";
  31010. header.style.padding = "5px 5px 4px 0px";
  31011. header.style.marginLeft = "-5px";
  31012. header.style.fontWeight = "bold";
  31013. root.appendChild(header);
  31014. };
  31015. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  31016. var label = document.createElement("label");
  31017. label.innerHTML = title;
  31018. label.style.color = color;
  31019. root.appendChild(label);
  31020. root.appendChild(document.createElement("br"));
  31021. };
  31022. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  31023. if (tag === void 0) { tag = null; }
  31024. var label = document.createElement("label");
  31025. var boundingBoxesCheckbox = document.createElement("input");
  31026. boundingBoxesCheckbox.type = "checkbox";
  31027. boundingBoxesCheckbox.checked = initialState;
  31028. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  31029. task(evt.target, tag);
  31030. });
  31031. label.appendChild(boundingBoxesCheckbox);
  31032. var container = document.createElement("span");
  31033. var leftPart = document.createElement("span");
  31034. var rightPart = document.createElement("span");
  31035. rightPart.style.cssFloat = "right";
  31036. leftPart.innerHTML = leftTitle;
  31037. rightPart.innerHTML = rightTitle;
  31038. rightPart.style.fontSize = "12px";
  31039. rightPart.style.maxWidth = "200px";
  31040. container.appendChild(leftPart);
  31041. container.appendChild(rightPart);
  31042. label.appendChild(container);
  31043. root.appendChild(label);
  31044. root.appendChild(document.createElement("br"));
  31045. };
  31046. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  31047. if (tag === void 0) { tag = null; }
  31048. var label = document.createElement("label");
  31049. var checkBox = document.createElement("input");
  31050. checkBox.type = "checkbox";
  31051. checkBox.checked = initialState;
  31052. checkBox.addEventListener("change", function (evt) {
  31053. task(evt.target, tag);
  31054. });
  31055. label.appendChild(checkBox);
  31056. label.appendChild(document.createTextNode(title));
  31057. root.appendChild(label);
  31058. root.appendChild(document.createElement("br"));
  31059. };
  31060. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  31061. if (tag === void 0) { tag = null; }
  31062. var button = document.createElement("button");
  31063. button.innerHTML = title;
  31064. button.style.height = "24px";
  31065. button.style.width = "150px";
  31066. button.style.marginBottom = "5px";
  31067. button.style.color = "#444444";
  31068. button.style.border = "1px solid white";
  31069. button.className = "debugLayerButton";
  31070. button.addEventListener("click", function (evt) {
  31071. task(evt.target, tag);
  31072. });
  31073. root.appendChild(button);
  31074. root.appendChild(document.createElement("br"));
  31075. };
  31076. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  31077. if (tag === void 0) { tag = null; }
  31078. var label = document.createElement("label");
  31079. var boundingBoxesRadio = document.createElement("input");
  31080. boundingBoxesRadio.type = "radio";
  31081. boundingBoxesRadio.name = name;
  31082. boundingBoxesRadio.checked = initialState;
  31083. boundingBoxesRadio.addEventListener("change", function (evt) {
  31084. task(evt.target, tag);
  31085. });
  31086. label.appendChild(boundingBoxesRadio);
  31087. label.appendChild(document.createTextNode(title));
  31088. root.appendChild(label);
  31089. root.appendChild(document.createElement("br"));
  31090. };
  31091. DebugLayer.prototype._generateDOMelements = function () {
  31092. var _this = this;
  31093. this._globalDiv.id = "DebugLayer";
  31094. this._globalDiv.style.position = "absolute";
  31095. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  31096. this._globalDiv.style.fontSize = "14px";
  31097. this._globalDiv.style.color = "white";
  31098. // Drawing canvas
  31099. this._drawingCanvas = document.createElement("canvas");
  31100. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  31101. this._drawingCanvas.style.position = "absolute";
  31102. this._drawingCanvas.style.pointerEvents = "none";
  31103. this._drawingCanvas.style.backgroundColor = "transparent";
  31104. this._drawingContext = this._drawingCanvas.getContext("2d");
  31105. this._globalDiv.appendChild(this._drawingCanvas);
  31106. if (this._showUI) {
  31107. var background = "rgba(128, 128, 128, 0.4)";
  31108. var border = "rgb(180, 180, 180) solid 1px";
  31109. // Stats
  31110. this._statsDiv = document.createElement("div");
  31111. this._statsDiv.id = "DebugLayerStats";
  31112. this._statsDiv.style.border = border;
  31113. this._statsDiv.style.position = "absolute";
  31114. this._statsDiv.style.background = background;
  31115. this._statsDiv.style.padding = "0px 0px 0px 5px";
  31116. this._generateheader(this._statsDiv, "STATISTICS");
  31117. this._statsSubsetDiv = document.createElement("div");
  31118. this._statsSubsetDiv.style.paddingTop = "5px";
  31119. this._statsSubsetDiv.style.paddingBottom = "5px";
  31120. this._statsSubsetDiv.style.overflowY = "auto";
  31121. this._statsDiv.appendChild(this._statsSubsetDiv);
  31122. // Tree
  31123. this._treeDiv = document.createElement("div");
  31124. this._treeDiv.id = "DebugLayerTree";
  31125. this._treeDiv.style.border = border;
  31126. this._treeDiv.style.position = "absolute";
  31127. this._treeDiv.style.background = background;
  31128. this._treeDiv.style.padding = "0px 0px 0px 5px";
  31129. this._treeDiv.style.display = "none";
  31130. this._generateheader(this._treeDiv, "MESHES TREE");
  31131. this._treeSubsetDiv = document.createElement("div");
  31132. this._treeSubsetDiv.style.paddingTop = "5px";
  31133. this._treeSubsetDiv.style.paddingRight = "5px";
  31134. this._treeSubsetDiv.style.overflowY = "auto";
  31135. this._treeSubsetDiv.style.maxHeight = "300px";
  31136. this._treeDiv.appendChild(this._treeSubsetDiv);
  31137. this._needToRefreshMeshesTree = true;
  31138. // Logs
  31139. this._logDiv = document.createElement("div");
  31140. this._logDiv.style.border = border;
  31141. this._logDiv.id = "DebugLayerLogs";
  31142. this._logDiv.style.position = "absolute";
  31143. this._logDiv.style.background = background;
  31144. this._logDiv.style.padding = "0px 0px 0px 5px";
  31145. this._logDiv.style.display = "none";
  31146. this._generateheader(this._logDiv, "LOGS");
  31147. this._logSubsetDiv = document.createElement("div");
  31148. this._logSubsetDiv.style.height = "127px";
  31149. this._logSubsetDiv.style.paddingTop = "5px";
  31150. this._logSubsetDiv.style.overflowY = "auto";
  31151. this._logSubsetDiv.style.fontSize = "12px";
  31152. this._logSubsetDiv.style.fontFamily = "consolas";
  31153. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31154. this._logDiv.appendChild(this._logSubsetDiv);
  31155. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31156. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31157. };
  31158. // Options
  31159. this._optionsDiv = document.createElement("div");
  31160. this._optionsDiv.id = "DebugLayerOptions";
  31161. this._optionsDiv.style.border = border;
  31162. this._optionsDiv.style.position = "absolute";
  31163. this._optionsDiv.style.background = background;
  31164. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31165. this._optionsDiv.style.overflowY = "auto";
  31166. this._generateheader(this._optionsDiv, "OPTIONS");
  31167. this._optionsSubsetDiv = document.createElement("div");
  31168. this._optionsSubsetDiv.style.paddingTop = "5px";
  31169. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31170. this._optionsSubsetDiv.style.overflowY = "auto";
  31171. this._optionsSubsetDiv.style.maxHeight = "200px";
  31172. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31173. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31174. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31175. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31176. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31177. _this._displayTree = element.checked;
  31178. _this._needToRefreshMeshesTree = true;
  31179. });
  31180. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31181. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31182. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31183. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31184. _this._labelsEnabled = element.checked;
  31185. if (!_this._labelsEnabled) {
  31186. _this._clearLabels();
  31187. }
  31188. });
  31189. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31190. if (element.checked) {
  31191. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31192. }
  31193. else {
  31194. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31195. }
  31196. });
  31197. ;
  31198. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31199. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31200. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31201. if (element.checked) {
  31202. _this._scene.forceWireframe = false;
  31203. _this._scene.forcePointsCloud = false;
  31204. }
  31205. });
  31206. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31207. if (element.checked) {
  31208. _this._scene.forceWireframe = true;
  31209. _this._scene.forcePointsCloud = false;
  31210. }
  31211. });
  31212. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31213. if (element.checked) {
  31214. _this._scene.forceWireframe = false;
  31215. _this._scene.forcePointsCloud = true;
  31216. }
  31217. });
  31218. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31219. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31220. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31221. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31222. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31223. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31224. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31225. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31226. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31227. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  31228. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  31229. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31230. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31231. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31232. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31233. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31234. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31235. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31236. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31237. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31238. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31239. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  31240. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31241. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31242. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31243. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31244. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31245. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31246. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  31247. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31248. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31249. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31250. if (element.checked) {
  31251. _this._scene.headphone = true;
  31252. }
  31253. });
  31254. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31255. if (element.checked) {
  31256. _this._scene.headphone = false;
  31257. }
  31258. });
  31259. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31260. _this._scene.audioEnabled = !element.checked;
  31261. });
  31262. }
  31263. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31264. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  31265. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  31266. if (!element.checked) {
  31267. _this._clearSkeletonViewers();
  31268. return;
  31269. }
  31270. for (var index = 0; index < _this._scene.meshes.length; index++) {
  31271. var mesh = _this._scene.meshes[index];
  31272. if (mesh.skeleton) {
  31273. var found = false;
  31274. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  31275. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  31276. found = true;
  31277. break;
  31278. }
  31279. }
  31280. if (found) {
  31281. continue;
  31282. }
  31283. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  31284. viewer.isEnabled = true;
  31285. _this._skeletonViewers.push(viewer);
  31286. }
  31287. }
  31288. });
  31289. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31290. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31291. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31292. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  31293. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  31294. if (_this._camera) {
  31295. console.log(_this._camera);
  31296. }
  31297. else {
  31298. console.warn("No camera defined, or debug layer created before camera creation!");
  31299. }
  31300. });
  31301. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31302. this._globalDiv.appendChild(this._statsDiv);
  31303. this._globalDiv.appendChild(this._logDiv);
  31304. this._globalDiv.appendChild(this._optionsDiv);
  31305. this._globalDiv.appendChild(this._treeDiv);
  31306. }
  31307. };
  31308. DebugLayer.prototype._displayStats = function () {
  31309. var scene = this._scene;
  31310. var engine = scene.getEngine();
  31311. var glInfo = engine.getGlInfo();
  31312. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31313. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31314. + "<b>Count</b><br>"
  31315. + "Total meshes: " + scene.meshes.length + "<br>"
  31316. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31317. + "Total materials: " + scene.materials.length + "<br>"
  31318. + "Total textures: " + scene.textures.length + "<br>"
  31319. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31320. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31321. + "Active bones: " + scene.getActiveBones() + "<br>"
  31322. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31323. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  31324. + "<b>Duration</b><br>"
  31325. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31326. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31327. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31328. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31329. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31330. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31331. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  31332. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  31333. + "</div>"
  31334. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31335. + "<b>Extensions</b><br>"
  31336. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31337. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31338. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31339. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  31340. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31341. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  31342. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  31343. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  31344. + "</div><br>"
  31345. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31346. + "<b>Caps.</b><br>"
  31347. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31348. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31349. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  31350. + "<b>Info</b><br>"
  31351. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  31352. + glInfo.version + "<br>"
  31353. + "</div><br>"
  31354. + glInfo.renderer + "<br>";
  31355. if (this.customStatsFunction) {
  31356. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31357. }
  31358. };
  31359. return DebugLayer;
  31360. })();
  31361. BABYLON.DebugLayer = DebugLayer;
  31362. })(BABYLON || (BABYLON = {}));
  31363. var BABYLON;
  31364. (function (BABYLON) {
  31365. var DefaultLoadingScreen = (function () {
  31366. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  31367. var _this = this;
  31368. if (_loadingText === void 0) { _loadingText = ""; }
  31369. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  31370. this._renderingCanvas = _renderingCanvas;
  31371. this._loadingText = _loadingText;
  31372. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  31373. // Resize
  31374. this._resizeLoadingUI = function () {
  31375. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  31376. _this._loadingDiv.style.position = "absolute";
  31377. _this._loadingDiv.style.left = canvasRect.left + "px";
  31378. _this._loadingDiv.style.top = canvasRect.top + "px";
  31379. _this._loadingDiv.style.width = canvasRect.width + "px";
  31380. _this._loadingDiv.style.height = canvasRect.height + "px";
  31381. };
  31382. }
  31383. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  31384. var _this = this;
  31385. if (this._loadingDiv) {
  31386. // Do not add a loading screen if there is already one
  31387. return;
  31388. }
  31389. this._loadingDiv = document.createElement("div");
  31390. this._loadingDiv.id = "babylonjsLoadingDiv";
  31391. this._loadingDiv.style.opacity = "0";
  31392. this._loadingDiv.style.transition = "opacity 1.5s ease";
  31393. // Loading text
  31394. this._loadingTextDiv = document.createElement("div");
  31395. this._loadingTextDiv.style.position = "absolute";
  31396. this._loadingTextDiv.style.left = "0";
  31397. this._loadingTextDiv.style.top = "50%";
  31398. this._loadingTextDiv.style.marginTop = "80px";
  31399. this._loadingTextDiv.style.width = "100%";
  31400. this._loadingTextDiv.style.height = "20px";
  31401. this._loadingTextDiv.style.fontFamily = "Arial";
  31402. this._loadingTextDiv.style.fontSize = "14px";
  31403. this._loadingTextDiv.style.color = "white";
  31404. this._loadingTextDiv.style.textAlign = "center";
  31405. this._loadingTextDiv.innerHTML = "Loading";
  31406. this._loadingDiv.appendChild(this._loadingTextDiv);
  31407. //set the predefined text
  31408. this._loadingTextDiv.innerHTML = this._loadingText;
  31409. // Loading img
  31410. var imgBack = new Image();
  31411. 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==";
  31412. imgBack.style.position = "absolute";
  31413. imgBack.style.left = "50%";
  31414. imgBack.style.top = "50%";
  31415. imgBack.style.marginLeft = "-50px";
  31416. imgBack.style.marginTop = "-50px";
  31417. imgBack.style.transition = "transform 1.0s ease";
  31418. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  31419. var deg = 360;
  31420. var onTransitionEnd = function () {
  31421. deg += 360;
  31422. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  31423. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  31424. };
  31425. imgBack.addEventListener("transitionend", onTransitionEnd);
  31426. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  31427. this._loadingDiv.appendChild(imgBack);
  31428. // front image
  31429. var imgFront = new Image();
  31430. 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=";
  31431. imgFront.style.position = "absolute";
  31432. imgFront.style.left = "50%";
  31433. imgFront.style.top = "50%";
  31434. imgFront.style.marginLeft = "-50px";
  31435. imgFront.style.marginTop = "-50px";
  31436. this._loadingDiv.appendChild(imgFront);
  31437. this._resizeLoadingUI();
  31438. window.addEventListener("resize", this._resizeLoadingUI);
  31439. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  31440. document.body.appendChild(this._loadingDiv);
  31441. setTimeout(function () {
  31442. _this._loadingDiv.style.opacity = "1";
  31443. imgBack.style.transform = "rotateZ(360deg)";
  31444. imgBack.style.webkitTransform = "rotateZ(360deg)";
  31445. }, 0);
  31446. };
  31447. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  31448. var _this = this;
  31449. if (!this._loadingDiv) {
  31450. return;
  31451. }
  31452. var onTransitionEnd = function () {
  31453. if (!_this._loadingDiv) {
  31454. return;
  31455. }
  31456. document.body.removeChild(_this._loadingDiv);
  31457. window.removeEventListener("resize", _this._resizeLoadingUI);
  31458. _this._loadingDiv = null;
  31459. };
  31460. this._loadingDiv.style.opacity = "0";
  31461. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  31462. };
  31463. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  31464. set: function (text) {
  31465. this._loadingText = text;
  31466. if (this._loadingTextDiv) {
  31467. this._loadingTextDiv.innerHTML = this._loadingText;
  31468. }
  31469. },
  31470. enumerable: true,
  31471. configurable: true
  31472. });
  31473. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  31474. get: function () {
  31475. return this._loadingDivBackgroundColor;
  31476. },
  31477. set: function (color) {
  31478. this._loadingDivBackgroundColor = color;
  31479. if (!this._loadingDiv) {
  31480. return;
  31481. }
  31482. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  31483. },
  31484. enumerable: true,
  31485. configurable: true
  31486. });
  31487. return DefaultLoadingScreen;
  31488. })();
  31489. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  31490. })(BABYLON || (BABYLON = {}));
  31491. var BABYLON;
  31492. (function (BABYLON) {
  31493. var AudioEngine = (function () {
  31494. function AudioEngine() {
  31495. this._audioContext = null;
  31496. this._audioContextInitialized = false;
  31497. this.canUseWebAudio = false;
  31498. this.WarnedWebAudioUnsupported = false;
  31499. this.unlocked = false;
  31500. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  31501. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  31502. this.canUseWebAudio = true;
  31503. }
  31504. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  31505. this._unlockiOSaudio();
  31506. }
  31507. else {
  31508. this.unlocked = true;
  31509. }
  31510. }
  31511. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  31512. get: function () {
  31513. if (!this._audioContextInitialized) {
  31514. this._initializeAudioContext();
  31515. }
  31516. return this._audioContext;
  31517. },
  31518. enumerable: true,
  31519. configurable: true
  31520. });
  31521. AudioEngine.prototype._unlockiOSaudio = function () {
  31522. var _this = this;
  31523. var unlockaudio = function () {
  31524. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  31525. var source = _this.audioContext.createBufferSource();
  31526. source.buffer = buffer;
  31527. source.connect(_this.audioContext.destination);
  31528. source.start(0);
  31529. setTimeout(function () {
  31530. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  31531. _this.unlocked = true;
  31532. window.removeEventListener('touchend', unlockaudio, false);
  31533. if (_this.onAudioUnlocked) {
  31534. _this.onAudioUnlocked();
  31535. }
  31536. }
  31537. }, 0);
  31538. };
  31539. window.addEventListener('touchend', unlockaudio, false);
  31540. };
  31541. AudioEngine.prototype._initializeAudioContext = function () {
  31542. try {
  31543. if (this.canUseWebAudio) {
  31544. this._audioContext = new AudioContext();
  31545. // create a global volume gain node
  31546. this.masterGain = this._audioContext.createGain();
  31547. this.masterGain.gain.value = 1;
  31548. this.masterGain.connect(this._audioContext.destination);
  31549. this._audioContextInitialized = true;
  31550. }
  31551. }
  31552. catch (e) {
  31553. this.canUseWebAudio = false;
  31554. BABYLON.Tools.Error("Web Audio: " + e.message);
  31555. }
  31556. };
  31557. AudioEngine.prototype.dispose = function () {
  31558. if (this.canUseWebAudio && this._audioContextInitialized) {
  31559. if (this._connectedAnalyser) {
  31560. this._connectedAnalyser.stopDebugCanvas();
  31561. this._connectedAnalyser.dispose();
  31562. this.masterGain.disconnect();
  31563. this.masterGain.connect(this._audioContext.destination);
  31564. this._connectedAnalyser = null;
  31565. }
  31566. this.masterGain.gain.value = 1;
  31567. }
  31568. this.WarnedWebAudioUnsupported = false;
  31569. };
  31570. AudioEngine.prototype.getGlobalVolume = function () {
  31571. if (this.canUseWebAudio && this._audioContextInitialized) {
  31572. return this.masterGain.gain.value;
  31573. }
  31574. else {
  31575. return -1;
  31576. }
  31577. };
  31578. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  31579. if (this.canUseWebAudio && this._audioContextInitialized) {
  31580. this.masterGain.gain.value = newVolume;
  31581. }
  31582. };
  31583. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  31584. if (this._connectedAnalyser) {
  31585. this._connectedAnalyser.stopDebugCanvas();
  31586. }
  31587. if (this.canUseWebAudio && this._audioContextInitialized) {
  31588. this._connectedAnalyser = analyser;
  31589. this.masterGain.disconnect();
  31590. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  31591. }
  31592. };
  31593. return AudioEngine;
  31594. })();
  31595. BABYLON.AudioEngine = AudioEngine;
  31596. })(BABYLON || (BABYLON = {}));
  31597. var BABYLON;
  31598. (function (BABYLON) {
  31599. var Sound = (function () {
  31600. /**
  31601. * Create a sound and attach it to a scene
  31602. * @param name Name of your sound
  31603. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  31604. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  31605. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  31606. */
  31607. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  31608. var _this = this;
  31609. this.autoplay = false;
  31610. this.loop = false;
  31611. this.useCustomAttenuation = false;
  31612. this.spatialSound = false;
  31613. this.refDistance = 1;
  31614. this.rolloffFactor = 1;
  31615. this.maxDistance = 100;
  31616. this.distanceModel = "linear";
  31617. this._panningModel = "equalpower";
  31618. this._playbackRate = 1;
  31619. this._streaming = false;
  31620. this._startTime = 0;
  31621. this._startOffset = 0;
  31622. this._position = BABYLON.Vector3.Zero();
  31623. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  31624. this._volume = 1;
  31625. this._isLoaded = false;
  31626. this._isReadyToPlay = false;
  31627. this.isPlaying = false;
  31628. this.isPaused = false;
  31629. this._isDirectional = false;
  31630. // Used if you'd like to create a directional sound.
  31631. // If not set, the sound will be omnidirectional
  31632. this._coneInnerAngle = 360;
  31633. this._coneOuterAngle = 360;
  31634. this._coneOuterGain = 0;
  31635. this._isOutputConnected = false;
  31636. this.name = name;
  31637. this._scene = scene;
  31638. this._readyToPlayCallback = readyToPlayCallback;
  31639. // Default custom attenuation function is a linear attenuation
  31640. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  31641. if (currentDistance < maxDistance) {
  31642. return currentVolume * (1 - currentDistance / maxDistance);
  31643. }
  31644. else {
  31645. return 0;
  31646. }
  31647. };
  31648. if (options) {
  31649. this.autoplay = options.autoplay || false;
  31650. this.loop = options.loop || false;
  31651. // if volume === 0, we need another way to check this option
  31652. if (options.volume !== undefined) {
  31653. this._volume = options.volume;
  31654. }
  31655. this.spatialSound = options.spatialSound || false;
  31656. this.maxDistance = options.maxDistance || 100;
  31657. this.useCustomAttenuation = options.useCustomAttenuation || false;
  31658. this.rolloffFactor = options.rolloffFactor || 1;
  31659. this.refDistance = options.refDistance || 1;
  31660. this.distanceModel = options.distanceModel || "linear";
  31661. this._playbackRate = options.playbackRate || 1;
  31662. this._streaming = options.streaming || false;
  31663. }
  31664. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31665. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  31666. this._soundGain.gain.value = this._volume;
  31667. this._inputAudioNode = this._soundGain;
  31668. this._ouputAudioNode = this._soundGain;
  31669. if (this.spatialSound) {
  31670. this._createSpatialParameters();
  31671. }
  31672. this._scene.mainSoundTrack.AddSound(this);
  31673. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  31674. if (urlOrArrayBuffer) {
  31675. // If it's an URL
  31676. if (typeof (urlOrArrayBuffer) === "string") {
  31677. // Loading sound using XHR2
  31678. if (!this._streaming) {
  31679. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  31680. }
  31681. else {
  31682. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  31683. this._htmlAudioElement.controls = false;
  31684. this._htmlAudioElement.loop = this.loop;
  31685. this._htmlAudioElement.crossOrigin = "anonymous";
  31686. this._htmlAudioElement.preload = "auto";
  31687. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  31688. _this._isReadyToPlay = true;
  31689. if (_this.autoplay) {
  31690. _this.play();
  31691. }
  31692. if (_this._readyToPlayCallback) {
  31693. _this._readyToPlayCallback();
  31694. }
  31695. });
  31696. document.body.appendChild(this._htmlAudioElement);
  31697. }
  31698. }
  31699. else {
  31700. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  31701. if (urlOrArrayBuffer.byteLength > 0) {
  31702. this._soundLoaded(urlOrArrayBuffer);
  31703. }
  31704. }
  31705. else {
  31706. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  31707. }
  31708. }
  31709. }
  31710. }
  31711. else {
  31712. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  31713. this._scene.mainSoundTrack.AddSound(this);
  31714. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  31715. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  31716. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  31717. }
  31718. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  31719. if (this._readyToPlayCallback) {
  31720. window.setTimeout(function () {
  31721. _this._readyToPlayCallback();
  31722. }, 1000);
  31723. }
  31724. }
  31725. }
  31726. Sound.prototype.dispose = function () {
  31727. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  31728. if (this.isPlaying) {
  31729. this.stop();
  31730. }
  31731. this._isReadyToPlay = false;
  31732. if (this.soundTrackId === -1) {
  31733. this._scene.mainSoundTrack.RemoveSound(this);
  31734. }
  31735. else {
  31736. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  31737. }
  31738. if (this._soundGain) {
  31739. this._soundGain.disconnect();
  31740. this._soundGain = null;
  31741. }
  31742. if (this._soundPanner) {
  31743. this._soundPanner.disconnect();
  31744. this._soundPanner = null;
  31745. }
  31746. if (this._soundSource) {
  31747. this._soundSource.disconnect();
  31748. this._soundSource = null;
  31749. }
  31750. this._audioBuffer = null;
  31751. if (this._htmlAudioElement) {
  31752. this._htmlAudioElement.pause();
  31753. this._htmlAudioElement.src = "";
  31754. document.body.removeChild(this._htmlAudioElement);
  31755. }
  31756. if (this._connectedMesh) {
  31757. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  31758. this._connectedMesh = null;
  31759. }
  31760. }
  31761. };
  31762. Sound.prototype._soundLoaded = function (audioData) {
  31763. var _this = this;
  31764. this._isLoaded = true;
  31765. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  31766. _this._audioBuffer = buffer;
  31767. _this._isReadyToPlay = true;
  31768. if (_this.autoplay) {
  31769. _this.play();
  31770. }
  31771. if (_this._readyToPlayCallback) {
  31772. _this._readyToPlayCallback();
  31773. }
  31774. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  31775. };
  31776. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  31777. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31778. this._audioBuffer = audioBuffer;
  31779. this._isReadyToPlay = true;
  31780. }
  31781. };
  31782. Sound.prototype.updateOptions = function (options) {
  31783. if (options) {
  31784. this.loop = options.loop || this.loop;
  31785. this.maxDistance = options.maxDistance || this.maxDistance;
  31786. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  31787. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  31788. this.refDistance = options.refDistance || this.refDistance;
  31789. this.distanceModel = options.distanceModel || this.distanceModel;
  31790. this._playbackRate = options.playbackRate || this._playbackRate;
  31791. this._updateSpatialParameters();
  31792. if (this.isPlaying) {
  31793. if (this._streaming) {
  31794. this._htmlAudioElement.playbackRate = this._playbackRate;
  31795. }
  31796. else {
  31797. this._soundSource.playbackRate.value = this._playbackRate;
  31798. }
  31799. }
  31800. }
  31801. };
  31802. Sound.prototype._createSpatialParameters = function () {
  31803. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31804. if (this._scene.headphone) {
  31805. this._panningModel = "HRTF";
  31806. }
  31807. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  31808. this._updateSpatialParameters();
  31809. this._soundPanner.connect(this._ouputAudioNode);
  31810. this._inputAudioNode = this._soundPanner;
  31811. }
  31812. };
  31813. Sound.prototype._updateSpatialParameters = function () {
  31814. if (this.spatialSound) {
  31815. if (this.useCustomAttenuation) {
  31816. // Tricks to disable in a way embedded Web Audio attenuation
  31817. this._soundPanner.distanceModel = "linear";
  31818. this._soundPanner.maxDistance = Number.MAX_VALUE;
  31819. this._soundPanner.refDistance = 1;
  31820. this._soundPanner.rolloffFactor = 1;
  31821. this._soundPanner.panningModel = this._panningModel;
  31822. }
  31823. else {
  31824. this._soundPanner.distanceModel = this.distanceModel;
  31825. this._soundPanner.maxDistance = this.maxDistance;
  31826. this._soundPanner.refDistance = this.refDistance;
  31827. this._soundPanner.rolloffFactor = this.rolloffFactor;
  31828. this._soundPanner.panningModel = this._panningModel;
  31829. }
  31830. }
  31831. };
  31832. Sound.prototype.switchPanningModelToHRTF = function () {
  31833. this._panningModel = "HRTF";
  31834. this._switchPanningModel();
  31835. };
  31836. Sound.prototype.switchPanningModelToEqualPower = function () {
  31837. this._panningModel = "equalpower";
  31838. this._switchPanningModel();
  31839. };
  31840. Sound.prototype._switchPanningModel = function () {
  31841. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31842. this._soundPanner.panningModel = this._panningModel;
  31843. }
  31844. };
  31845. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  31846. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31847. if (this._isOutputConnected) {
  31848. this._ouputAudioNode.disconnect();
  31849. }
  31850. this._ouputAudioNode.connect(soundTrackAudioNode);
  31851. this._isOutputConnected = true;
  31852. }
  31853. };
  31854. /**
  31855. * Transform this sound into a directional source
  31856. * @param coneInnerAngle Size of the inner cone in degree
  31857. * @param coneOuterAngle Size of the outer cone in degree
  31858. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  31859. */
  31860. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  31861. if (coneOuterAngle < coneInnerAngle) {
  31862. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  31863. return;
  31864. }
  31865. this._coneInnerAngle = coneInnerAngle;
  31866. this._coneOuterAngle = coneOuterAngle;
  31867. this._coneOuterGain = coneOuterGain;
  31868. this._isDirectional = true;
  31869. if (this.isPlaying && this.loop) {
  31870. this.stop();
  31871. this.play();
  31872. }
  31873. };
  31874. Sound.prototype.setPosition = function (newPosition) {
  31875. this._position = newPosition;
  31876. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31877. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31878. }
  31879. };
  31880. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  31881. this._localDirection = newLocalDirection;
  31882. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  31883. this._updateDirection();
  31884. }
  31885. };
  31886. Sound.prototype._updateDirection = function () {
  31887. var mat = this._connectedMesh.getWorldMatrix();
  31888. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  31889. direction.normalize();
  31890. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  31891. };
  31892. Sound.prototype.updateDistanceFromListener = function () {
  31893. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  31894. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  31895. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  31896. }
  31897. };
  31898. Sound.prototype.setAttenuationFunction = function (callback) {
  31899. this._customAttenuationFunction = callback;
  31900. };
  31901. /**
  31902. * Play the sound
  31903. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  31904. */
  31905. Sound.prototype.play = function (time) {
  31906. var _this = this;
  31907. if (this._isReadyToPlay && this._scene.audioEnabled) {
  31908. try {
  31909. if (this._startOffset < 0) {
  31910. time = -this._startOffset;
  31911. this._startOffset = 0;
  31912. }
  31913. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  31914. if (!this._soundSource || !this._streamingSource) {
  31915. if (this.spatialSound) {
  31916. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31917. if (this._isDirectional) {
  31918. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  31919. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  31920. this._soundPanner.coneOuterGain = this._coneOuterGain;
  31921. if (this._connectedMesh) {
  31922. this._updateDirection();
  31923. }
  31924. else {
  31925. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  31926. }
  31927. }
  31928. }
  31929. }
  31930. if (this._streaming) {
  31931. if (!this._streamingSource) {
  31932. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  31933. this._htmlAudioElement.onended = function () { _this._onended(); };
  31934. this._htmlAudioElement.playbackRate = this._playbackRate;
  31935. }
  31936. this._streamingSource.disconnect();
  31937. this._streamingSource.connect(this._inputAudioNode);
  31938. this._htmlAudioElement.play();
  31939. }
  31940. else {
  31941. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  31942. this._soundSource.buffer = this._audioBuffer;
  31943. this._soundSource.connect(this._inputAudioNode);
  31944. this._soundSource.loop = this.loop;
  31945. this._soundSource.playbackRate.value = this._playbackRate;
  31946. this._soundSource.onended = function () { _this._onended(); };
  31947. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  31948. }
  31949. this._startTime = startTime;
  31950. this.isPlaying = true;
  31951. this.isPaused = false;
  31952. }
  31953. catch (ex) {
  31954. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  31955. }
  31956. }
  31957. };
  31958. Sound.prototype._onended = function () {
  31959. this.isPlaying = false;
  31960. if (this.onended) {
  31961. this.onended();
  31962. }
  31963. };
  31964. /**
  31965. * Stop the sound
  31966. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  31967. */
  31968. Sound.prototype.stop = function (time) {
  31969. if (this.isPlaying) {
  31970. if (this._streaming) {
  31971. this._htmlAudioElement.pause();
  31972. // Test needed for Firefox or it will generate an Invalid State Error
  31973. if (this._htmlAudioElement.currentTime > 0) {
  31974. this._htmlAudioElement.currentTime = 0;
  31975. }
  31976. }
  31977. else {
  31978. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  31979. this._soundSource.stop(stopTime);
  31980. if (!this.isPaused) {
  31981. this._startOffset = 0;
  31982. }
  31983. }
  31984. this.isPlaying = false;
  31985. }
  31986. };
  31987. Sound.prototype.pause = function () {
  31988. if (this.isPlaying) {
  31989. this.isPaused = true;
  31990. if (this._streaming) {
  31991. this._htmlAudioElement.pause();
  31992. }
  31993. else {
  31994. this.stop(0);
  31995. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  31996. }
  31997. }
  31998. };
  31999. Sound.prototype.setVolume = function (newVolume, time) {
  32000. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32001. if (time) {
  32002. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  32003. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  32004. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  32005. }
  32006. else {
  32007. this._soundGain.gain.value = newVolume;
  32008. }
  32009. }
  32010. this._volume = newVolume;
  32011. };
  32012. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  32013. this._playbackRate = newPlaybackRate;
  32014. if (this.isPlaying) {
  32015. if (this._streaming) {
  32016. this._htmlAudioElement.playbackRate = this._playbackRate;
  32017. }
  32018. else {
  32019. this._soundSource.playbackRate.value = this._playbackRate;
  32020. }
  32021. }
  32022. };
  32023. Sound.prototype.getVolume = function () {
  32024. return this._volume;
  32025. };
  32026. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  32027. var _this = this;
  32028. if (this._connectedMesh) {
  32029. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  32030. this._registerFunc = null;
  32031. }
  32032. this._connectedMesh = meshToConnectTo;
  32033. if (!this.spatialSound) {
  32034. this.spatialSound = true;
  32035. this._createSpatialParameters();
  32036. if (this.isPlaying && this.loop) {
  32037. this.stop();
  32038. this.play();
  32039. }
  32040. }
  32041. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  32042. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  32043. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  32044. };
  32045. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  32046. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  32047. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  32048. this._updateDirection();
  32049. }
  32050. };
  32051. Sound.prototype.clone = function () {
  32052. var _this = this;
  32053. if (!this._streaming) {
  32054. var setBufferAndRun = function () {
  32055. if (_this._isReadyToPlay) {
  32056. clonedSound._audioBuffer = _this.getAudioBuffer();
  32057. clonedSound._isReadyToPlay = true;
  32058. if (clonedSound.autoplay) {
  32059. clonedSound.play();
  32060. }
  32061. }
  32062. else {
  32063. window.setTimeout(setBufferAndRun, 300);
  32064. }
  32065. };
  32066. var currentOptions = {
  32067. autoplay: this.autoplay, loop: this.loop,
  32068. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  32069. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  32070. refDistance: this.refDistance, distanceModel: this.distanceModel
  32071. };
  32072. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  32073. if (this.useCustomAttenuation) {
  32074. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  32075. }
  32076. clonedSound.setPosition(this._position);
  32077. clonedSound.setPlaybackRate(this._playbackRate);
  32078. setBufferAndRun();
  32079. return clonedSound;
  32080. }
  32081. else {
  32082. return null;
  32083. }
  32084. };
  32085. Sound.prototype.getAudioBuffer = function () {
  32086. return this._audioBuffer;
  32087. };
  32088. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  32089. var soundName = parsedSound.name;
  32090. var soundUrl;
  32091. if (parsedSound.url) {
  32092. soundUrl = rootUrl + parsedSound.url;
  32093. }
  32094. else {
  32095. soundUrl = rootUrl + soundName;
  32096. }
  32097. var options = {
  32098. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  32099. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  32100. rolloffFactor: parsedSound.rolloffFactor,
  32101. refDistance: parsedSound.refDistance,
  32102. distanceModel: parsedSound.distanceModel,
  32103. playbackRate: parsedSound.playbackRate
  32104. };
  32105. var newSound;
  32106. if (!sourceSound) {
  32107. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  32108. scene._addPendingData(newSound);
  32109. }
  32110. else {
  32111. var setBufferAndRun = function () {
  32112. if (sourceSound._isReadyToPlay) {
  32113. newSound._audioBuffer = sourceSound.getAudioBuffer();
  32114. newSound._isReadyToPlay = true;
  32115. if (newSound.autoplay) {
  32116. newSound.play();
  32117. }
  32118. }
  32119. else {
  32120. window.setTimeout(setBufferAndRun, 300);
  32121. }
  32122. };
  32123. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  32124. setBufferAndRun();
  32125. }
  32126. if (parsedSound.position) {
  32127. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  32128. newSound.setPosition(soundPosition);
  32129. }
  32130. if (parsedSound.isDirectional) {
  32131. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  32132. if (parsedSound.localDirectionToMesh) {
  32133. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  32134. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  32135. }
  32136. }
  32137. if (parsedSound.connectedMeshId) {
  32138. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  32139. if (connectedMesh) {
  32140. newSound.attachToMesh(connectedMesh);
  32141. }
  32142. }
  32143. return newSound;
  32144. };
  32145. return Sound;
  32146. })();
  32147. BABYLON.Sound = Sound;
  32148. })(BABYLON || (BABYLON = {}));
  32149. var BABYLON;
  32150. (function (BABYLON) {
  32151. var SoundTrack = (function () {
  32152. function SoundTrack(scene, options) {
  32153. this.id = -1;
  32154. this._isMainTrack = false;
  32155. this._isInitialized = false;
  32156. this._scene = scene;
  32157. this.soundCollection = new Array();
  32158. this._options = options;
  32159. if (!this._isMainTrack) {
  32160. this._scene.soundTracks.push(this);
  32161. this.id = this._scene.soundTracks.length - 1;
  32162. }
  32163. }
  32164. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  32165. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32166. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  32167. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  32168. if (this._options) {
  32169. if (this._options.volume) {
  32170. this._outputAudioNode.gain.value = this._options.volume;
  32171. }
  32172. if (this._options.mainTrack) {
  32173. this._isMainTrack = this._options.mainTrack;
  32174. }
  32175. }
  32176. this._isInitialized = true;
  32177. }
  32178. };
  32179. SoundTrack.prototype.dispose = function () {
  32180. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32181. if (this._connectedAnalyser) {
  32182. this._connectedAnalyser.stopDebugCanvas();
  32183. }
  32184. while (this.soundCollection.length) {
  32185. this.soundCollection[0].dispose();
  32186. }
  32187. if (this._outputAudioNode) {
  32188. this._outputAudioNode.disconnect();
  32189. }
  32190. this._outputAudioNode = null;
  32191. }
  32192. };
  32193. SoundTrack.prototype.AddSound = function (sound) {
  32194. if (!this._isInitialized) {
  32195. this._initializeSoundTrackAudioGraph();
  32196. }
  32197. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32198. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  32199. }
  32200. if (sound.soundTrackId) {
  32201. if (sound.soundTrackId === -1) {
  32202. this._scene.mainSoundTrack.RemoveSound(sound);
  32203. }
  32204. else {
  32205. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  32206. }
  32207. }
  32208. this.soundCollection.push(sound);
  32209. sound.soundTrackId = this.id;
  32210. };
  32211. SoundTrack.prototype.RemoveSound = function (sound) {
  32212. var index = this.soundCollection.indexOf(sound);
  32213. if (index !== -1) {
  32214. this.soundCollection.splice(index, 1);
  32215. }
  32216. };
  32217. SoundTrack.prototype.setVolume = function (newVolume) {
  32218. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32219. this._outputAudioNode.gain.value = newVolume;
  32220. }
  32221. };
  32222. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  32223. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32224. for (var i = 0; i < this.soundCollection.length; i++) {
  32225. this.soundCollection[i].switchPanningModelToHRTF();
  32226. }
  32227. }
  32228. };
  32229. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  32230. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32231. for (var i = 0; i < this.soundCollection.length; i++) {
  32232. this.soundCollection[i].switchPanningModelToEqualPower();
  32233. }
  32234. }
  32235. };
  32236. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  32237. if (this._connectedAnalyser) {
  32238. this._connectedAnalyser.stopDebugCanvas();
  32239. }
  32240. this._connectedAnalyser = analyser;
  32241. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32242. this._outputAudioNode.disconnect();
  32243. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  32244. }
  32245. };
  32246. return SoundTrack;
  32247. })();
  32248. BABYLON.SoundTrack = SoundTrack;
  32249. })(BABYLON || (BABYLON = {}));
  32250. var BABYLON;
  32251. (function (BABYLON) {
  32252. var SIMDVector3 = (function () {
  32253. function SIMDVector3() {
  32254. }
  32255. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  32256. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  32257. var m0 = SIMD.float32x4.load(transformation.m, 0);
  32258. var m1 = SIMD.float32x4.load(transformation.m, 4);
  32259. var m2 = SIMD.float32x4.load(transformation.m, 8);
  32260. var m3 = SIMD.float32x4.load(transformation.m, 12);
  32261. 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));
  32262. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  32263. SIMD.float32x4.storeXYZ(result._data, 0, r);
  32264. };
  32265. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  32266. var v0 = SIMD.float32x4.splat(x);
  32267. var v1 = SIMD.float32x4.splat(y);
  32268. var v2 = SIMD.float32x4.splat(z);
  32269. var m0 = SIMD.float32x4.load(transformation.m, 0);
  32270. var m1 = SIMD.float32x4.load(transformation.m, 4);
  32271. var m2 = SIMD.float32x4.load(transformation.m, 8);
  32272. var m3 = SIMD.float32x4.load(transformation.m, 12);
  32273. 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));
  32274. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  32275. SIMD.float32x4.storeXYZ(result._data, 0, r);
  32276. };
  32277. return SIMDVector3;
  32278. })();
  32279. BABYLON.SIMDVector3 = SIMDVector3;
  32280. var SIMDMatrix = (function () {
  32281. function SIMDMatrix() {
  32282. }
  32283. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  32284. if (offset === void 0) { offset = 0; }
  32285. var tm = this.m;
  32286. var om = other.m;
  32287. var om0 = SIMD.float32x4.load(om, 0);
  32288. var om1 = SIMD.float32x4.load(om, 4);
  32289. var om2 = SIMD.float32x4.load(om, 8);
  32290. var om3 = SIMD.float32x4.load(om, 12);
  32291. var tm0 = SIMD.float32x4.load(tm, 0);
  32292. 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)))));
  32293. var tm1 = SIMD.float32x4.load(tm, 4);
  32294. 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)))));
  32295. var tm2 = SIMD.float32x4.load(tm, 8);
  32296. 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)))));
  32297. var tm3 = SIMD.float32x4.load(tm, 12);
  32298. 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)))));
  32299. };
  32300. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  32301. var src = this.m;
  32302. var dest = other.m;
  32303. var row0, row1, row2, row3;
  32304. var tmp1;
  32305. var minor0, minor1, minor2, minor3;
  32306. var det;
  32307. // Load the 4 rows
  32308. var src0 = SIMD.float32x4.load(src, 0);
  32309. var src1 = SIMD.float32x4.load(src, 4);
  32310. var src2 = SIMD.float32x4.load(src, 8);
  32311. var src3 = SIMD.float32x4.load(src, 12);
  32312. // Transpose the source matrix. Sort of. Not a true transpose operation
  32313. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  32314. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  32315. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  32316. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  32317. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  32318. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  32319. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  32320. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  32321. // This is a true transposition, but it will lead to an incorrect result
  32322. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  32323. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  32324. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  32325. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  32326. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  32327. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  32328. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  32329. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  32330. // ----
  32331. tmp1 = SIMD.float32x4.mul(row2, row3);
  32332. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32333. minor0 = SIMD.float32x4.mul(row1, tmp1);
  32334. minor1 = SIMD.float32x4.mul(row0, tmp1);
  32335. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32336. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  32337. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  32338. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  32339. // ----
  32340. tmp1 = SIMD.float32x4.mul(row1, row2);
  32341. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32342. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  32343. minor3 = SIMD.float32x4.mul(row0, tmp1);
  32344. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32345. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  32346. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  32347. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  32348. // ----
  32349. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  32350. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32351. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  32352. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  32353. minor2 = SIMD.float32x4.mul(row0, tmp1);
  32354. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32355. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  32356. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  32357. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  32358. // ----
  32359. tmp1 = SIMD.float32x4.mul(row0, row1);
  32360. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32361. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  32362. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  32363. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32364. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  32365. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  32366. // ----
  32367. tmp1 = SIMD.float32x4.mul(row0, row3);
  32368. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32369. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  32370. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  32371. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32372. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  32373. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  32374. // ----
  32375. tmp1 = SIMD.float32x4.mul(row0, row2);
  32376. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32377. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  32378. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  32379. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32380. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  32381. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  32382. // Compute determinant
  32383. det = SIMD.float32x4.mul(row0, minor0);
  32384. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  32385. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  32386. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  32387. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  32388. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  32389. // These shuffles aren't necessary if the faulty transposition is done
  32390. // up at the top of this function.
  32391. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  32392. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  32393. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  32394. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  32395. // Compute final values by multiplying with 1/det
  32396. minor0 = SIMD.float32x4.mul(det, minor0);
  32397. minor1 = SIMD.float32x4.mul(det, minor1);
  32398. minor2 = SIMD.float32x4.mul(det, minor2);
  32399. minor3 = SIMD.float32x4.mul(det, minor3);
  32400. SIMD.float32x4.store(dest, 0, minor0);
  32401. SIMD.float32x4.store(dest, 4, minor1);
  32402. SIMD.float32x4.store(dest, 8, minor2);
  32403. SIMD.float32x4.store(dest, 12, minor3);
  32404. return this;
  32405. };
  32406. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  32407. var out = result.m;
  32408. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  32409. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  32410. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  32411. // cc.kmVec3Subtract(f, pCenter, pEye);
  32412. var f = SIMD.float32x4.sub(center, eye);
  32413. // cc.kmVec3Normalize(f, f);
  32414. var tmp = SIMD.float32x4.mul(f, f);
  32415. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32416. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32417. // cc.kmVec3Assign(up, pUp);
  32418. // cc.kmVec3Normalize(up, up);
  32419. tmp = SIMD.float32x4.mul(up, up);
  32420. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32421. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32422. // cc.kmVec3Cross(s, f, up);
  32423. 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)));
  32424. // cc.kmVec3Normalize(s, s);
  32425. tmp = SIMD.float32x4.mul(s, s);
  32426. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32427. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32428. // cc.kmVec3Cross(u, s, f);
  32429. 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)));
  32430. // cc.kmVec3Normalize(s, s);
  32431. tmp = SIMD.float32x4.mul(s, s);
  32432. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32433. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32434. var zero = SIMD.float32x4.splat(0.0);
  32435. s = SIMD.float32x4.neg(s);
  32436. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  32437. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  32438. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  32439. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  32440. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  32441. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  32442. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  32443. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  32444. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  32445. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  32446. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  32447. var b3 = SIMD.float32x4.neg(eye);
  32448. b3 = SIMD.float32x4.withW(b3, 1.0);
  32449. 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)))));
  32450. 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)))));
  32451. 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)))));
  32452. 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)))));
  32453. };
  32454. return SIMDMatrix;
  32455. })();
  32456. BABYLON.SIMDMatrix = SIMDMatrix;
  32457. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  32458. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  32459. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  32460. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  32461. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  32462. var SIMDHelper = (function () {
  32463. function SIMDHelper() {
  32464. }
  32465. Object.defineProperty(SIMDHelper, "IsEnabled", {
  32466. get: function () {
  32467. return SIMDHelper._isEnabled;
  32468. },
  32469. enumerable: true,
  32470. configurable: true
  32471. });
  32472. SIMDHelper.DisableSIMD = function () {
  32473. // Replace functions
  32474. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  32475. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  32476. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  32477. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  32478. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  32479. SIMDHelper._isEnabled = false;
  32480. };
  32481. SIMDHelper.EnableSIMD = function () {
  32482. if (window.SIMD === undefined) {
  32483. return;
  32484. }
  32485. // Replace functions
  32486. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  32487. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  32488. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  32489. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  32490. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  32491. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  32492. get: function () { return this._data[0]; },
  32493. set: function (value) {
  32494. if (!this._data) {
  32495. this._data = new Float32Array(3);
  32496. }
  32497. this._data[0] = value;
  32498. }
  32499. });
  32500. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  32501. get: function () { return this._data[1]; },
  32502. set: function (value) {
  32503. this._data[1] = value;
  32504. }
  32505. });
  32506. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  32507. get: function () { return this._data[2]; },
  32508. set: function (value) {
  32509. this._data[2] = value;
  32510. }
  32511. });
  32512. SIMDHelper._isEnabled = true;
  32513. };
  32514. SIMDHelper._isEnabled = false;
  32515. return SIMDHelper;
  32516. })();
  32517. BABYLON.SIMDHelper = SIMDHelper;
  32518. })(BABYLON || (BABYLON = {}));
  32519. var BABYLON;
  32520. (function (BABYLON) {
  32521. var ShaderMaterial = (function (_super) {
  32522. __extends(ShaderMaterial, _super);
  32523. function ShaderMaterial(name, scene, shaderPath, options) {
  32524. _super.call(this, name, scene);
  32525. this._textures = {};
  32526. this._floats = {};
  32527. this._floatsArrays = {};
  32528. this._colors3 = {};
  32529. this._colors4 = {};
  32530. this._vectors2 = {};
  32531. this._vectors3 = {};
  32532. this._vectors4 = {};
  32533. this._matrices = {};
  32534. this._matrices3x3 = {};
  32535. this._matrices2x2 = {};
  32536. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  32537. this._shaderPath = shaderPath;
  32538. options.needAlphaBlending = options.needAlphaBlending || false;
  32539. options.needAlphaTesting = options.needAlphaTesting || false;
  32540. options.attributes = options.attributes || ["position", "normal", "uv"];
  32541. options.uniforms = options.uniforms || ["worldViewProjection"];
  32542. options.samplers = options.samplers || [];
  32543. options.defines = options.defines || [];
  32544. this._options = options;
  32545. }
  32546. ShaderMaterial.prototype.needAlphaBlending = function () {
  32547. return this._options.needAlphaBlending;
  32548. };
  32549. ShaderMaterial.prototype.needAlphaTesting = function () {
  32550. return this._options.needAlphaTesting;
  32551. };
  32552. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  32553. if (this._options.uniforms.indexOf(uniformName) === -1) {
  32554. this._options.uniforms.push(uniformName);
  32555. }
  32556. };
  32557. ShaderMaterial.prototype.setTexture = function (name, texture) {
  32558. if (this._options.samplers.indexOf(name) === -1) {
  32559. this._options.samplers.push(name);
  32560. }
  32561. this._textures[name] = texture;
  32562. return this;
  32563. };
  32564. ShaderMaterial.prototype.setFloat = function (name, value) {
  32565. this._checkUniform(name);
  32566. this._floats[name] = value;
  32567. return this;
  32568. };
  32569. ShaderMaterial.prototype.setFloats = function (name, value) {
  32570. this._checkUniform(name);
  32571. this._floatsArrays[name] = value;
  32572. return this;
  32573. };
  32574. ShaderMaterial.prototype.setColor3 = function (name, value) {
  32575. this._checkUniform(name);
  32576. this._colors3[name] = value;
  32577. return this;
  32578. };
  32579. ShaderMaterial.prototype.setColor4 = function (name, value) {
  32580. this._checkUniform(name);
  32581. this._colors4[name] = value;
  32582. return this;
  32583. };
  32584. ShaderMaterial.prototype.setVector2 = function (name, value) {
  32585. this._checkUniform(name);
  32586. this._vectors2[name] = value;
  32587. return this;
  32588. };
  32589. ShaderMaterial.prototype.setVector3 = function (name, value) {
  32590. this._checkUniform(name);
  32591. this._vectors3[name] = value;
  32592. return this;
  32593. };
  32594. ShaderMaterial.prototype.setVector4 = function (name, value) {
  32595. this._checkUniform(name);
  32596. this._vectors4[name] = value;
  32597. return this;
  32598. };
  32599. ShaderMaterial.prototype.setMatrix = function (name, value) {
  32600. this._checkUniform(name);
  32601. this._matrices[name] = value;
  32602. return this;
  32603. };
  32604. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  32605. this._checkUniform(name);
  32606. this._matrices3x3[name] = value;
  32607. return this;
  32608. };
  32609. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  32610. this._checkUniform(name);
  32611. this._matrices2x2[name] = value;
  32612. return this;
  32613. };
  32614. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  32615. var scene = this.getScene();
  32616. var engine = scene.getEngine();
  32617. if (!this.checkReadyOnEveryCall) {
  32618. if (this._renderId === scene.getRenderId()) {
  32619. return true;
  32620. }
  32621. }
  32622. // Instances
  32623. var defines = [];
  32624. var fallbacks = new BABYLON.EffectFallbacks();
  32625. if (useInstances) {
  32626. defines.push("#define INSTANCES");
  32627. }
  32628. for (var index = 0; index < this._options.defines.length; index++) {
  32629. defines.push(this._options.defines[index]);
  32630. }
  32631. // Bones
  32632. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  32633. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32634. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32635. fallbacks.addCPUSkinningFallback(0, mesh);
  32636. }
  32637. // Alpha test
  32638. if (engine.getAlphaTesting()) {
  32639. defines.push("#define ALPHATEST");
  32640. }
  32641. var previousEffect = this._effect;
  32642. var join = defines.join("\n");
  32643. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  32644. if (!this._effect.isReady()) {
  32645. return false;
  32646. }
  32647. if (previousEffect !== this._effect) {
  32648. scene.resetCachedMaterial();
  32649. }
  32650. this._renderId = scene.getRenderId();
  32651. return true;
  32652. };
  32653. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32654. var scene = this.getScene();
  32655. if (this._options.uniforms.indexOf("world") !== -1) {
  32656. this._effect.setMatrix("world", world);
  32657. }
  32658. if (this._options.uniforms.indexOf("worldView") !== -1) {
  32659. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  32660. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  32661. }
  32662. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  32663. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  32664. }
  32665. };
  32666. ShaderMaterial.prototype.bind = function (world, mesh) {
  32667. // Std values
  32668. this.bindOnlyWorldMatrix(world);
  32669. if (this.getScene().getCachedMaterial() !== this) {
  32670. if (this._options.uniforms.indexOf("view") !== -1) {
  32671. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  32672. }
  32673. if (this._options.uniforms.indexOf("projection") !== -1) {
  32674. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  32675. }
  32676. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  32677. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32678. }
  32679. // Bones
  32680. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  32681. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32682. }
  32683. // Texture
  32684. for (var name in this._textures) {
  32685. this._effect.setTexture(name, this._textures[name]);
  32686. }
  32687. // Float
  32688. for (name in this._floats) {
  32689. this._effect.setFloat(name, this._floats[name]);
  32690. }
  32691. // Float s
  32692. for (name in this._floatsArrays) {
  32693. this._effect.setArray(name, this._floatsArrays[name]);
  32694. }
  32695. // Color3
  32696. for (name in this._colors3) {
  32697. this._effect.setColor3(name, this._colors3[name]);
  32698. }
  32699. // Color4
  32700. for (name in this._colors4) {
  32701. var color = this._colors4[name];
  32702. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  32703. }
  32704. // Vector2
  32705. for (name in this._vectors2) {
  32706. this._effect.setVector2(name, this._vectors2[name]);
  32707. }
  32708. // Vector3
  32709. for (name in this._vectors3) {
  32710. this._effect.setVector3(name, this._vectors3[name]);
  32711. }
  32712. // Vector4
  32713. for (name in this._vectors4) {
  32714. this._effect.setVector4(name, this._vectors4[name]);
  32715. }
  32716. // Matrix
  32717. for (name in this._matrices) {
  32718. this._effect.setMatrix(name, this._matrices[name]);
  32719. }
  32720. // Matrix 3x3
  32721. for (name in this._matrices3x3) {
  32722. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  32723. }
  32724. // Matrix 2x2
  32725. for (name in this._matrices2x2) {
  32726. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  32727. }
  32728. }
  32729. _super.prototype.bind.call(this, world, mesh);
  32730. };
  32731. ShaderMaterial.prototype.clone = function (name) {
  32732. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  32733. return newShaderMaterial;
  32734. };
  32735. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  32736. for (var name in this._textures) {
  32737. this._textures[name].dispose();
  32738. }
  32739. this._textures = {};
  32740. _super.prototype.dispose.call(this, forceDisposeEffect);
  32741. };
  32742. ShaderMaterial.prototype.serialize = function () {
  32743. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32744. serializationObject.customType = "BABYLON.ShaderMaterial";
  32745. serializationObject.options = this._options;
  32746. serializationObject.shaderPath = this._shaderPath;
  32747. // Texture
  32748. serializationObject.textures = {};
  32749. for (var name in this._textures) {
  32750. serializationObject.textures[name] = this._textures[name].serialize();
  32751. }
  32752. // Float
  32753. serializationObject.floats = {};
  32754. for (name in this._floats) {
  32755. serializationObject.floats[name] = this._floats[name];
  32756. }
  32757. // Float s
  32758. serializationObject.floatArrays = {};
  32759. for (name in this._floatsArrays) {
  32760. serializationObject.floatArrays[name] = this._floatsArrays[name];
  32761. }
  32762. // Color3
  32763. serializationObject.colors3 = {};
  32764. for (name in this._colors3) {
  32765. serializationObject.colors3[name] = this._colors3[name].asArray();
  32766. }
  32767. // Color4
  32768. serializationObject.colors4 = {};
  32769. for (name in this._colors4) {
  32770. serializationObject.colors4[name] = this._colors4[name].asArray();
  32771. }
  32772. // Vector2
  32773. serializationObject.vectors2 = {};
  32774. for (name in this._vectors2) {
  32775. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  32776. }
  32777. // Vector3
  32778. serializationObject.vectors3 = {};
  32779. for (name in this._vectors3) {
  32780. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  32781. }
  32782. // Vector4
  32783. serializationObject.vectors4 = {};
  32784. for (name in this._vectors4) {
  32785. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  32786. }
  32787. // Matrix
  32788. serializationObject.matrices = {};
  32789. for (name in this._matrices) {
  32790. serializationObject.matrices[name] = this._matrices[name].asArray();
  32791. }
  32792. // Matrix 3x3
  32793. serializationObject.matrices3x3 = {};
  32794. for (name in this._matrices3x3) {
  32795. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  32796. }
  32797. // Matrix 2x2
  32798. serializationObject.matrices2x2 = {};
  32799. for (name in this._matrices2x2) {
  32800. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  32801. }
  32802. return serializationObject;
  32803. };
  32804. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  32805. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  32806. // Texture
  32807. for (var name in source.textures) {
  32808. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  32809. }
  32810. // Float
  32811. for (name in source.floats) {
  32812. material.setFloat(name, source.floats[name]);
  32813. }
  32814. // Float s
  32815. for (name in source.floatsArrays) {
  32816. material.setFloats(name, source.floatsArrays[name]);
  32817. }
  32818. // Color3
  32819. for (name in source.colors3) {
  32820. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  32821. }
  32822. // Color4
  32823. for (name in source.colors4) {
  32824. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  32825. }
  32826. // Vector2
  32827. for (name in source.vectors2) {
  32828. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  32829. }
  32830. // Vector3
  32831. for (name in source.vectors3) {
  32832. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  32833. }
  32834. // Vector4
  32835. for (name in source.vectors4) {
  32836. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  32837. }
  32838. // Matrix
  32839. for (name in source.matrices) {
  32840. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  32841. }
  32842. // Matrix 3x3
  32843. for (name in source.matrices3x3) {
  32844. material.setMatrix3x3(name, source.matrices3x3[name]);
  32845. }
  32846. // Matrix 2x2
  32847. for (name in source.matrices2x2) {
  32848. material.setMatrix2x2(name, source.matrices2x2[name]);
  32849. }
  32850. return material;
  32851. };
  32852. return ShaderMaterial;
  32853. })(BABYLON.Material);
  32854. BABYLON.ShaderMaterial = ShaderMaterial;
  32855. })(BABYLON || (BABYLON = {}));
  32856. var BABYLON;
  32857. (function (BABYLON) {
  32858. var Internals;
  32859. (function (Internals) {
  32860. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32861. // All values and structures referenced from:
  32862. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32863. var DDS_MAGIC = 0x20534444;
  32864. 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;
  32865. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32866. 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;
  32867. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32868. function FourCCToInt32(value) {
  32869. return value.charCodeAt(0) +
  32870. (value.charCodeAt(1) << 8) +
  32871. (value.charCodeAt(2) << 16) +
  32872. (value.charCodeAt(3) << 24);
  32873. }
  32874. function Int32ToFourCC(value) {
  32875. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32876. }
  32877. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32878. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32879. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32880. var headerLengthInt = 31; // The header length in 32 bit ints
  32881. // Offsets into the header array
  32882. var off_magic = 0;
  32883. var off_size = 1;
  32884. var off_flags = 2;
  32885. var off_height = 3;
  32886. var off_width = 4;
  32887. var off_mipmapCount = 7;
  32888. var off_pfFlags = 20;
  32889. var off_pfFourCC = 21;
  32890. var off_RGBbpp = 22;
  32891. var off_RMask = 23;
  32892. var off_GMask = 24;
  32893. var off_BMask = 25;
  32894. var off_AMask = 26;
  32895. var off_caps1 = 27;
  32896. var off_caps2 = 28;
  32897. ;
  32898. var DDSTools = (function () {
  32899. function DDSTools() {
  32900. }
  32901. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32902. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32903. var mipmapCount = 1;
  32904. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32905. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32906. }
  32907. return {
  32908. width: header[off_width],
  32909. height: header[off_height],
  32910. mipmapCount: mipmapCount,
  32911. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32912. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32913. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32914. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  32915. };
  32916. };
  32917. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32918. var byteArray = new Uint8Array(dataLength);
  32919. var srcData = new Uint8Array(arrayBuffer);
  32920. var index = 0;
  32921. for (var y = height - 1; y >= 0; y--) {
  32922. for (var x = 0; x < width; x++) {
  32923. var srcPos = dataOffset + (x + y * width) * 4;
  32924. byteArray[index + 2] = srcData[srcPos];
  32925. byteArray[index + 1] = srcData[srcPos + 1];
  32926. byteArray[index] = srcData[srcPos + 2];
  32927. byteArray[index + 3] = srcData[srcPos + 3];
  32928. index += 4;
  32929. }
  32930. }
  32931. return byteArray;
  32932. };
  32933. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32934. var byteArray = new Uint8Array(dataLength);
  32935. var srcData = new Uint8Array(arrayBuffer);
  32936. var index = 0;
  32937. for (var y = height - 1; y >= 0; y--) {
  32938. for (var x = 0; x < width; x++) {
  32939. var srcPos = dataOffset + (x + y * width) * 3;
  32940. byteArray[index + 2] = srcData[srcPos];
  32941. byteArray[index + 1] = srcData[srcPos + 1];
  32942. byteArray[index] = srcData[srcPos + 2];
  32943. index += 3;
  32944. }
  32945. }
  32946. return byteArray;
  32947. };
  32948. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32949. var byteArray = new Uint8Array(dataLength);
  32950. var srcData = new Uint8Array(arrayBuffer);
  32951. var index = 0;
  32952. for (var y = height - 1; y >= 0; y--) {
  32953. for (var x = 0; x < width; x++) {
  32954. var srcPos = dataOffset + (x + y * width);
  32955. byteArray[index] = srcData[srcPos];
  32956. index++;
  32957. }
  32958. }
  32959. return byteArray;
  32960. };
  32961. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  32962. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  32963. if (header[off_magic] != DDS_MAGIC) {
  32964. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32965. return;
  32966. }
  32967. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32968. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32969. return;
  32970. }
  32971. if (info.isFourCC) {
  32972. fourCC = header[off_pfFourCC];
  32973. switch (fourCC) {
  32974. case FOURCC_DXT1:
  32975. blockBytes = 8;
  32976. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32977. break;
  32978. case FOURCC_DXT3:
  32979. blockBytes = 16;
  32980. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32981. break;
  32982. case FOURCC_DXT5:
  32983. blockBytes = 16;
  32984. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32985. break;
  32986. default:
  32987. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  32988. return;
  32989. }
  32990. }
  32991. mipmapCount = 1;
  32992. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  32993. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32994. }
  32995. var bpp = header[off_RGBbpp];
  32996. for (var face = 0; face < faces; face++) {
  32997. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32998. width = header[off_width];
  32999. height = header[off_height];
  33000. dataOffset = header[off_size] + 4;
  33001. for (i = 0; i < mipmapCount; ++i) {
  33002. if (info.isRGB) {
  33003. if (bpp === 24) {
  33004. dataLength = width * height * 3;
  33005. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33006. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33007. }
  33008. else {
  33009. dataLength = width * height * 4;
  33010. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33011. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33012. }
  33013. }
  33014. else if (info.isLuminance) {
  33015. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33016. var unpaddedRowSize = width;
  33017. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33018. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33019. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33020. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33021. }
  33022. else {
  33023. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33024. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33025. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  33026. }
  33027. dataOffset += dataLength;
  33028. width *= 0.5;
  33029. height *= 0.5;
  33030. width = Math.max(1.0, width);
  33031. height = Math.max(1.0, height);
  33032. }
  33033. }
  33034. };
  33035. return DDSTools;
  33036. })();
  33037. Internals.DDSTools = DDSTools;
  33038. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33039. })(BABYLON || (BABYLON = {}));
  33040. var BABYLON;
  33041. (function (BABYLON) {
  33042. var CannonJSPlugin = (function () {
  33043. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  33044. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  33045. if (iterations === void 0) { iterations = 10; }
  33046. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  33047. this.name = "CannonJSPlugin";
  33048. this._physicsMaterials = [];
  33049. this._fixedTimeStep = 1 / 60;
  33050. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  33051. this._currentCollisionGroup = 2;
  33052. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  33053. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  33054. this._tmpPosition = BABYLON.Vector3.Zero();
  33055. this._tmpQuaternion = new BABYLON.Quaternion();
  33056. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  33057. this._tmpDeltaRotation = new BABYLON.Quaternion();
  33058. this._tmpUnityRotation = new BABYLON.Quaternion();
  33059. if (!this.isSupported()) {
  33060. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  33061. return;
  33062. }
  33063. this.world = new CANNON.World();
  33064. this.world.broadphase = new CANNON.NaiveBroadphase();
  33065. this.world.solver.iterations = iterations;
  33066. }
  33067. CannonJSPlugin.prototype.setGravity = function (gravity) {
  33068. this.world.gravity.copy(gravity);
  33069. };
  33070. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  33071. this._fixedTimeStep = timeStep;
  33072. };
  33073. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  33074. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  33075. };
  33076. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  33077. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  33078. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  33079. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  33080. };
  33081. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  33082. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  33083. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  33084. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  33085. };
  33086. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  33087. //parent-child relationship. Does this impostor has a parent impostor?
  33088. if (impostor.parent) {
  33089. if (impostor.physicsBody) {
  33090. this.removePhysicsBody(impostor);
  33091. //TODO is that needed?
  33092. impostor.forceUpdate();
  33093. }
  33094. return;
  33095. }
  33096. //should a new body be created for this impostor?
  33097. if (impostor.isBodyInitRequired()) {
  33098. if (!impostor.mesh.rotationQuaternion) {
  33099. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  33100. }
  33101. var shape = this._createShape(impostor);
  33102. //unregister events, if body is being changed
  33103. var oldBody = impostor.physicsBody;
  33104. if (oldBody) {
  33105. this.removePhysicsBody(impostor);
  33106. }
  33107. //create the body and material
  33108. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  33109. var bodyCreationObject = {
  33110. mass: impostor.getParam("mass"),
  33111. material: material
  33112. };
  33113. // A simple extend, in case native options were used.
  33114. var nativeOptions = impostor.getParam("nativeOptions");
  33115. for (var key in nativeOptions) {
  33116. if (nativeOptions.hasOwnProperty(key)) {
  33117. bodyCreationObject[key] = nativeOptions[key];
  33118. }
  33119. }
  33120. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  33121. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  33122. this.world.addEventListener("preStep", impostor.beforeStep);
  33123. this.world.addEventListener("postStep", impostor.afterStep);
  33124. impostor.physicsBody.addShape(shape);
  33125. this.world.add(impostor.physicsBody);
  33126. //try to keep the body moving in the right direction by taking old properties.
  33127. //Should be tested!
  33128. if (oldBody) {
  33129. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  33130. impostor.physicsBody[param].copy(oldBody[param]);
  33131. });
  33132. }
  33133. this._processChildMeshes(impostor);
  33134. }
  33135. //now update the body's transformation
  33136. this._updatePhysicsBodyTransformation(impostor);
  33137. };
  33138. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  33139. var _this = this;
  33140. var meshChildren = mainImpostor.mesh.getChildMeshes();
  33141. if (meshChildren.length) {
  33142. var processMesh = function (localPosition, mesh) {
  33143. var childImpostor = mesh.getPhysicsImpostor();
  33144. if (childImpostor) {
  33145. var parent = childImpostor.parent;
  33146. if (parent !== mainImpostor) {
  33147. var localPosition = mesh.position;
  33148. if (childImpostor.physicsBody) {
  33149. _this.removePhysicsBody(childImpostor);
  33150. childImpostor.physicsBody = null;
  33151. }
  33152. childImpostor.parent = mainImpostor;
  33153. childImpostor.resetUpdateFlags();
  33154. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  33155. //Add the mass of the children.
  33156. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  33157. }
  33158. }
  33159. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  33160. };
  33161. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  33162. }
  33163. };
  33164. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  33165. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  33166. this.world.removeEventListener("preStep", impostor.beforeStep);
  33167. this.world.removeEventListener("postStep", impostor.afterStep);
  33168. this.world.remove(impostor.physicsBody);
  33169. };
  33170. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  33171. var mainBody = impostorJoint.mainImpostor.physicsBody;
  33172. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  33173. if (!mainBody || !connectedBody) {
  33174. return;
  33175. }
  33176. var constraint;
  33177. var jointData = impostorJoint.joint.jointData;
  33178. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  33179. var constraintData = {
  33180. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  33181. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  33182. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  33183. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  33184. maxForce: jointData.nativeParams.maxForce,
  33185. collideConnected: !!jointData.collision
  33186. };
  33187. //Not needed, Cannon has a collideConnected flag
  33188. /*if (!jointData.collision) {
  33189. //add 1st body to a collision group of its own, if it is not in 1
  33190. if (mainBody.collisionFilterGroup === 1) {
  33191. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  33192. this._currentCollisionGroup <<= 1;
  33193. }
  33194. if (connectedBody.collisionFilterGroup === 1) {
  33195. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  33196. this._currentCollisionGroup <<= 1;
  33197. }
  33198. //add their mask to the collisionFilterMask of each other:
  33199. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  33200. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  33201. }*/
  33202. switch (impostorJoint.joint.type) {
  33203. case BABYLON.PhysicsJoint.HingeJoint:
  33204. case BABYLON.PhysicsJoint.Hinge2Joint:
  33205. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  33206. break;
  33207. case BABYLON.PhysicsJoint.DistanceJoint:
  33208. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  33209. break;
  33210. case BABYLON.PhysicsJoint.SpringJoint:
  33211. var springData = jointData;
  33212. constraint = new CANNON.Spring(mainBody, connectedBody, {
  33213. restLength: springData.length,
  33214. stiffness: springData.stiffness,
  33215. damping: springData.damping,
  33216. localAnchorA: constraintData.pivotA,
  33217. localAnchorB: constraintData.pivotB
  33218. });
  33219. break;
  33220. default:
  33221. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  33222. break;
  33223. }
  33224. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  33225. constraint.collideConnected = !!jointData.collision;
  33226. impostorJoint.joint.physicsJoint = constraint;
  33227. //don't add spring as constraint, as it is not one.
  33228. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  33229. this.world.addConstraint(constraint);
  33230. }
  33231. else {
  33232. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  33233. constraint.applyForce();
  33234. });
  33235. }
  33236. };
  33237. CannonJSPlugin.prototype.removeJoint = function (joint) {
  33238. //TODO
  33239. };
  33240. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  33241. var index;
  33242. var mat;
  33243. for (index = 0; index < this._physicsMaterials.length; index++) {
  33244. mat = this._physicsMaterials[index];
  33245. if (mat.friction === friction && mat.restitution === restitution) {
  33246. return mat;
  33247. }
  33248. }
  33249. var currentMat = new CANNON.Material("mat");
  33250. currentMat.friction = friction;
  33251. currentMat.restitution = restitution;
  33252. this._physicsMaterials.push(currentMat);
  33253. return currentMat;
  33254. };
  33255. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  33256. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  33257. };
  33258. CannonJSPlugin.prototype._createShape = function (impostor) {
  33259. var mesh = impostor.mesh;
  33260. //get the correct bounding box
  33261. var oldQuaternion = mesh.rotationQuaternion;
  33262. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  33263. mesh.computeWorldMatrix(true);
  33264. var returnValue;
  33265. switch (impostor.type) {
  33266. case BABYLON.PhysicsEngine.SphereImpostor:
  33267. var bbox = mesh.getBoundingInfo().boundingBox;
  33268. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  33269. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  33270. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  33271. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  33272. break;
  33273. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  33274. case BABYLON.PhysicsEngine.CylinderImpostor:
  33275. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  33276. case BABYLON.PhysicsEngine.BoxImpostor:
  33277. bbox = mesh.getBoundingInfo().boundingBox;
  33278. var min = bbox.minimumWorld;
  33279. var max = bbox.maximumWorld;
  33280. var box = max.subtract(min).scale(0.5);
  33281. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  33282. break;
  33283. case BABYLON.PhysicsEngine.PlaneImpostor:
  33284. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  33285. returnValue = new CANNON.Plane();
  33286. break;
  33287. case BABYLON.PhysicsEngine.MeshImpostor:
  33288. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33289. var rawFaces = mesh.getIndices();
  33290. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  33291. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  33292. break;
  33293. case BABYLON.PhysicsEngine.HeightmapImpostor:
  33294. returnValue = this._createHeightmap(mesh);
  33295. break;
  33296. }
  33297. mesh.rotationQuaternion = oldQuaternion;
  33298. return returnValue;
  33299. };
  33300. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  33301. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33302. var matrix = [];
  33303. //For now pointDepth will not be used and will be automatically calculated.
  33304. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  33305. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  33306. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  33307. var elementSize = dim * 2 / arraySize;
  33308. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  33309. for (var i = 0; i < pos.length; i = i + 3) {
  33310. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  33311. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  33312. var y = pos[i + 1] + minY;
  33313. if (!matrix[x]) {
  33314. matrix[x] = [];
  33315. }
  33316. if (!matrix[x][z]) {
  33317. matrix[x][z] = y;
  33318. }
  33319. matrix[x][z] = Math.max(y, matrix[x][z]);
  33320. }
  33321. for (var x = 0; x <= arraySize; ++x) {
  33322. if (!matrix[x]) {
  33323. var loc = 1;
  33324. while (!matrix[(x + loc) % arraySize]) {
  33325. loc++;
  33326. }
  33327. matrix[x] = matrix[(x + loc) % arraySize].slice();
  33328. }
  33329. for (var z = 0; z <= arraySize; ++z) {
  33330. if (!matrix[x][z]) {
  33331. var loc = 1;
  33332. var newValue;
  33333. while (newValue === undefined) {
  33334. newValue = matrix[x][(z + loc++) % arraySize];
  33335. }
  33336. matrix[x][z] = newValue;
  33337. }
  33338. }
  33339. }
  33340. var shape = new CANNON.Heightfield(matrix, {
  33341. elementSize: elementSize
  33342. });
  33343. //For future reference, needed for body transformation
  33344. shape.minY = minY;
  33345. return shape;
  33346. };
  33347. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  33348. var mesh = impostor.mesh;
  33349. //make sure it is updated...
  33350. impostor.mesh.computeWorldMatrix(true);
  33351. // The delta between the mesh position and the mesh bounding box center
  33352. var bbox = mesh.getBoundingInfo().boundingBox;
  33353. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  33354. var quaternion = mesh.rotationQuaternion;
  33355. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  33356. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  33357. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  33358. //-90 DEG in X, precalculated
  33359. quaternion = quaternion.multiply(this._minus90X);
  33360. //Invert! (Precalculated, 90 deg in X)
  33361. //No need to clone. this will never change.
  33362. impostor.setDeltaRotation(this._plus90X);
  33363. }
  33364. //If it is a heightfield, if should be centered.
  33365. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  33366. //calculate the correct body position:
  33367. var rotationQuaternion = mesh.rotationQuaternion;
  33368. mesh.rotationQuaternion = this._tmpUnityRotation;
  33369. mesh.computeWorldMatrix(true);
  33370. //get original center with no rotation
  33371. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  33372. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  33373. //rotation is back
  33374. mesh.rotationQuaternion = rotationQuaternion;
  33375. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  33376. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  33377. mesh.setPivotMatrix(p);
  33378. mesh.computeWorldMatrix(true);
  33379. //calculate the translation
  33380. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  33381. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  33382. //add it inverted to the delta
  33383. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  33384. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  33385. mesh.setPivotMatrix(oldPivot);
  33386. mesh.computeWorldMatrix(true);
  33387. }
  33388. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  33389. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  33390. this._tmpPosition.copyFrom(mesh.position);
  33391. }
  33392. impostor.setDeltaPosition(this._tmpDeltaPosition);
  33393. //Now update the impostor object
  33394. impostor.physicsBody.position.copy(this._tmpPosition);
  33395. impostor.physicsBody.quaternion.copy(quaternion);
  33396. };
  33397. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  33398. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  33399. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  33400. };
  33401. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  33402. impostor.physicsBody.position.copy(newPosition);
  33403. impostor.physicsBody.quaternion.copy(newRotation);
  33404. };
  33405. CannonJSPlugin.prototype.isSupported = function () {
  33406. return window.CANNON !== undefined;
  33407. };
  33408. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  33409. impostor.physicsBody.velocity.copy(velocity);
  33410. };
  33411. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  33412. impostor.physicsBody.angularVelocity.copy(velocity);
  33413. };
  33414. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  33415. var v = impostor.physicsBody.velocity;
  33416. if (!v)
  33417. return null;
  33418. return new BABYLON.Vector3(v.x, v.y, v.z);
  33419. };
  33420. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  33421. var v = impostor.physicsBody.angularVelocity;
  33422. if (!v)
  33423. return null;
  33424. return new BABYLON.Vector3(v.x, v.y, v.z);
  33425. };
  33426. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  33427. impostor.physicsBody.mass = mass;
  33428. impostor.physicsBody.updateMassProperties();
  33429. };
  33430. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  33431. impostor.physicsBody.sleep();
  33432. };
  33433. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  33434. impostor.physicsBody.wakeUp();
  33435. };
  33436. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  33437. joint.physicsJoint.distance = maxDistance;
  33438. };
  33439. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  33440. if (!motorIndex) {
  33441. joint.physicsJoint.enableMotor();
  33442. }
  33443. };
  33444. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  33445. if (!motorIndex) {
  33446. joint.physicsJoint.disableMotor();
  33447. }
  33448. };
  33449. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  33450. if (!motorIndex) {
  33451. joint.physicsJoint.enableMotor();
  33452. joint.physicsJoint.setMotorSpeed(speed);
  33453. if (maxForce) {
  33454. this.setLimit(joint, maxForce);
  33455. }
  33456. }
  33457. };
  33458. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  33459. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  33460. joint.physicsJoint.motorEquation.minForce = lowerLimit || -upperLimit;
  33461. };
  33462. CannonJSPlugin.prototype.dispose = function () {
  33463. //nothing to do, actually.
  33464. };
  33465. return CannonJSPlugin;
  33466. })();
  33467. BABYLON.CannonJSPlugin = CannonJSPlugin;
  33468. })(BABYLON || (BABYLON = {}));
  33469. var BABYLON;
  33470. (function (BABYLON) {
  33471. var OimoJSPlugin = (function () {
  33472. function OimoJSPlugin(iterations) {
  33473. this.name = "OimoJSPlugin";
  33474. this._tmpImpostorsArray = [];
  33475. this._tmpPositionVector = BABYLON.Vector3.Zero();
  33476. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  33477. this.world.clear();
  33478. //making sure no stats are calculated
  33479. this.world.isNoStat = true;
  33480. }
  33481. OimoJSPlugin.prototype.setGravity = function (gravity) {
  33482. this.world.gravity.copy(gravity);
  33483. };
  33484. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  33485. this.world.timeStep = timeStep;
  33486. };
  33487. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  33488. var _this = this;
  33489. impostors.forEach(function (impostor) {
  33490. impostor.beforeStep();
  33491. });
  33492. this.world.step();
  33493. impostors.forEach(function (impostor) {
  33494. impostor.afterStep();
  33495. //update the ordered impostors array
  33496. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  33497. });
  33498. //check for collisions
  33499. var contact = this.world.contacts;
  33500. while (contact !== null) {
  33501. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  33502. contact = contact.next;
  33503. continue;
  33504. }
  33505. //is this body colliding with any other? get the impostor
  33506. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  33507. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  33508. if (!mainImpostor || !collidingImpostor) {
  33509. contact = contact.next;
  33510. continue;
  33511. }
  33512. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  33513. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  33514. contact = contact.next;
  33515. }
  33516. };
  33517. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  33518. var mass = impostor.physicsBody.massInfo.mass;
  33519. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  33520. };
  33521. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  33522. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  33523. this.applyImpulse(impostor, force, contactPoint);
  33524. };
  33525. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  33526. var _this = this;
  33527. //parent-child relationship. Does this impostor has a parent impostor?
  33528. if (impostor.parent) {
  33529. if (impostor.physicsBody) {
  33530. this.removePhysicsBody(impostor);
  33531. //TODO is that needed?
  33532. impostor.forceUpdate();
  33533. }
  33534. return;
  33535. }
  33536. impostor.mesh.computeWorldMatrix(true);
  33537. if (impostor.isBodyInitRequired()) {
  33538. if (!impostor.mesh.rotationQuaternion) {
  33539. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  33540. }
  33541. var bodyConfig = {
  33542. name: impostor.mesh.uniqueId,
  33543. //Oimo must have mass, also for static objects.
  33544. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  33545. size: [],
  33546. type: [],
  33547. pos: [],
  33548. rot: [],
  33549. move: impostor.getParam("mass") !== 0,
  33550. //Supporting older versions of Oimo
  33551. world: this.world
  33552. };
  33553. var impostors = [impostor];
  33554. function addToArray(parent) {
  33555. parent.getChildMeshes().forEach(function (m) {
  33556. if (m.physicsImpostor) {
  33557. impostors.push(m.physicsImpostor);
  33558. m.physicsImpostor._init();
  33559. }
  33560. });
  33561. }
  33562. addToArray(impostor.mesh);
  33563. function checkWithEpsilon(value) {
  33564. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  33565. }
  33566. impostors.forEach(function (i) {
  33567. //get the correct bounding box
  33568. var oldQuaternion = i.mesh.rotationQuaternion;
  33569. 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 });
  33570. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  33571. i.mesh.computeWorldMatrix(true);
  33572. var bbox = i.mesh.getBoundingInfo().boundingBox;
  33573. if (i === impostor) {
  33574. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  33575. //Can also use Array.prototype.push.apply
  33576. bodyConfig.pos.push(bbox.center.x);
  33577. bodyConfig.pos.push(bbox.center.y);
  33578. bodyConfig.pos.push(bbox.center.z);
  33579. //tmp solution
  33580. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  33581. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  33582. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  33583. }
  33584. else {
  33585. bodyConfig.pos.push(i.mesh.position.x);
  33586. bodyConfig.pos.push(i.mesh.position.y);
  33587. bodyConfig.pos.push(i.mesh.position.z);
  33588. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  33589. bodyConfig.rot.push(0);
  33590. bodyConfig.rot.push(0);
  33591. bodyConfig.rot.push(0);
  33592. }
  33593. // register mesh
  33594. switch (i.type) {
  33595. case BABYLON.PhysicsEngine.SphereImpostor:
  33596. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  33597. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  33598. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  33599. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  33600. bodyConfig.type.push('sphere');
  33601. //due to the way oimo works with compounds, add 3 times
  33602. bodyConfig.size.push(size);
  33603. bodyConfig.size.push(size);
  33604. bodyConfig.size.push(size);
  33605. break;
  33606. case BABYLON.PhysicsEngine.PlaneImpostor:
  33607. //TODO Oimo now supports cylinder!
  33608. case BABYLON.PhysicsEngine.CylinderImpostor:
  33609. case BABYLON.PhysicsEngine.BoxImpostor:
  33610. default:
  33611. var min = bbox.minimumWorld;
  33612. var max = bbox.maximumWorld;
  33613. var box = max.subtract(min);
  33614. var sizeX = checkWithEpsilon(box.x);
  33615. var sizeY = checkWithEpsilon(box.y);
  33616. var sizeZ = checkWithEpsilon(box.z);
  33617. bodyConfig.type.push('box');
  33618. bodyConfig.size.push(sizeX);
  33619. bodyConfig.size.push(sizeY);
  33620. bodyConfig.size.push(sizeZ);
  33621. break;
  33622. }
  33623. //actually not needed, but hey...
  33624. i.mesh.rotationQuaternion = oldQuaternion;
  33625. });
  33626. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  33627. }
  33628. else {
  33629. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  33630. }
  33631. impostor.setDeltaPosition(this._tmpPositionVector);
  33632. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  33633. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  33634. };
  33635. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  33636. //impostor.physicsBody.dispose();
  33637. //Same as : (older oimo versions)
  33638. this.world.removeRigidBody(impostor.physicsBody);
  33639. };
  33640. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  33641. var mainBody = impostorJoint.mainImpostor.physicsBody;
  33642. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  33643. if (!mainBody || !connectedBody) {
  33644. return;
  33645. }
  33646. var jointData = impostorJoint.joint.jointData;
  33647. var options = jointData.nativeParams || {};
  33648. var type;
  33649. var nativeJointData = {
  33650. body1: mainBody,
  33651. body2: connectedBody,
  33652. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  33653. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  33654. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  33655. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  33656. min: options.min,
  33657. max: options.max,
  33658. collision: options.collision || jointData.collision,
  33659. spring: options.spring,
  33660. //supporting older version of Oimo
  33661. world: this.world
  33662. };
  33663. switch (impostorJoint.joint.type) {
  33664. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  33665. type = "jointBall";
  33666. break;
  33667. case BABYLON.PhysicsJoint.SpringJoint:
  33668. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  33669. var springData = jointData;
  33670. nativeJointData.min = springData.length || nativeJointData.min;
  33671. //Max should also be set, just make sure it is at least min
  33672. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  33673. case BABYLON.PhysicsJoint.DistanceJoint:
  33674. type = "jointDistance";
  33675. nativeJointData.max = jointData.maxDistance;
  33676. break;
  33677. case BABYLON.PhysicsJoint.PrismaticJoint:
  33678. type = "jointPrisme";
  33679. break;
  33680. case BABYLON.PhysicsJoint.SliderJoint:
  33681. type = "jointSlide";
  33682. break;
  33683. case BABYLON.PhysicsJoint.WheelJoint:
  33684. type = "jointWheel";
  33685. break;
  33686. case BABYLON.PhysicsJoint.HingeJoint:
  33687. default:
  33688. type = "jointHinge";
  33689. break;
  33690. }
  33691. nativeJointData.type = type;
  33692. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  33693. };
  33694. OimoJSPlugin.prototype.removeJoint = function (joint) {
  33695. joint.joint.physicsJoint.dispose();
  33696. };
  33697. OimoJSPlugin.prototype.isSupported = function () {
  33698. return OIMO !== undefined;
  33699. };
  33700. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  33701. if (!impostor.physicsBody.sleeping) {
  33702. //TODO check that
  33703. if (impostor.physicsBody.shapes.next) {
  33704. var parentShape = this._getLastShape(impostor.physicsBody);
  33705. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  33706. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  33707. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  33708. }
  33709. else {
  33710. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  33711. }
  33712. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  33713. }
  33714. };
  33715. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  33716. var body = impostor.physicsBody;
  33717. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  33718. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  33719. body.syncShapes();
  33720. body.awake();
  33721. };
  33722. OimoJSPlugin.prototype._getLastShape = function (body) {
  33723. var lastShape = body.shapes;
  33724. while (lastShape.next) {
  33725. lastShape = lastShape.next;
  33726. }
  33727. return lastShape;
  33728. };
  33729. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  33730. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  33731. };
  33732. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  33733. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  33734. };
  33735. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  33736. var v = impostor.physicsBody.linearVelocity;
  33737. if (!v)
  33738. return null;
  33739. return new BABYLON.Vector3(v.x, v.y, v.z);
  33740. };
  33741. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  33742. var v = impostor.physicsBody.angularVelocity;
  33743. if (!v)
  33744. return null;
  33745. return new BABYLON.Vector3(v.x, v.y, v.z);
  33746. };
  33747. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  33748. var staticBody = mass === 0;
  33749. //this will actually set the body's density and not its mass.
  33750. //But this is how oimo treats the mass variable.
  33751. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  33752. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  33753. };
  33754. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  33755. impostor.physicsBody.sleep();
  33756. };
  33757. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  33758. impostor.physicsBody.awake();
  33759. };
  33760. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  33761. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  33762. if (minDistance !== void 0) {
  33763. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  33764. }
  33765. };
  33766. OimoJSPlugin.prototype.setMotor = function (joint, force, maxForce, motorIndex) {
  33767. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  33768. if (motor) {
  33769. motor.setMotor(force, maxForce);
  33770. }
  33771. };
  33772. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  33773. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  33774. if (motor) {
  33775. motor.setLimit(upperLimit, lowerLimit || -upperLimit);
  33776. }
  33777. };
  33778. OimoJSPlugin.prototype.dispose = function () {
  33779. this.world.clear();
  33780. };
  33781. return OimoJSPlugin;
  33782. })();
  33783. BABYLON.OimoJSPlugin = OimoJSPlugin;
  33784. })(BABYLON || (BABYLON = {}));
  33785. var BABYLON;
  33786. (function (BABYLON) {
  33787. var DisplayPassPostProcess = (function (_super) {
  33788. __extends(DisplayPassPostProcess, _super);
  33789. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33790. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  33791. }
  33792. return DisplayPassPostProcess;
  33793. })(BABYLON.PostProcess);
  33794. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  33795. })(BABYLON || (BABYLON = {}));
  33796. var BABYLON;
  33797. (function (BABYLON) {
  33798. var SimplificationSettings = (function () {
  33799. function SimplificationSettings(quality, distance, optimizeMesh) {
  33800. this.quality = quality;
  33801. this.distance = distance;
  33802. this.optimizeMesh = optimizeMesh;
  33803. }
  33804. return SimplificationSettings;
  33805. })();
  33806. BABYLON.SimplificationSettings = SimplificationSettings;
  33807. var SimplificationQueue = (function () {
  33808. function SimplificationQueue() {
  33809. this.running = false;
  33810. this._simplificationArray = [];
  33811. }
  33812. SimplificationQueue.prototype.addTask = function (task) {
  33813. this._simplificationArray.push(task);
  33814. };
  33815. SimplificationQueue.prototype.executeNext = function () {
  33816. var task = this._simplificationArray.pop();
  33817. if (task) {
  33818. this.running = true;
  33819. this.runSimplification(task);
  33820. }
  33821. else {
  33822. this.running = false;
  33823. }
  33824. };
  33825. SimplificationQueue.prototype.runSimplification = function (task) {
  33826. var _this = this;
  33827. if (task.parallelProcessing) {
  33828. //parallel simplifier
  33829. task.settings.forEach(function (setting) {
  33830. var simplifier = _this.getSimplifier(task);
  33831. simplifier.simplify(setting, function (newMesh) {
  33832. task.mesh.addLODLevel(setting.distance, newMesh);
  33833. newMesh.isVisible = true;
  33834. //check if it is the last
  33835. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  33836. //all done, run the success callback.
  33837. task.successCallback();
  33838. }
  33839. _this.executeNext();
  33840. });
  33841. });
  33842. }
  33843. else {
  33844. //single simplifier.
  33845. var simplifier = this.getSimplifier(task);
  33846. var runDecimation = function (setting, callback) {
  33847. simplifier.simplify(setting, function (newMesh) {
  33848. task.mesh.addLODLevel(setting.distance, newMesh);
  33849. newMesh.isVisible = true;
  33850. //run the next quality level
  33851. callback();
  33852. });
  33853. };
  33854. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  33855. runDecimation(task.settings[loop.index], function () {
  33856. loop.executeNext();
  33857. });
  33858. }, function () {
  33859. //execution ended, run the success callback.
  33860. if (task.successCallback) {
  33861. task.successCallback();
  33862. }
  33863. _this.executeNext();
  33864. });
  33865. }
  33866. };
  33867. SimplificationQueue.prototype.getSimplifier = function (task) {
  33868. switch (task.simplificationType) {
  33869. case SimplificationType.QUADRATIC:
  33870. default:
  33871. return new QuadraticErrorSimplification(task.mesh);
  33872. }
  33873. };
  33874. return SimplificationQueue;
  33875. })();
  33876. BABYLON.SimplificationQueue = SimplificationQueue;
  33877. /**
  33878. * The implemented types of simplification.
  33879. * At the moment only Quadratic Error Decimation is implemented.
  33880. */
  33881. (function (SimplificationType) {
  33882. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  33883. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  33884. var SimplificationType = BABYLON.SimplificationType;
  33885. var DecimationTriangle = (function () {
  33886. function DecimationTriangle(vertices) {
  33887. this.vertices = vertices;
  33888. this.error = new Array(4);
  33889. this.deleted = false;
  33890. this.isDirty = false;
  33891. this.deletePending = false;
  33892. this.borderFactor = 0;
  33893. }
  33894. return DecimationTriangle;
  33895. })();
  33896. BABYLON.DecimationTriangle = DecimationTriangle;
  33897. var DecimationVertex = (function () {
  33898. function DecimationVertex(position, id) {
  33899. this.position = position;
  33900. this.id = id;
  33901. this.isBorder = true;
  33902. this.q = new QuadraticMatrix();
  33903. this.triangleCount = 0;
  33904. this.triangleStart = 0;
  33905. this.originalOffsets = [];
  33906. }
  33907. DecimationVertex.prototype.updatePosition = function (newPosition) {
  33908. this.position.copyFrom(newPosition);
  33909. };
  33910. return DecimationVertex;
  33911. })();
  33912. BABYLON.DecimationVertex = DecimationVertex;
  33913. var QuadraticMatrix = (function () {
  33914. function QuadraticMatrix(data) {
  33915. this.data = new Array(10);
  33916. for (var i = 0; i < 10; ++i) {
  33917. if (data && data[i]) {
  33918. this.data[i] = data[i];
  33919. }
  33920. else {
  33921. this.data[i] = 0;
  33922. }
  33923. }
  33924. }
  33925. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  33926. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  33927. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  33928. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  33929. return det;
  33930. };
  33931. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  33932. for (var i = 0; i < 10; ++i) {
  33933. this.data[i] += matrix.data[i];
  33934. }
  33935. };
  33936. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  33937. for (var i = 0; i < 10; ++i) {
  33938. this.data[i] += data[i];
  33939. }
  33940. };
  33941. QuadraticMatrix.prototype.add = function (matrix) {
  33942. var m = new QuadraticMatrix();
  33943. for (var i = 0; i < 10; ++i) {
  33944. m.data[i] = this.data[i] + matrix.data[i];
  33945. }
  33946. return m;
  33947. };
  33948. QuadraticMatrix.FromData = function (a, b, c, d) {
  33949. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  33950. };
  33951. //returning an array to avoid garbage collection
  33952. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  33953. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  33954. };
  33955. return QuadraticMatrix;
  33956. })();
  33957. BABYLON.QuadraticMatrix = QuadraticMatrix;
  33958. var Reference = (function () {
  33959. function Reference(vertexId, triangleId) {
  33960. this.vertexId = vertexId;
  33961. this.triangleId = triangleId;
  33962. }
  33963. return Reference;
  33964. })();
  33965. BABYLON.Reference = Reference;
  33966. /**
  33967. * An implementation of the Quadratic Error simplification algorithm.
  33968. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  33969. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  33970. * @author RaananW
  33971. */
  33972. var QuadraticErrorSimplification = (function () {
  33973. function QuadraticErrorSimplification(_mesh) {
  33974. this._mesh = _mesh;
  33975. this.initialized = false;
  33976. this.syncIterations = 5000;
  33977. this.aggressiveness = 7;
  33978. this.decimationIterations = 100;
  33979. this.boundingBoxEpsilon = BABYLON.Epsilon;
  33980. }
  33981. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  33982. var _this = this;
  33983. this.initDecimatedMesh();
  33984. //iterating through the submeshes array, one after the other.
  33985. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  33986. _this.initWithMesh(loop.index, function () {
  33987. _this.runDecimation(settings, loop.index, function () {
  33988. loop.executeNext();
  33989. });
  33990. }, settings.optimizeMesh);
  33991. }, function () {
  33992. setTimeout(function () {
  33993. successCallback(_this._reconstructedMesh);
  33994. }, 0);
  33995. });
  33996. };
  33997. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  33998. var _this = this;
  33999. var gCount = 0;
  34000. triangle.vertices.forEach(function (vertex) {
  34001. var count = 0;
  34002. var vPos = vertex.position;
  34003. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  34004. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  34005. ++count;
  34006. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  34007. ++count;
  34008. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  34009. ++count;
  34010. if (count > 1) {
  34011. ++gCount;
  34012. }
  34013. ;
  34014. });
  34015. if (gCount > 1) {
  34016. console.log(triangle, gCount);
  34017. }
  34018. return gCount > 1;
  34019. };
  34020. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  34021. var _this = this;
  34022. var targetCount = ~~(this.triangles.length * settings.quality);
  34023. var deletedTriangles = 0;
  34024. var triangleCount = this.triangles.length;
  34025. var iterationFunction = function (iteration, callback) {
  34026. setTimeout(function () {
  34027. if (iteration % 5 === 0) {
  34028. _this.updateMesh(iteration === 0);
  34029. }
  34030. for (var i = 0; i < _this.triangles.length; ++i) {
  34031. _this.triangles[i].isDirty = false;
  34032. }
  34033. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  34034. var trianglesIterator = function (i) {
  34035. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  34036. var t = _this.triangles[tIdx];
  34037. if (!t)
  34038. return;
  34039. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  34040. return;
  34041. }
  34042. for (var j = 0; j < 3; ++j) {
  34043. if (t.error[j] < threshold) {
  34044. var deleted0 = [];
  34045. var deleted1 = [];
  34046. var v0 = t.vertices[j];
  34047. var v1 = t.vertices[(j + 1) % 3];
  34048. if (v0.isBorder !== v1.isBorder)
  34049. continue;
  34050. var p = BABYLON.Vector3.Zero();
  34051. var n = BABYLON.Vector3.Zero();
  34052. var uv = BABYLON.Vector2.Zero();
  34053. var color = new BABYLON.Color4(0, 0, 0, 1);
  34054. _this.calculateError(v0, v1, p, n, uv, color);
  34055. var delTr = [];
  34056. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  34057. continue;
  34058. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  34059. continue;
  34060. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  34061. continue;
  34062. var uniqueArray = [];
  34063. delTr.forEach(function (deletedT) {
  34064. if (uniqueArray.indexOf(deletedT) === -1) {
  34065. deletedT.deletePending = true;
  34066. uniqueArray.push(deletedT);
  34067. }
  34068. });
  34069. if (uniqueArray.length % 2 !== 0) {
  34070. continue;
  34071. }
  34072. v0.q = v1.q.add(v0.q);
  34073. v0.updatePosition(p);
  34074. var tStart = _this.references.length;
  34075. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  34076. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  34077. var tCount = _this.references.length - tStart;
  34078. if (tCount <= v0.triangleCount) {
  34079. if (tCount) {
  34080. for (var c = 0; c < tCount; c++) {
  34081. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  34082. }
  34083. }
  34084. }
  34085. else {
  34086. v0.triangleStart = tStart;
  34087. }
  34088. v0.triangleCount = tCount;
  34089. break;
  34090. }
  34091. }
  34092. };
  34093. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  34094. }, 0);
  34095. };
  34096. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  34097. if (triangleCount - deletedTriangles <= targetCount)
  34098. loop.breakLoop();
  34099. else {
  34100. iterationFunction(loop.index, function () {
  34101. loop.executeNext();
  34102. });
  34103. }
  34104. }, function () {
  34105. setTimeout(function () {
  34106. //reconstruct this part of the mesh
  34107. _this.reconstructMesh(submeshIndex);
  34108. successCallback();
  34109. }, 0);
  34110. });
  34111. };
  34112. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  34113. var _this = this;
  34114. this.vertices = [];
  34115. this.triangles = [];
  34116. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34117. var indices = this._mesh.getIndices();
  34118. var submesh = this._mesh.subMeshes[submeshIndex];
  34119. var findInVertices = function (positionToSearch) {
  34120. if (optimizeMesh) {
  34121. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  34122. if (_this.vertices[ii].position.equals(positionToSearch)) {
  34123. return _this.vertices[ii];
  34124. }
  34125. }
  34126. }
  34127. return null;
  34128. };
  34129. var vertexReferences = [];
  34130. var vertexInit = function (i) {
  34131. var offset = i + submesh.verticesStart;
  34132. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  34133. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  34134. vertex.originalOffsets.push(offset);
  34135. if (vertex.id === _this.vertices.length) {
  34136. _this.vertices.push(vertex);
  34137. }
  34138. vertexReferences.push(vertex.id);
  34139. };
  34140. //var totalVertices = mesh.getTotalVertices();
  34141. var totalVertices = submesh.verticesCount;
  34142. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  34143. var indicesInit = function (i) {
  34144. var offset = (submesh.indexStart / 3) + i;
  34145. var pos = (offset * 3);
  34146. var i0 = indices[pos + 0];
  34147. var i1 = indices[pos + 1];
  34148. var i2 = indices[pos + 2];
  34149. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  34150. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  34151. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  34152. var triangle = new DecimationTriangle([v0, v1, v2]);
  34153. triangle.originalOffset = pos;
  34154. _this.triangles.push(triangle);
  34155. };
  34156. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  34157. _this.init(callback);
  34158. });
  34159. });
  34160. };
  34161. QuadraticErrorSimplification.prototype.init = function (callback) {
  34162. var _this = this;
  34163. var triangleInit1 = function (i) {
  34164. var t = _this.triangles[i];
  34165. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  34166. for (var j = 0; j < 3; j++) {
  34167. 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))));
  34168. }
  34169. };
  34170. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  34171. var triangleInit2 = function (i) {
  34172. var t = _this.triangles[i];
  34173. for (var j = 0; j < 3; ++j) {
  34174. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  34175. }
  34176. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  34177. };
  34178. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  34179. _this.initialized = true;
  34180. callback();
  34181. });
  34182. });
  34183. };
  34184. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  34185. var newTriangles = [];
  34186. var i;
  34187. for (i = 0; i < this.vertices.length; ++i) {
  34188. this.vertices[i].triangleCount = 0;
  34189. }
  34190. var t;
  34191. var j;
  34192. for (i = 0; i < this.triangles.length; ++i) {
  34193. if (!this.triangles[i].deleted) {
  34194. t = this.triangles[i];
  34195. for (j = 0; j < 3; ++j) {
  34196. t.vertices[j].triangleCount = 1;
  34197. }
  34198. newTriangles.push(t);
  34199. }
  34200. }
  34201. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  34202. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  34203. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  34204. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  34205. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34206. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34207. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34208. var vertexCount = 0;
  34209. for (i = 0; i < this.vertices.length; ++i) {
  34210. var vertex = this.vertices[i];
  34211. vertex.id = vertexCount;
  34212. if (vertex.triangleCount) {
  34213. vertex.originalOffsets.forEach(function (originalOffset) {
  34214. newPositionData.push(vertex.position.x);
  34215. newPositionData.push(vertex.position.y);
  34216. newPositionData.push(vertex.position.z);
  34217. newNormalData.push(normalData[originalOffset * 3]);
  34218. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  34219. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  34220. if (uvs && uvs.length) {
  34221. newUVsData.push(uvs[(originalOffset * 2)]);
  34222. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  34223. }
  34224. else if (colorsData && colorsData.length) {
  34225. newColorsData.push(colorsData[(originalOffset * 4)]);
  34226. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  34227. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  34228. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  34229. }
  34230. ++vertexCount;
  34231. });
  34232. }
  34233. }
  34234. var startingIndex = this._reconstructedMesh.getTotalIndices();
  34235. var startingVertex = this._reconstructedMesh.getTotalVertices();
  34236. var submeshesArray = this._reconstructedMesh.subMeshes;
  34237. this._reconstructedMesh.subMeshes = [];
  34238. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  34239. var originalIndices = this._mesh.getIndices();
  34240. for (i = 0; i < newTriangles.length; ++i) {
  34241. t = newTriangles[i]; //now get the new referencing point for each vertex
  34242. [0, 1, 2].forEach(function (idx) {
  34243. var id = originalIndices[t.originalOffset + idx];
  34244. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  34245. if (offset < 0)
  34246. offset = 0;
  34247. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  34248. });
  34249. }
  34250. //overwriting the old vertex buffers and indices.
  34251. this._reconstructedMesh.setIndices(newIndicesArray);
  34252. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  34253. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  34254. if (newUVsData.length > 0)
  34255. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  34256. if (newColorsData.length > 0)
  34257. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  34258. //create submesh
  34259. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  34260. if (submeshIndex > 0) {
  34261. this._reconstructedMesh.subMeshes = [];
  34262. submeshesArray.forEach(function (submesh) {
  34263. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  34264. });
  34265. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  34266. }
  34267. };
  34268. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  34269. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  34270. this._reconstructedMesh.material = this._mesh.material;
  34271. this._reconstructedMesh.parent = this._mesh.parent;
  34272. this._reconstructedMesh.isVisible = false;
  34273. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  34274. };
  34275. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  34276. for (var i = 0; i < vertex1.triangleCount; ++i) {
  34277. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  34278. if (t.deleted)
  34279. continue;
  34280. var s = this.references[vertex1.triangleStart + i].vertexId;
  34281. var v1 = t.vertices[(s + 1) % 3];
  34282. var v2 = t.vertices[(s + 2) % 3];
  34283. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  34284. deletedArray[i] = true;
  34285. delTr.push(t);
  34286. continue;
  34287. }
  34288. var d1 = v1.position.subtract(point);
  34289. d1 = d1.normalize();
  34290. var d2 = v2.position.subtract(point);
  34291. d2 = d2.normalize();
  34292. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  34293. return true;
  34294. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  34295. deletedArray[i] = false;
  34296. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  34297. return true;
  34298. }
  34299. return false;
  34300. };
  34301. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  34302. var newDeleted = deletedTriangles;
  34303. for (var i = 0; i < vertex.triangleCount; ++i) {
  34304. var ref = this.references[vertex.triangleStart + i];
  34305. var t = this.triangles[ref.triangleId];
  34306. if (t.deleted)
  34307. continue;
  34308. if (deletedArray[i] && t.deletePending) {
  34309. t.deleted = true;
  34310. newDeleted++;
  34311. continue;
  34312. }
  34313. t.vertices[ref.vertexId] = origVertex;
  34314. t.isDirty = true;
  34315. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  34316. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  34317. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  34318. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  34319. this.references.push(ref);
  34320. }
  34321. return newDeleted;
  34322. };
  34323. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  34324. for (var i = 0; i < this.vertices.length; ++i) {
  34325. var vCount = [];
  34326. var vId = [];
  34327. var v = this.vertices[i];
  34328. var j;
  34329. for (j = 0; j < v.triangleCount; ++j) {
  34330. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  34331. for (var ii = 0; ii < 3; ii++) {
  34332. var ofs = 0;
  34333. var vv = triangle.vertices[ii];
  34334. while (ofs < vCount.length) {
  34335. if (vId[ofs] === vv.id)
  34336. break;
  34337. ++ofs;
  34338. }
  34339. if (ofs === vCount.length) {
  34340. vCount.push(1);
  34341. vId.push(vv.id);
  34342. }
  34343. else {
  34344. vCount[ofs]++;
  34345. }
  34346. }
  34347. }
  34348. for (j = 0; j < vCount.length; ++j) {
  34349. if (vCount[j] === 1) {
  34350. this.vertices[vId[j]].isBorder = true;
  34351. }
  34352. else {
  34353. this.vertices[vId[j]].isBorder = false;
  34354. }
  34355. }
  34356. }
  34357. };
  34358. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  34359. if (identifyBorders === void 0) { identifyBorders = false; }
  34360. var i;
  34361. if (!identifyBorders) {
  34362. var newTrianglesVector = [];
  34363. for (i = 0; i < this.triangles.length; ++i) {
  34364. if (!this.triangles[i].deleted) {
  34365. newTrianglesVector.push(this.triangles[i]);
  34366. }
  34367. }
  34368. this.triangles = newTrianglesVector;
  34369. }
  34370. for (i = 0; i < this.vertices.length; ++i) {
  34371. this.vertices[i].triangleCount = 0;
  34372. this.vertices[i].triangleStart = 0;
  34373. }
  34374. var t;
  34375. var j;
  34376. var v;
  34377. for (i = 0; i < this.triangles.length; ++i) {
  34378. t = this.triangles[i];
  34379. for (j = 0; j < 3; ++j) {
  34380. v = t.vertices[j];
  34381. v.triangleCount++;
  34382. }
  34383. }
  34384. var tStart = 0;
  34385. for (i = 0; i < this.vertices.length; ++i) {
  34386. this.vertices[i].triangleStart = tStart;
  34387. tStart += this.vertices[i].triangleCount;
  34388. this.vertices[i].triangleCount = 0;
  34389. }
  34390. var newReferences = new Array(this.triangles.length * 3);
  34391. for (i = 0; i < this.triangles.length; ++i) {
  34392. t = this.triangles[i];
  34393. for (j = 0; j < 3; ++j) {
  34394. v = t.vertices[j];
  34395. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  34396. v.triangleCount++;
  34397. }
  34398. }
  34399. this.references = newReferences;
  34400. if (identifyBorders) {
  34401. this.identifyBorder();
  34402. }
  34403. };
  34404. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  34405. var x = point.x;
  34406. var y = point.y;
  34407. var z = point.z;
  34408. 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
  34409. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  34410. };
  34411. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  34412. var q = vertex1.q.add(vertex2.q);
  34413. var border = vertex1.isBorder && vertex2.isBorder;
  34414. var error = 0;
  34415. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  34416. if (qDet !== 0 && !border) {
  34417. if (!pointResult) {
  34418. pointResult = BABYLON.Vector3.Zero();
  34419. }
  34420. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  34421. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  34422. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  34423. error = this.vertexError(q, pointResult);
  34424. }
  34425. else {
  34426. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  34427. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  34428. var error1 = this.vertexError(q, vertex1.position);
  34429. var error2 = this.vertexError(q, vertex2.position);
  34430. var error3 = this.vertexError(q, p3);
  34431. error = Math.min(error1, error2, error3);
  34432. if (error === error1) {
  34433. if (pointResult) {
  34434. pointResult.copyFrom(vertex1.position);
  34435. }
  34436. }
  34437. else if (error === error2) {
  34438. if (pointResult) {
  34439. pointResult.copyFrom(vertex2.position);
  34440. }
  34441. }
  34442. else {
  34443. if (pointResult) {
  34444. pointResult.copyFrom(p3);
  34445. }
  34446. }
  34447. }
  34448. return error;
  34449. };
  34450. return QuadraticErrorSimplification;
  34451. })();
  34452. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  34453. })(BABYLON || (BABYLON = {}));
  34454. var BABYLON;
  34455. (function (BABYLON) {
  34456. var serializedGeometries = [];
  34457. var serializeGeometry = function (geometry, serializationGeometries) {
  34458. if (serializedGeometries[geometry.id]) {
  34459. return;
  34460. }
  34461. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  34462. serializationGeometries.boxes.push(geometry.serialize());
  34463. }
  34464. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  34465. serializationGeometries.spheres.push(geometry.serialize());
  34466. }
  34467. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  34468. serializationGeometries.cylinders.push(geometry.serialize());
  34469. }
  34470. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  34471. serializationGeometries.toruses.push(geometry.serialize());
  34472. }
  34473. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  34474. serializationGeometries.grounds.push(geometry.serialize());
  34475. }
  34476. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  34477. serializationGeometries.planes.push(geometry.serialize());
  34478. }
  34479. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  34480. serializationGeometries.torusKnots.push(geometry.serialize());
  34481. }
  34482. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  34483. throw new Error("Unknown primitive type");
  34484. }
  34485. else {
  34486. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  34487. }
  34488. serializedGeometries[geometry.id] = true;
  34489. };
  34490. var serializeMesh = function (mesh, serializationScene) {
  34491. var serializationObject = {};
  34492. serializationObject.name = mesh.name;
  34493. serializationObject.id = mesh.id;
  34494. if (BABYLON.Tags.HasTags(mesh)) {
  34495. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  34496. }
  34497. serializationObject.position = mesh.position.asArray();
  34498. if (mesh.rotationQuaternion) {
  34499. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  34500. }
  34501. else if (mesh.rotation) {
  34502. serializationObject.rotation = mesh.rotation.asArray();
  34503. }
  34504. serializationObject.scaling = mesh.scaling.asArray();
  34505. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  34506. serializationObject.isEnabled = mesh.isEnabled();
  34507. serializationObject.isVisible = mesh.isVisible;
  34508. serializationObject.infiniteDistance = mesh.infiniteDistance;
  34509. serializationObject.pickable = mesh.isPickable;
  34510. serializationObject.receiveShadows = mesh.receiveShadows;
  34511. serializationObject.billboardMode = mesh.billboardMode;
  34512. serializationObject.visibility = mesh.visibility;
  34513. serializationObject.checkCollisions = mesh.checkCollisions;
  34514. // Parent
  34515. if (mesh.parent) {
  34516. serializationObject.parentId = mesh.parent.id;
  34517. }
  34518. // Geometry
  34519. var geometry = mesh._geometry;
  34520. if (geometry) {
  34521. var geometryId = geometry.id;
  34522. serializationObject.geometryId = geometryId;
  34523. if (!mesh.getScene().getGeometryByID(geometryId)) {
  34524. // 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
  34525. serializeGeometry(geometry, serializationScene.geometries);
  34526. }
  34527. // SubMeshes
  34528. serializationObject.subMeshes = [];
  34529. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34530. var subMesh = mesh.subMeshes[subIndex];
  34531. serializationObject.subMeshes.push({
  34532. materialIndex: subMesh.materialIndex,
  34533. verticesStart: subMesh.verticesStart,
  34534. verticesCount: subMesh.verticesCount,
  34535. indexStart: subMesh.indexStart,
  34536. indexCount: subMesh.indexCount
  34537. });
  34538. }
  34539. }
  34540. // Material
  34541. if (mesh.material) {
  34542. serializationObject.materialId = mesh.material.id;
  34543. }
  34544. else {
  34545. mesh.material = null;
  34546. }
  34547. // Skeleton
  34548. if (mesh.skeleton) {
  34549. serializationObject.skeletonId = mesh.skeleton.id;
  34550. }
  34551. // Physics
  34552. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  34553. serializationObject.physicsMass = mesh.getPhysicsMass();
  34554. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  34555. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  34556. switch (mesh.getPhysicsImpostor().type) {
  34557. case BABYLON.PhysicsEngine.BoxImpostor:
  34558. serializationObject.physicsImpostor = 1;
  34559. break;
  34560. case BABYLON.PhysicsEngine.SphereImpostor:
  34561. serializationObject.physicsImpostor = 2;
  34562. break;
  34563. }
  34564. }
  34565. // Instances
  34566. serializationObject.instances = [];
  34567. for (var index = 0; index < mesh.instances.length; index++) {
  34568. var instance = mesh.instances[index];
  34569. var serializationInstance = {
  34570. name: instance.name,
  34571. position: instance.position.asArray(),
  34572. scaling: instance.scaling.asArray()
  34573. };
  34574. if (instance.rotationQuaternion) {
  34575. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34576. }
  34577. else if (instance.rotation) {
  34578. serializationInstance.rotation = instance.rotation.asArray();
  34579. }
  34580. serializationObject.instances.push(serializationInstance);
  34581. // Animations
  34582. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34583. serializationInstance.ranges = instance.serializeAnimationRanges();
  34584. }
  34585. // Animations
  34586. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  34587. serializationObject.ranges = mesh.serializeAnimationRanges();
  34588. // Layer mask
  34589. serializationObject.layerMask = mesh.layerMask;
  34590. return serializationObject;
  34591. };
  34592. var finalizeSingleMesh = function (mesh, serializationObject) {
  34593. //only works if the mesh is already loaded
  34594. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  34595. //serialize material
  34596. if (mesh.material) {
  34597. if (mesh.material instanceof BABYLON.StandardMaterial) {
  34598. serializationObject.materials = serializationObject.materials || [];
  34599. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  34600. serializationObject.materials.push(mesh.material.serialize());
  34601. }
  34602. }
  34603. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  34604. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  34605. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  34606. serializationObject.multiMaterials.push(mesh.material.serialize());
  34607. }
  34608. }
  34609. }
  34610. //serialize geometry
  34611. var geometry = mesh._geometry;
  34612. if (geometry) {
  34613. if (!serializationObject.geometries) {
  34614. serializationObject.geometries = {};
  34615. serializationObject.geometries.boxes = [];
  34616. serializationObject.geometries.spheres = [];
  34617. serializationObject.geometries.cylinders = [];
  34618. serializationObject.geometries.toruses = [];
  34619. serializationObject.geometries.grounds = [];
  34620. serializationObject.geometries.planes = [];
  34621. serializationObject.geometries.torusKnots = [];
  34622. serializationObject.geometries.vertexData = [];
  34623. }
  34624. serializeGeometry(geometry, serializationObject.geometries);
  34625. }
  34626. // Skeletons
  34627. if (mesh.skeleton) {
  34628. serializationObject.skeletons = serializationObject.skeletons || [];
  34629. serializationObject.skeletons.push(mesh.skeleton.serialize());
  34630. }
  34631. //serialize the actual mesh
  34632. serializationObject.meshes = serializationObject.meshes || [];
  34633. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  34634. }
  34635. };
  34636. var SceneSerializer = (function () {
  34637. function SceneSerializer() {
  34638. }
  34639. SceneSerializer.ClearCache = function () {
  34640. serializedGeometries = [];
  34641. };
  34642. SceneSerializer.Serialize = function (scene) {
  34643. var serializationObject = {};
  34644. // Scene
  34645. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  34646. serializationObject.autoClear = scene.autoClear;
  34647. serializationObject.clearColor = scene.clearColor.asArray();
  34648. serializationObject.ambientColor = scene.ambientColor.asArray();
  34649. serializationObject.gravity = scene.gravity.asArray();
  34650. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  34651. serializationObject.workerCollisions = scene.workerCollisions;
  34652. // Fog
  34653. if (scene.fogMode && scene.fogMode !== 0) {
  34654. serializationObject.fogMode = scene.fogMode;
  34655. serializationObject.fogColor = scene.fogColor.asArray();
  34656. serializationObject.fogStart = scene.fogStart;
  34657. serializationObject.fogEnd = scene.fogEnd;
  34658. serializationObject.fogDensity = scene.fogDensity;
  34659. }
  34660. //Physics
  34661. if (scene.isPhysicsEnabled()) {
  34662. serializationObject.physicsEnabled = true;
  34663. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  34664. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  34665. }
  34666. // Lights
  34667. serializationObject.lights = [];
  34668. var index;
  34669. var light;
  34670. for (index = 0; index < scene.lights.length; index++) {
  34671. light = scene.lights[index];
  34672. serializationObject.lights.push(light.serialize());
  34673. }
  34674. // Cameras
  34675. serializationObject.cameras = [];
  34676. for (index = 0; index < scene.cameras.length; index++) {
  34677. var camera = scene.cameras[index];
  34678. serializationObject.cameras.push(camera.serialize());
  34679. }
  34680. if (scene.activeCamera) {
  34681. serializationObject.activeCameraID = scene.activeCamera.id;
  34682. }
  34683. // Animations
  34684. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  34685. // Materials
  34686. serializationObject.materials = [];
  34687. serializationObject.multiMaterials = [];
  34688. var material;
  34689. for (index = 0; index < scene.materials.length; index++) {
  34690. material = scene.materials[index];
  34691. serializationObject.materials.push(material.serialize());
  34692. }
  34693. // MultiMaterials
  34694. serializationObject.multiMaterials = [];
  34695. for (index = 0; index < scene.multiMaterials.length; index++) {
  34696. var multiMaterial = scene.multiMaterials[index];
  34697. serializationObject.multiMaterials.push(multiMaterial.serialize());
  34698. }
  34699. // Skeletons
  34700. serializationObject.skeletons = [];
  34701. for (index = 0; index < scene.skeletons.length; index++) {
  34702. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  34703. }
  34704. // Geometries
  34705. serializationObject.geometries = {};
  34706. serializationObject.geometries.boxes = [];
  34707. serializationObject.geometries.spheres = [];
  34708. serializationObject.geometries.cylinders = [];
  34709. serializationObject.geometries.toruses = [];
  34710. serializationObject.geometries.grounds = [];
  34711. serializationObject.geometries.planes = [];
  34712. serializationObject.geometries.torusKnots = [];
  34713. serializationObject.geometries.vertexData = [];
  34714. serializedGeometries = [];
  34715. var geometries = scene.getGeometries();
  34716. for (index = 0; index < geometries.length; index++) {
  34717. var geometry = geometries[index];
  34718. if (geometry.isReady()) {
  34719. serializeGeometry(geometry, serializationObject.geometries);
  34720. }
  34721. }
  34722. // Meshes
  34723. serializationObject.meshes = [];
  34724. for (index = 0; index < scene.meshes.length; index++) {
  34725. var abstractMesh = scene.meshes[index];
  34726. if (abstractMesh instanceof BABYLON.Mesh) {
  34727. var mesh = abstractMesh;
  34728. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  34729. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  34730. }
  34731. }
  34732. }
  34733. // Particles Systems
  34734. serializationObject.particleSystems = [];
  34735. for (index = 0; index < scene.particleSystems.length; index++) {
  34736. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  34737. }
  34738. // Lens flares
  34739. serializationObject.lensFlareSystems = [];
  34740. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  34741. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  34742. }
  34743. // Shadows
  34744. serializationObject.shadowGenerators = [];
  34745. for (index = 0; index < scene.lights.length; index++) {
  34746. light = scene.lights[index];
  34747. if (light.getShadowGenerator()) {
  34748. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  34749. }
  34750. }
  34751. return serializationObject;
  34752. };
  34753. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  34754. if (withParents === void 0) { withParents = false; }
  34755. if (withChildren === void 0) { withChildren = false; }
  34756. var serializationObject = {};
  34757. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  34758. if (withParents || withChildren) {
  34759. //deliberate for loop! not for each, appended should be processed as well.
  34760. for (var i = 0; i < toSerialize.length; ++i) {
  34761. if (withChildren) {
  34762. toSerialize[i].getDescendants().forEach(function (node) {
  34763. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  34764. toSerialize.push(node);
  34765. }
  34766. });
  34767. }
  34768. //make sure the array doesn't contain the object already
  34769. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  34770. toSerialize.push(toSerialize[i].parent);
  34771. }
  34772. }
  34773. }
  34774. toSerialize.forEach(function (mesh) {
  34775. finalizeSingleMesh(mesh, serializationObject);
  34776. });
  34777. return serializationObject;
  34778. };
  34779. return SceneSerializer;
  34780. })();
  34781. BABYLON.SceneSerializer = SceneSerializer;
  34782. })(BABYLON || (BABYLON = {}));
  34783. var BABYLON;
  34784. (function (BABYLON) {
  34785. // Unique ID when we import meshes from Babylon to CSG
  34786. var currentCSGMeshId = 0;
  34787. // # class Vertex
  34788. // Represents a vertex of a polygon. Use your own vertex class instead of this
  34789. // one to provide additional features like texture coordinates and vertex
  34790. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  34791. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  34792. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  34793. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  34794. // is not used anywhere else.
  34795. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  34796. var Vertex = (function () {
  34797. function Vertex(pos, normal, uv) {
  34798. this.pos = pos;
  34799. this.normal = normal;
  34800. this.uv = uv;
  34801. }
  34802. Vertex.prototype.clone = function () {
  34803. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  34804. };
  34805. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  34806. // orientation of a polygon is flipped.
  34807. Vertex.prototype.flip = function () {
  34808. this.normal = this.normal.scale(-1);
  34809. };
  34810. // Create a new vertex between this vertex and `other` by linearly
  34811. // interpolating all properties using a parameter of `t`. Subclasses should
  34812. // override this to interpolate additional properties.
  34813. Vertex.prototype.interpolate = function (other, t) {
  34814. 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));
  34815. };
  34816. return Vertex;
  34817. })();
  34818. // # class Plane
  34819. // Represents a plane in 3D space.
  34820. var Plane = (function () {
  34821. function Plane(normal, w) {
  34822. this.normal = normal;
  34823. this.w = w;
  34824. }
  34825. Plane.FromPoints = function (a, b, c) {
  34826. var v0 = c.subtract(a);
  34827. var v1 = b.subtract(a);
  34828. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  34829. return null;
  34830. }
  34831. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  34832. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  34833. };
  34834. Plane.prototype.clone = function () {
  34835. return new Plane(this.normal.clone(), this.w);
  34836. };
  34837. Plane.prototype.flip = function () {
  34838. this.normal.scaleInPlace(-1);
  34839. this.w = -this.w;
  34840. };
  34841. // Split `polygon` by this plane if needed, then put the polygon or polygon
  34842. // fragments in the appropriate lists. Coplanar polygons go into either
  34843. // `coplanarFront` or `coplanarBack` depending on their orientation with
  34844. // respect to this plane. Polygons in front or in back of this plane go into
  34845. // either `front` or `back`.
  34846. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  34847. var COPLANAR = 0;
  34848. var FRONT = 1;
  34849. var BACK = 2;
  34850. var SPANNING = 3;
  34851. // Classify each point as well as the entire polygon into one of the above
  34852. // four classes.
  34853. var polygonType = 0;
  34854. var types = [];
  34855. var i;
  34856. var t;
  34857. for (i = 0; i < polygon.vertices.length; i++) {
  34858. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  34859. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  34860. polygonType |= type;
  34861. types.push(type);
  34862. }
  34863. // Put the polygon in the correct list, splitting it when necessary.
  34864. switch (polygonType) {
  34865. case COPLANAR:
  34866. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  34867. break;
  34868. case FRONT:
  34869. front.push(polygon);
  34870. break;
  34871. case BACK:
  34872. back.push(polygon);
  34873. break;
  34874. case SPANNING:
  34875. var f = [], b = [];
  34876. for (i = 0; i < polygon.vertices.length; i++) {
  34877. var j = (i + 1) % polygon.vertices.length;
  34878. var ti = types[i], tj = types[j];
  34879. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  34880. if (ti !== BACK)
  34881. f.push(vi);
  34882. if (ti !== FRONT)
  34883. b.push(ti !== BACK ? vi.clone() : vi);
  34884. if ((ti | tj) === SPANNING) {
  34885. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  34886. var v = vi.interpolate(vj, t);
  34887. f.push(v);
  34888. b.push(v.clone());
  34889. }
  34890. }
  34891. var poly;
  34892. if (f.length >= 3) {
  34893. poly = new Polygon(f, polygon.shared);
  34894. if (poly.plane)
  34895. front.push(poly);
  34896. }
  34897. if (b.length >= 3) {
  34898. poly = new Polygon(b, polygon.shared);
  34899. if (poly.plane)
  34900. back.push(poly);
  34901. }
  34902. break;
  34903. }
  34904. };
  34905. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  34906. // point is on the plane.
  34907. Plane.EPSILON = 1e-5;
  34908. return Plane;
  34909. })();
  34910. // # class Polygon
  34911. // Represents a convex polygon. The vertices used to initialize a polygon must
  34912. // be coplanar and form a convex loop.
  34913. //
  34914. // Each convex polygon has a `shared` property, which is shared between all
  34915. // polygons that are clones of each other or were split from the same polygon.
  34916. // This can be used to define per-polygon properties (such as surface color).
  34917. var Polygon = (function () {
  34918. function Polygon(vertices, shared) {
  34919. this.vertices = vertices;
  34920. this.shared = shared;
  34921. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  34922. }
  34923. Polygon.prototype.clone = function () {
  34924. var vertices = this.vertices.map(function (v) { return v.clone(); });
  34925. return new Polygon(vertices, this.shared);
  34926. };
  34927. Polygon.prototype.flip = function () {
  34928. this.vertices.reverse().map(function (v) { v.flip(); });
  34929. this.plane.flip();
  34930. };
  34931. return Polygon;
  34932. })();
  34933. // # class Node
  34934. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  34935. // by picking a polygon to split along. That polygon (and all other coplanar
  34936. // polygons) are added directly to that node and the other polygons are added to
  34937. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  34938. // no distinction between internal and leaf nodes.
  34939. var Node = (function () {
  34940. function Node(polygons) {
  34941. this.plane = null;
  34942. this.front = null;
  34943. this.back = null;
  34944. this.polygons = [];
  34945. if (polygons) {
  34946. this.build(polygons);
  34947. }
  34948. }
  34949. Node.prototype.clone = function () {
  34950. var node = new Node();
  34951. node.plane = this.plane && this.plane.clone();
  34952. node.front = this.front && this.front.clone();
  34953. node.back = this.back && this.back.clone();
  34954. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  34955. return node;
  34956. };
  34957. // Convert solid space to empty space and empty space to solid space.
  34958. Node.prototype.invert = function () {
  34959. for (var i = 0; i < this.polygons.length; i++) {
  34960. this.polygons[i].flip();
  34961. }
  34962. if (this.plane) {
  34963. this.plane.flip();
  34964. }
  34965. if (this.front) {
  34966. this.front.invert();
  34967. }
  34968. if (this.back) {
  34969. this.back.invert();
  34970. }
  34971. var temp = this.front;
  34972. this.front = this.back;
  34973. this.back = temp;
  34974. };
  34975. // Recursively remove all polygons in `polygons` that are inside this BSP
  34976. // tree.
  34977. Node.prototype.clipPolygons = function (polygons) {
  34978. if (!this.plane)
  34979. return polygons.slice();
  34980. var front = [], back = [];
  34981. for (var i = 0; i < polygons.length; i++) {
  34982. this.plane.splitPolygon(polygons[i], front, back, front, back);
  34983. }
  34984. if (this.front) {
  34985. front = this.front.clipPolygons(front);
  34986. }
  34987. if (this.back) {
  34988. back = this.back.clipPolygons(back);
  34989. }
  34990. else {
  34991. back = [];
  34992. }
  34993. return front.concat(back);
  34994. };
  34995. // Remove all polygons in this BSP tree that are inside the other BSP tree
  34996. // `bsp`.
  34997. Node.prototype.clipTo = function (bsp) {
  34998. this.polygons = bsp.clipPolygons(this.polygons);
  34999. if (this.front)
  35000. this.front.clipTo(bsp);
  35001. if (this.back)
  35002. this.back.clipTo(bsp);
  35003. };
  35004. // Return a list of all polygons in this BSP tree.
  35005. Node.prototype.allPolygons = function () {
  35006. var polygons = this.polygons.slice();
  35007. if (this.front)
  35008. polygons = polygons.concat(this.front.allPolygons());
  35009. if (this.back)
  35010. polygons = polygons.concat(this.back.allPolygons());
  35011. return polygons;
  35012. };
  35013. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  35014. // new polygons are filtered down to the bottom of the tree and become new
  35015. // nodes there. Each set of polygons is partitioned using the first polygon
  35016. // (no heuristic is used to pick a good split).
  35017. Node.prototype.build = function (polygons) {
  35018. if (!polygons.length)
  35019. return;
  35020. if (!this.plane)
  35021. this.plane = polygons[0].plane.clone();
  35022. var front = [], back = [];
  35023. for (var i = 0; i < polygons.length; i++) {
  35024. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  35025. }
  35026. if (front.length) {
  35027. if (!this.front)
  35028. this.front = new Node();
  35029. this.front.build(front);
  35030. }
  35031. if (back.length) {
  35032. if (!this.back)
  35033. this.back = new Node();
  35034. this.back.build(back);
  35035. }
  35036. };
  35037. return Node;
  35038. })();
  35039. var CSG = (function () {
  35040. function CSG() {
  35041. this.polygons = new Array();
  35042. }
  35043. // Convert BABYLON.Mesh to BABYLON.CSG
  35044. CSG.FromMesh = function (mesh) {
  35045. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  35046. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  35047. if (mesh instanceof BABYLON.Mesh) {
  35048. mesh.computeWorldMatrix(true);
  35049. matrix = mesh.getWorldMatrix();
  35050. meshPosition = mesh.position.clone();
  35051. meshRotation = mesh.rotation.clone();
  35052. if (mesh.rotationQuaternion) {
  35053. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  35054. }
  35055. meshScaling = mesh.scaling.clone();
  35056. }
  35057. else {
  35058. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  35059. }
  35060. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35061. var subMeshes = mesh.subMeshes;
  35062. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  35063. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  35064. vertices = [];
  35065. for (var j = 0; j < 3; j++) {
  35066. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  35067. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  35068. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  35069. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  35070. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  35071. vertex = new Vertex(position, normal, uv);
  35072. vertices.push(vertex);
  35073. }
  35074. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  35075. // To handle the case of degenerated triangle
  35076. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  35077. if (polygon.plane)
  35078. polygons.push(polygon);
  35079. }
  35080. }
  35081. var csg = CSG.FromPolygons(polygons);
  35082. csg.matrix = matrix;
  35083. csg.position = meshPosition;
  35084. csg.rotation = meshRotation;
  35085. csg.scaling = meshScaling;
  35086. csg.rotationQuaternion = meshRotationQuaternion;
  35087. currentCSGMeshId++;
  35088. return csg;
  35089. };
  35090. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  35091. CSG.FromPolygons = function (polygons) {
  35092. var csg = new CSG();
  35093. csg.polygons = polygons;
  35094. return csg;
  35095. };
  35096. CSG.prototype.clone = function () {
  35097. var csg = new CSG();
  35098. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  35099. csg.copyTransformAttributes(this);
  35100. return csg;
  35101. };
  35102. CSG.prototype.toPolygons = function () {
  35103. return this.polygons;
  35104. };
  35105. CSG.prototype.union = function (csg) {
  35106. var a = new Node(this.clone().polygons);
  35107. var b = new Node(csg.clone().polygons);
  35108. a.clipTo(b);
  35109. b.clipTo(a);
  35110. b.invert();
  35111. b.clipTo(a);
  35112. b.invert();
  35113. a.build(b.allPolygons());
  35114. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35115. };
  35116. CSG.prototype.unionInPlace = function (csg) {
  35117. var a = new Node(this.polygons);
  35118. var b = new Node(csg.polygons);
  35119. a.clipTo(b);
  35120. b.clipTo(a);
  35121. b.invert();
  35122. b.clipTo(a);
  35123. b.invert();
  35124. a.build(b.allPolygons());
  35125. this.polygons = a.allPolygons();
  35126. };
  35127. CSG.prototype.subtract = function (csg) {
  35128. var a = new Node(this.clone().polygons);
  35129. var b = new Node(csg.clone().polygons);
  35130. a.invert();
  35131. a.clipTo(b);
  35132. b.clipTo(a);
  35133. b.invert();
  35134. b.clipTo(a);
  35135. b.invert();
  35136. a.build(b.allPolygons());
  35137. a.invert();
  35138. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35139. };
  35140. CSG.prototype.subtractInPlace = function (csg) {
  35141. var a = new Node(this.polygons);
  35142. var b = new Node(csg.polygons);
  35143. a.invert();
  35144. a.clipTo(b);
  35145. b.clipTo(a);
  35146. b.invert();
  35147. b.clipTo(a);
  35148. b.invert();
  35149. a.build(b.allPolygons());
  35150. a.invert();
  35151. this.polygons = a.allPolygons();
  35152. };
  35153. CSG.prototype.intersect = function (csg) {
  35154. var a = new Node(this.clone().polygons);
  35155. var b = new Node(csg.clone().polygons);
  35156. a.invert();
  35157. b.clipTo(a);
  35158. b.invert();
  35159. a.clipTo(b);
  35160. b.clipTo(a);
  35161. a.build(b.allPolygons());
  35162. a.invert();
  35163. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35164. };
  35165. CSG.prototype.intersectInPlace = function (csg) {
  35166. var a = new Node(this.polygons);
  35167. var b = new Node(csg.polygons);
  35168. a.invert();
  35169. b.clipTo(a);
  35170. b.invert();
  35171. a.clipTo(b);
  35172. b.clipTo(a);
  35173. a.build(b.allPolygons());
  35174. a.invert();
  35175. this.polygons = a.allPolygons();
  35176. };
  35177. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  35178. // not modified.
  35179. CSG.prototype.inverse = function () {
  35180. var csg = this.clone();
  35181. csg.inverseInPlace();
  35182. return csg;
  35183. };
  35184. CSG.prototype.inverseInPlace = function () {
  35185. this.polygons.map(function (p) { p.flip(); });
  35186. };
  35187. // This is used to keep meshes transformations so they can be restored
  35188. // when we build back a Babylon Mesh
  35189. // NB : All CSG operations are performed in world coordinates
  35190. CSG.prototype.copyTransformAttributes = function (csg) {
  35191. this.matrix = csg.matrix;
  35192. this.position = csg.position;
  35193. this.rotation = csg.rotation;
  35194. this.scaling = csg.scaling;
  35195. this.rotationQuaternion = csg.rotationQuaternion;
  35196. return this;
  35197. };
  35198. // Build Raw mesh from CSG
  35199. // Coordinates here are in world space
  35200. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  35201. var matrix = this.matrix.clone();
  35202. matrix.invert();
  35203. 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;
  35204. if (keepSubMeshes) {
  35205. // Sort Polygons, since subMeshes are indices range
  35206. polygons.sort(function (a, b) {
  35207. if (a.shared.meshId === b.shared.meshId) {
  35208. return a.shared.subMeshId - b.shared.subMeshId;
  35209. }
  35210. else {
  35211. return a.shared.meshId - b.shared.meshId;
  35212. }
  35213. });
  35214. }
  35215. for (var i = 0, il = polygons.length; i < il; i++) {
  35216. polygon = polygons[i];
  35217. // Building SubMeshes
  35218. if (!subMesh_dict[polygon.shared.meshId]) {
  35219. subMesh_dict[polygon.shared.meshId] = {};
  35220. }
  35221. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  35222. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  35223. indexStart: +Infinity,
  35224. indexEnd: -Infinity,
  35225. materialIndex: polygon.shared.materialIndex
  35226. };
  35227. }
  35228. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  35229. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  35230. polygonIndices[0] = 0;
  35231. polygonIndices[1] = j - 1;
  35232. polygonIndices[2] = j;
  35233. for (var k = 0; k < 3; k++) {
  35234. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  35235. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  35236. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  35237. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  35238. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  35239. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  35240. // Check if 2 points can be merged
  35241. if (!(typeof vertex_idx !== 'undefined' &&
  35242. normals[vertex_idx * 3] === localNormal.x &&
  35243. normals[vertex_idx * 3 + 1] === localNormal.y &&
  35244. normals[vertex_idx * 3 + 2] === localNormal.z &&
  35245. uvs[vertex_idx * 2] === uv.x &&
  35246. uvs[vertex_idx * 2 + 1] === uv.y)) {
  35247. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  35248. uvs.push(uv.x, uv.y);
  35249. normals.push(normal.x, normal.y, normal.z);
  35250. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  35251. }
  35252. indices.push(vertex_idx);
  35253. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  35254. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  35255. currentIndex++;
  35256. }
  35257. }
  35258. }
  35259. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  35260. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  35261. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  35262. mesh.setIndices(indices);
  35263. if (keepSubMeshes) {
  35264. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  35265. var materialIndexOffset = 0, materialMaxIndex;
  35266. mesh.subMeshes = new Array();
  35267. for (var m in subMesh_dict) {
  35268. materialMaxIndex = -1;
  35269. for (var sm in subMesh_dict[m]) {
  35270. subMesh_obj = subMesh_dict[m][sm];
  35271. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  35272. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  35273. }
  35274. materialIndexOffset += ++materialMaxIndex;
  35275. }
  35276. }
  35277. return mesh;
  35278. };
  35279. // Build Mesh from CSG taking material and transforms into account
  35280. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  35281. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  35282. mesh.material = material;
  35283. mesh.position.copyFrom(this.position);
  35284. mesh.rotation.copyFrom(this.rotation);
  35285. if (this.rotationQuaternion) {
  35286. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  35287. }
  35288. mesh.scaling.copyFrom(this.scaling);
  35289. mesh.computeWorldMatrix(true);
  35290. return mesh;
  35291. };
  35292. return CSG;
  35293. })();
  35294. BABYLON.CSG = CSG;
  35295. })(BABYLON || (BABYLON = {}));
  35296. var BABYLON;
  35297. (function (BABYLON) {
  35298. var VRDistortionCorrectionPostProcess = (function (_super) {
  35299. __extends(VRDistortionCorrectionPostProcess, _super);
  35300. //ANY
  35301. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  35302. var _this = this;
  35303. _super.call(this, name, "vrDistortionCorrection", [
  35304. 'LensCenter',
  35305. 'Scale',
  35306. 'ScaleIn',
  35307. 'HmdWarpParam'
  35308. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  35309. this._isRightEye = isRightEye;
  35310. this._distortionFactors = vrMetrics.distortionK;
  35311. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  35312. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  35313. this.onSizeChanged = function () {
  35314. _this.aspectRatio = _this.width * .5 / _this.height;
  35315. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  35316. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  35317. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  35318. };
  35319. this.onApply = function (effect) {
  35320. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  35321. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  35322. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  35323. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  35324. };
  35325. }
  35326. return VRDistortionCorrectionPostProcess;
  35327. })(BABYLON.PostProcess);
  35328. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  35329. })(BABYLON || (BABYLON = {}));
  35330. // Mainly based on these 2 articles :
  35331. // 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
  35332. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  35333. var BABYLON;
  35334. (function (BABYLON) {
  35335. (function (JoystickAxis) {
  35336. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  35337. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  35338. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  35339. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  35340. var JoystickAxis = BABYLON.JoystickAxis;
  35341. var VirtualJoystick = (function () {
  35342. function VirtualJoystick(leftJoystick) {
  35343. var _this = this;
  35344. if (leftJoystick) {
  35345. this._leftJoystick = true;
  35346. }
  35347. else {
  35348. this._leftJoystick = false;
  35349. }
  35350. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  35351. VirtualJoystick._globalJoystickIndex++;
  35352. // By default left & right arrow keys are moving the X
  35353. // and up & down keys are moving the Y
  35354. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  35355. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  35356. this.reverseLeftRight = false;
  35357. this.reverseUpDown = false;
  35358. // collections of pointers
  35359. this._touches = new BABYLON.SmartCollection();
  35360. this.deltaPosition = BABYLON.Vector3.Zero();
  35361. this._joystickSensibility = 25;
  35362. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  35363. this._rotationSpeed = 25;
  35364. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  35365. this._rotateOnAxisRelativeToMesh = false;
  35366. this._onResize = function (evt) {
  35367. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  35368. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  35369. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  35370. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  35371. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  35372. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  35373. };
  35374. // injecting a canvas element on top of the canvas 3D game
  35375. if (!VirtualJoystick.vjCanvas) {
  35376. window.addEventListener("resize", this._onResize, false);
  35377. VirtualJoystick.vjCanvas = document.createElement("canvas");
  35378. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  35379. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  35380. VirtualJoystick.vjCanvas.width = window.innerWidth;
  35381. VirtualJoystick.vjCanvas.height = window.innerHeight;
  35382. VirtualJoystick.vjCanvas.style.width = "100%";
  35383. VirtualJoystick.vjCanvas.style.height = "100%";
  35384. VirtualJoystick.vjCanvas.style.position = "absolute";
  35385. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  35386. VirtualJoystick.vjCanvas.style.top = "0px";
  35387. VirtualJoystick.vjCanvas.style.left = "0px";
  35388. VirtualJoystick.vjCanvas.style.zIndex = "5";
  35389. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  35390. // Support for jQuery PEP polyfill
  35391. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  35392. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  35393. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  35394. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  35395. document.body.appendChild(VirtualJoystick.vjCanvas);
  35396. }
  35397. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  35398. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  35399. this.pressed = false;
  35400. // default joystick color
  35401. this._joystickColor = "cyan";
  35402. this._joystickPointerID = -1;
  35403. // current joystick position
  35404. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  35405. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  35406. // origin joystick position
  35407. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  35408. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  35409. this._onPointerDownHandlerRef = function (evt) {
  35410. _this._onPointerDown(evt);
  35411. };
  35412. this._onPointerMoveHandlerRef = function (evt) {
  35413. _this._onPointerMove(evt);
  35414. };
  35415. this._onPointerOutHandlerRef = function (evt) {
  35416. _this._onPointerUp(evt);
  35417. };
  35418. this._onPointerUpHandlerRef = function (evt) {
  35419. _this._onPointerUp(evt);
  35420. };
  35421. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  35422. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  35423. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  35424. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  35425. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  35426. evt.preventDefault(); // Disables system menu
  35427. }, false);
  35428. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  35429. }
  35430. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  35431. this._joystickSensibility = newJoystickSensibility;
  35432. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  35433. };
  35434. VirtualJoystick.prototype._onPointerDown = function (e) {
  35435. var positionOnScreenCondition;
  35436. e.preventDefault();
  35437. if (this._leftJoystick === true) {
  35438. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  35439. }
  35440. else {
  35441. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  35442. }
  35443. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  35444. // First contact will be dedicated to the virtual joystick
  35445. this._joystickPointerID = e.pointerId;
  35446. this._joystickPointerStartPos.x = e.clientX;
  35447. this._joystickPointerStartPos.y = e.clientY;
  35448. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  35449. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  35450. this._deltaJoystickVector.x = 0;
  35451. this._deltaJoystickVector.y = 0;
  35452. this.pressed = true;
  35453. this._touches.add(e.pointerId.toString(), e);
  35454. }
  35455. else {
  35456. // You can only trigger the action buttons with a joystick declared
  35457. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  35458. this._action();
  35459. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  35460. }
  35461. }
  35462. };
  35463. VirtualJoystick.prototype._onPointerMove = function (e) {
  35464. // If the current pointer is the one associated to the joystick (first touch contact)
  35465. if (this._joystickPointerID == e.pointerId) {
  35466. this._joystickPointerPos.x = e.clientX;
  35467. this._joystickPointerPos.y = e.clientY;
  35468. this._deltaJoystickVector = this._joystickPointerPos.clone();
  35469. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  35470. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  35471. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  35472. switch (this._axisTargetedByLeftAndRight) {
  35473. case JoystickAxis.X:
  35474. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  35475. break;
  35476. case JoystickAxis.Y:
  35477. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  35478. break;
  35479. case JoystickAxis.Z:
  35480. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  35481. break;
  35482. }
  35483. var directionUpDown = this.reverseUpDown ? 1 : -1;
  35484. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  35485. switch (this._axisTargetedByUpAndDown) {
  35486. case JoystickAxis.X:
  35487. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  35488. break;
  35489. case JoystickAxis.Y:
  35490. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  35491. break;
  35492. case JoystickAxis.Z:
  35493. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  35494. break;
  35495. }
  35496. }
  35497. else {
  35498. if (this._touches.item(e.pointerId.toString())) {
  35499. this._touches.item(e.pointerId.toString()).x = e.clientX;
  35500. this._touches.item(e.pointerId.toString()).y = e.clientY;
  35501. }
  35502. }
  35503. };
  35504. VirtualJoystick.prototype._onPointerUp = function (e) {
  35505. if (this._joystickPointerID == e.pointerId) {
  35506. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  35507. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  35508. this._joystickPointerID = -1;
  35509. this.pressed = false;
  35510. }
  35511. else {
  35512. var touch = this._touches.item(e.pointerId.toString());
  35513. if (touch) {
  35514. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  35515. }
  35516. }
  35517. this._deltaJoystickVector.x = 0;
  35518. this._deltaJoystickVector.y = 0;
  35519. this._touches.remove(e.pointerId.toString());
  35520. };
  35521. /**
  35522. * Change the color of the virtual joystick
  35523. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  35524. */
  35525. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  35526. this._joystickColor = newColor;
  35527. };
  35528. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  35529. this._action = action;
  35530. };
  35531. // Define which axis you'd like to control for left & right
  35532. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  35533. switch (axis) {
  35534. case JoystickAxis.X:
  35535. case JoystickAxis.Y:
  35536. case JoystickAxis.Z:
  35537. this._axisTargetedByLeftAndRight = axis;
  35538. break;
  35539. default:
  35540. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  35541. break;
  35542. }
  35543. };
  35544. // Define which axis you'd like to control for up & down
  35545. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  35546. switch (axis) {
  35547. case JoystickAxis.X:
  35548. case JoystickAxis.Y:
  35549. case JoystickAxis.Z:
  35550. this._axisTargetedByUpAndDown = axis;
  35551. break;
  35552. default:
  35553. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  35554. break;
  35555. }
  35556. };
  35557. VirtualJoystick.prototype._clearCanvas = function () {
  35558. if (this._leftJoystick) {
  35559. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  35560. }
  35561. else {
  35562. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  35563. }
  35564. };
  35565. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  35566. var _this = this;
  35567. if (this.pressed) {
  35568. this._touches.forEach(function (touch) {
  35569. if (touch.pointerId === _this._joystickPointerID) {
  35570. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  35571. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  35572. VirtualJoystick.vjCanvasContext.beginPath();
  35573. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  35574. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35575. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  35576. VirtualJoystick.vjCanvasContext.stroke();
  35577. VirtualJoystick.vjCanvasContext.closePath();
  35578. VirtualJoystick.vjCanvasContext.beginPath();
  35579. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35580. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  35581. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  35582. VirtualJoystick.vjCanvasContext.stroke();
  35583. VirtualJoystick.vjCanvasContext.closePath();
  35584. VirtualJoystick.vjCanvasContext.beginPath();
  35585. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35586. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  35587. VirtualJoystick.vjCanvasContext.stroke();
  35588. VirtualJoystick.vjCanvasContext.closePath();
  35589. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  35590. }
  35591. else {
  35592. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  35593. VirtualJoystick.vjCanvasContext.beginPath();
  35594. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  35595. VirtualJoystick.vjCanvasContext.beginPath();
  35596. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  35597. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  35598. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  35599. VirtualJoystick.vjCanvasContext.stroke();
  35600. VirtualJoystick.vjCanvasContext.closePath();
  35601. touch.prevX = touch.x;
  35602. touch.prevY = touch.y;
  35603. }
  35604. ;
  35605. });
  35606. }
  35607. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  35608. };
  35609. VirtualJoystick.prototype.releaseCanvas = function () {
  35610. if (VirtualJoystick.vjCanvas) {
  35611. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  35612. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  35613. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  35614. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  35615. window.removeEventListener("resize", this._onResize);
  35616. document.body.removeChild(VirtualJoystick.vjCanvas);
  35617. VirtualJoystick.vjCanvas = null;
  35618. }
  35619. };
  35620. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  35621. VirtualJoystick._globalJoystickIndex = 0;
  35622. return VirtualJoystick;
  35623. })();
  35624. BABYLON.VirtualJoystick = VirtualJoystick;
  35625. })(BABYLON || (BABYLON = {}));
  35626. var BABYLON;
  35627. (function (BABYLON) {
  35628. // We're mainly based on the logic defined into the FreeCamera code
  35629. var VirtualJoysticksCamera = (function (_super) {
  35630. __extends(VirtualJoysticksCamera, _super);
  35631. function VirtualJoysticksCamera(name, position, scene) {
  35632. _super.call(this, name, position, scene);
  35633. this.inputs.addVirtualJoystick();
  35634. }
  35635. return VirtualJoysticksCamera;
  35636. })(BABYLON.FreeCamera);
  35637. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  35638. })(BABYLON || (BABYLON = {}));
  35639. var BABYLON;
  35640. (function (BABYLON) {
  35641. var AnaglyphPostProcess = (function (_super) {
  35642. __extends(AnaglyphPostProcess, _super);
  35643. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35644. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  35645. }
  35646. return AnaglyphPostProcess;
  35647. })(BABYLON.PostProcess);
  35648. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  35649. })(BABYLON || (BABYLON = {}));
  35650. var BABYLON;
  35651. (function (BABYLON) {
  35652. var OutlineRenderer = (function () {
  35653. function OutlineRenderer(scene) {
  35654. this._scene = scene;
  35655. }
  35656. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  35657. var _this = this;
  35658. if (useOverlay === void 0) { useOverlay = false; }
  35659. var scene = this._scene;
  35660. var engine = this._scene.getEngine();
  35661. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35662. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  35663. return;
  35664. }
  35665. var mesh = subMesh.getRenderingMesh();
  35666. var material = subMesh.getMaterial();
  35667. engine.enableEffect(this._effect);
  35668. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  35669. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  35670. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35671. // Bones
  35672. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35673. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35674. }
  35675. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35676. // Alpha test
  35677. if (material && material.needAlphaTesting()) {
  35678. var alphaTexture = material.getAlphaTestTexture();
  35679. this._effect.setTexture("diffuseSampler", alphaTexture);
  35680. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35681. }
  35682. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  35683. };
  35684. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  35685. var defines = [];
  35686. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  35687. var mesh = subMesh.getMesh();
  35688. var material = subMesh.getMaterial();
  35689. // Alpha test
  35690. if (material && material.needAlphaTesting()) {
  35691. defines.push("#define ALPHATEST");
  35692. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35693. attribs.push(BABYLON.VertexBuffer.UVKind);
  35694. defines.push("#define UV1");
  35695. }
  35696. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35697. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35698. defines.push("#define UV2");
  35699. }
  35700. }
  35701. // Bones
  35702. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35703. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35704. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35705. if (mesh.numBoneInfluencers > 4) {
  35706. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35707. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35708. }
  35709. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35710. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35711. }
  35712. else {
  35713. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35714. }
  35715. // Instances
  35716. if (useInstances) {
  35717. defines.push("#define INSTANCES");
  35718. attribs.push("world0");
  35719. attribs.push("world1");
  35720. attribs.push("world2");
  35721. attribs.push("world3");
  35722. }
  35723. // Get correct effect
  35724. var join = defines.join("\n");
  35725. if (this._cachedDefines !== join) {
  35726. this._cachedDefines = join;
  35727. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  35728. }
  35729. return this._effect.isReady();
  35730. };
  35731. return OutlineRenderer;
  35732. })();
  35733. BABYLON.OutlineRenderer = OutlineRenderer;
  35734. })(BABYLON || (BABYLON = {}));
  35735. var BABYLON;
  35736. (function (BABYLON) {
  35737. var MeshAssetTask = (function () {
  35738. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  35739. this.name = name;
  35740. this.meshesNames = meshesNames;
  35741. this.rootUrl = rootUrl;
  35742. this.sceneFilename = sceneFilename;
  35743. this.isCompleted = false;
  35744. }
  35745. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35746. var _this = this;
  35747. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  35748. _this.loadedMeshes = meshes;
  35749. _this.loadedParticleSystems = particleSystems;
  35750. _this.loadedSkeletons = skeletons;
  35751. _this.isCompleted = true;
  35752. if (_this.onSuccess) {
  35753. _this.onSuccess(_this);
  35754. }
  35755. onSuccess();
  35756. }, null, function () {
  35757. if (_this.onError) {
  35758. _this.onError(_this);
  35759. }
  35760. onError();
  35761. });
  35762. };
  35763. return MeshAssetTask;
  35764. })();
  35765. BABYLON.MeshAssetTask = MeshAssetTask;
  35766. var TextFileAssetTask = (function () {
  35767. function TextFileAssetTask(name, url) {
  35768. this.name = name;
  35769. this.url = url;
  35770. this.isCompleted = false;
  35771. }
  35772. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35773. var _this = this;
  35774. BABYLON.Tools.LoadFile(this.url, function (data) {
  35775. _this.text = data;
  35776. _this.isCompleted = true;
  35777. if (_this.onSuccess) {
  35778. _this.onSuccess(_this);
  35779. }
  35780. onSuccess();
  35781. }, null, scene.database, false, function () {
  35782. if (_this.onError) {
  35783. _this.onError(_this);
  35784. }
  35785. onError();
  35786. });
  35787. };
  35788. return TextFileAssetTask;
  35789. })();
  35790. BABYLON.TextFileAssetTask = TextFileAssetTask;
  35791. var BinaryFileAssetTask = (function () {
  35792. function BinaryFileAssetTask(name, url) {
  35793. this.name = name;
  35794. this.url = url;
  35795. this.isCompleted = false;
  35796. }
  35797. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35798. var _this = this;
  35799. BABYLON.Tools.LoadFile(this.url, function (data) {
  35800. _this.data = data;
  35801. _this.isCompleted = true;
  35802. if (_this.onSuccess) {
  35803. _this.onSuccess(_this);
  35804. }
  35805. onSuccess();
  35806. }, null, scene.database, true, function () {
  35807. if (_this.onError) {
  35808. _this.onError(_this);
  35809. }
  35810. onError();
  35811. });
  35812. };
  35813. return BinaryFileAssetTask;
  35814. })();
  35815. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  35816. var ImageAssetTask = (function () {
  35817. function ImageAssetTask(name, url) {
  35818. this.name = name;
  35819. this.url = url;
  35820. this.isCompleted = false;
  35821. }
  35822. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35823. var _this = this;
  35824. var img = new Image();
  35825. img.onload = function () {
  35826. _this.image = img;
  35827. _this.isCompleted = true;
  35828. if (_this.onSuccess) {
  35829. _this.onSuccess(_this);
  35830. }
  35831. onSuccess();
  35832. };
  35833. img.onerror = function () {
  35834. if (_this.onError) {
  35835. _this.onError(_this);
  35836. }
  35837. onError();
  35838. };
  35839. img.src = this.url;
  35840. };
  35841. return ImageAssetTask;
  35842. })();
  35843. BABYLON.ImageAssetTask = ImageAssetTask;
  35844. var TextureAssetTask = (function () {
  35845. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  35846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35847. this.name = name;
  35848. this.url = url;
  35849. this.noMipmap = noMipmap;
  35850. this.invertY = invertY;
  35851. this.samplingMode = samplingMode;
  35852. this.isCompleted = false;
  35853. }
  35854. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35855. var _this = this;
  35856. var onload = function () {
  35857. _this.isCompleted = true;
  35858. if (_this.onSuccess) {
  35859. _this.onSuccess(_this);
  35860. }
  35861. onSuccess();
  35862. };
  35863. var onerror = function () {
  35864. if (_this.onError) {
  35865. _this.onError(_this);
  35866. }
  35867. onError();
  35868. };
  35869. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  35870. };
  35871. return TextureAssetTask;
  35872. })();
  35873. BABYLON.TextureAssetTask = TextureAssetTask;
  35874. var AssetsManager = (function () {
  35875. function AssetsManager(scene) {
  35876. this._tasks = new Array();
  35877. this._waitingTasksCount = 0;
  35878. this.useDefaultLoadingScreen = true;
  35879. this._scene = scene;
  35880. }
  35881. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  35882. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  35883. this._tasks.push(task);
  35884. return task;
  35885. };
  35886. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  35887. var task = new TextFileAssetTask(taskName, url);
  35888. this._tasks.push(task);
  35889. return task;
  35890. };
  35891. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  35892. var task = new BinaryFileAssetTask(taskName, url);
  35893. this._tasks.push(task);
  35894. return task;
  35895. };
  35896. AssetsManager.prototype.addImageTask = function (taskName, url) {
  35897. var task = new ImageAssetTask(taskName, url);
  35898. this._tasks.push(task);
  35899. return task;
  35900. };
  35901. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  35902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35903. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  35904. this._tasks.push(task);
  35905. return task;
  35906. };
  35907. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  35908. this._waitingTasksCount--;
  35909. if (this._waitingTasksCount === 0) {
  35910. if (this.onFinish) {
  35911. this.onFinish(this._tasks);
  35912. }
  35913. this._scene.getEngine().hideLoadingUI();
  35914. }
  35915. };
  35916. AssetsManager.prototype._runTask = function (task) {
  35917. var _this = this;
  35918. task.run(this._scene, function () {
  35919. if (_this.onTaskSuccess) {
  35920. _this.onTaskSuccess(task);
  35921. }
  35922. _this._decreaseWaitingTasksCount();
  35923. }, function () {
  35924. if (_this.onTaskError) {
  35925. _this.onTaskError(task);
  35926. }
  35927. _this._decreaseWaitingTasksCount();
  35928. });
  35929. };
  35930. AssetsManager.prototype.reset = function () {
  35931. this._tasks = new Array();
  35932. return this;
  35933. };
  35934. AssetsManager.prototype.load = function () {
  35935. this._waitingTasksCount = this._tasks.length;
  35936. if (this._waitingTasksCount === 0) {
  35937. if (this.onFinish) {
  35938. this.onFinish(this._tasks);
  35939. }
  35940. return this;
  35941. }
  35942. if (this.useDefaultLoadingScreen) {
  35943. this._scene.getEngine().displayLoadingUI();
  35944. }
  35945. for (var index = 0; index < this._tasks.length; index++) {
  35946. var task = this._tasks[index];
  35947. this._runTask(task);
  35948. }
  35949. return this;
  35950. };
  35951. return AssetsManager;
  35952. })();
  35953. BABYLON.AssetsManager = AssetsManager;
  35954. })(BABYLON || (BABYLON = {}));
  35955. var BABYLON;
  35956. (function (BABYLON) {
  35957. var VRCameraMetrics = (function () {
  35958. function VRCameraMetrics() {
  35959. this.compensateDistortion = true;
  35960. }
  35961. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  35962. get: function () {
  35963. return this.hResolution / (2 * this.vResolution);
  35964. },
  35965. enumerable: true,
  35966. configurable: true
  35967. });
  35968. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  35969. get: function () {
  35970. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  35971. },
  35972. enumerable: true,
  35973. configurable: true
  35974. });
  35975. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  35976. get: function () {
  35977. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  35978. var h = (4 * meters) / this.hScreenSize;
  35979. return BABYLON.Matrix.Translation(h, 0, 0);
  35980. },
  35981. enumerable: true,
  35982. configurable: true
  35983. });
  35984. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  35985. get: function () {
  35986. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  35987. var h = (4 * meters) / this.hScreenSize;
  35988. return BABYLON.Matrix.Translation(-h, 0, 0);
  35989. },
  35990. enumerable: true,
  35991. configurable: true
  35992. });
  35993. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  35994. get: function () {
  35995. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  35996. },
  35997. enumerable: true,
  35998. configurable: true
  35999. });
  36000. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  36001. get: function () {
  36002. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  36003. },
  36004. enumerable: true,
  36005. configurable: true
  36006. });
  36007. VRCameraMetrics.GetDefault = function () {
  36008. var result = new VRCameraMetrics();
  36009. result.hResolution = 1280;
  36010. result.vResolution = 800;
  36011. result.hScreenSize = 0.149759993;
  36012. result.vScreenSize = 0.0935999975;
  36013. result.vScreenCenter = 0.0467999987,
  36014. result.eyeToScreenDistance = 0.0410000011;
  36015. result.lensSeparationDistance = 0.0635000020;
  36016. result.interpupillaryDistance = 0.0640000030;
  36017. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  36018. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  36019. result.postProcessScaleFactor = 1.714605507808412;
  36020. result.lensCenterOffset = 0.151976421;
  36021. return result;
  36022. };
  36023. return VRCameraMetrics;
  36024. })();
  36025. BABYLON.VRCameraMetrics = VRCameraMetrics;
  36026. })(BABYLON || (BABYLON = {}));
  36027. var BABYLON;
  36028. (function (BABYLON) {
  36029. var VRDeviceOrientationFreeCamera = (function (_super) {
  36030. __extends(VRDeviceOrientationFreeCamera, _super);
  36031. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  36032. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36033. _super.call(this, name, position, scene);
  36034. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  36035. metrics.compensateDistortion = compensateDistortion;
  36036. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  36037. this.inputs.addVRDeviceOrientation();
  36038. }
  36039. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  36040. return "VRDeviceOrientationFreeCamera";
  36041. };
  36042. return VRDeviceOrientationFreeCamera;
  36043. })(BABYLON.FreeCamera);
  36044. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  36045. })(BABYLON || (BABYLON = {}));
  36046. var BABYLON;
  36047. (function (BABYLON) {
  36048. var WebVRFreeCamera = (function (_super) {
  36049. __extends(WebVRFreeCamera, _super);
  36050. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  36051. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36052. _super.call(this, name, position, scene);
  36053. this._hmdDevice = null;
  36054. this._sensorDevice = null;
  36055. this._cacheState = null;
  36056. this._cacheQuaternion = new BABYLON.Quaternion();
  36057. this._cacheRotation = BABYLON.Vector3.Zero();
  36058. this._vrEnabled = false;
  36059. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  36060. metrics.compensateDistortion = compensateDistortion;
  36061. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  36062. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  36063. }
  36064. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  36065. var size = devices.length;
  36066. var i = 0;
  36067. // Reset devices.
  36068. this._sensorDevice = null;
  36069. this._hmdDevice = null;
  36070. // Search for a HmdDevice.
  36071. while (i < size && this._hmdDevice === null) {
  36072. if (devices[i] instanceof HMDVRDevice) {
  36073. this._hmdDevice = devices[i];
  36074. }
  36075. i++;
  36076. }
  36077. i = 0;
  36078. while (i < size && this._sensorDevice === null) {
  36079. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  36080. this._sensorDevice = devices[i];
  36081. }
  36082. i++;
  36083. }
  36084. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  36085. };
  36086. WebVRFreeCamera.prototype._checkInputs = function () {
  36087. if (this._vrEnabled) {
  36088. this._cacheState = this._sensorDevice.getState();
  36089. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  36090. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  36091. this.rotation.x = -this._cacheRotation.x;
  36092. this.rotation.y = -this._cacheRotation.y;
  36093. this.rotation.z = this._cacheRotation.z;
  36094. }
  36095. _super.prototype._checkInputs.call(this);
  36096. };
  36097. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  36098. _super.prototype.attachControl.call(this, element, noPreventDefault);
  36099. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36100. if (navigator.getVRDevices) {
  36101. navigator.getVRDevices().then(this._getWebVRDevices);
  36102. }
  36103. else if (navigator.mozGetVRDevices) {
  36104. navigator.mozGetVRDevices(this._getWebVRDevices);
  36105. }
  36106. };
  36107. WebVRFreeCamera.prototype.detachControl = function (element) {
  36108. _super.prototype.detachControl.call(this, element);
  36109. this._vrEnabled = false;
  36110. };
  36111. WebVRFreeCamera.prototype.getTypeName = function () {
  36112. return "WebVRFreeCamera";
  36113. };
  36114. return WebVRFreeCamera;
  36115. })(BABYLON.FreeCamera);
  36116. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  36117. })(BABYLON || (BABYLON = {}));
  36118. var BABYLON;
  36119. (function (BABYLON) {
  36120. // Standard optimizations
  36121. var SceneOptimization = (function () {
  36122. function SceneOptimization(priority) {
  36123. if (priority === void 0) { priority = 0; }
  36124. this.priority = priority;
  36125. this.apply = function (scene) {
  36126. return true; // Return true if everything that can be done was applied
  36127. };
  36128. }
  36129. return SceneOptimization;
  36130. })();
  36131. BABYLON.SceneOptimization = SceneOptimization;
  36132. var TextureOptimization = (function (_super) {
  36133. __extends(TextureOptimization, _super);
  36134. function TextureOptimization(priority, maximumSize) {
  36135. var _this = this;
  36136. if (priority === void 0) { priority = 0; }
  36137. if (maximumSize === void 0) { maximumSize = 1024; }
  36138. _super.call(this, priority);
  36139. this.priority = priority;
  36140. this.maximumSize = maximumSize;
  36141. this.apply = function (scene) {
  36142. var allDone = true;
  36143. for (var index = 0; index < scene.textures.length; index++) {
  36144. var texture = scene.textures[index];
  36145. if (!texture.canRescale) {
  36146. continue;
  36147. }
  36148. var currentSize = texture.getSize();
  36149. var maxDimension = Math.max(currentSize.width, currentSize.height);
  36150. if (maxDimension > _this.maximumSize) {
  36151. texture.scale(0.5);
  36152. allDone = false;
  36153. }
  36154. }
  36155. return allDone;
  36156. };
  36157. }
  36158. return TextureOptimization;
  36159. })(SceneOptimization);
  36160. BABYLON.TextureOptimization = TextureOptimization;
  36161. var HardwareScalingOptimization = (function (_super) {
  36162. __extends(HardwareScalingOptimization, _super);
  36163. function HardwareScalingOptimization(priority, maximumScale) {
  36164. var _this = this;
  36165. if (priority === void 0) { priority = 0; }
  36166. if (maximumScale === void 0) { maximumScale = 2; }
  36167. _super.call(this, priority);
  36168. this.priority = priority;
  36169. this.maximumScale = maximumScale;
  36170. this._currentScale = 1;
  36171. this.apply = function (scene) {
  36172. _this._currentScale++;
  36173. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  36174. return _this._currentScale >= _this.maximumScale;
  36175. };
  36176. }
  36177. return HardwareScalingOptimization;
  36178. })(SceneOptimization);
  36179. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  36180. var ShadowsOptimization = (function (_super) {
  36181. __extends(ShadowsOptimization, _super);
  36182. function ShadowsOptimization() {
  36183. _super.apply(this, arguments);
  36184. this.apply = function (scene) {
  36185. scene.shadowsEnabled = false;
  36186. return true;
  36187. };
  36188. }
  36189. return ShadowsOptimization;
  36190. })(SceneOptimization);
  36191. BABYLON.ShadowsOptimization = ShadowsOptimization;
  36192. var PostProcessesOptimization = (function (_super) {
  36193. __extends(PostProcessesOptimization, _super);
  36194. function PostProcessesOptimization() {
  36195. _super.apply(this, arguments);
  36196. this.apply = function (scene) {
  36197. scene.postProcessesEnabled = false;
  36198. return true;
  36199. };
  36200. }
  36201. return PostProcessesOptimization;
  36202. })(SceneOptimization);
  36203. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  36204. var LensFlaresOptimization = (function (_super) {
  36205. __extends(LensFlaresOptimization, _super);
  36206. function LensFlaresOptimization() {
  36207. _super.apply(this, arguments);
  36208. this.apply = function (scene) {
  36209. scene.lensFlaresEnabled = false;
  36210. return true;
  36211. };
  36212. }
  36213. return LensFlaresOptimization;
  36214. })(SceneOptimization);
  36215. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  36216. var ParticlesOptimization = (function (_super) {
  36217. __extends(ParticlesOptimization, _super);
  36218. function ParticlesOptimization() {
  36219. _super.apply(this, arguments);
  36220. this.apply = function (scene) {
  36221. scene.particlesEnabled = false;
  36222. return true;
  36223. };
  36224. }
  36225. return ParticlesOptimization;
  36226. })(SceneOptimization);
  36227. BABYLON.ParticlesOptimization = ParticlesOptimization;
  36228. var RenderTargetsOptimization = (function (_super) {
  36229. __extends(RenderTargetsOptimization, _super);
  36230. function RenderTargetsOptimization() {
  36231. _super.apply(this, arguments);
  36232. this.apply = function (scene) {
  36233. scene.renderTargetsEnabled = false;
  36234. return true;
  36235. };
  36236. }
  36237. return RenderTargetsOptimization;
  36238. })(SceneOptimization);
  36239. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  36240. var MergeMeshesOptimization = (function (_super) {
  36241. __extends(MergeMeshesOptimization, _super);
  36242. function MergeMeshesOptimization() {
  36243. var _this = this;
  36244. _super.apply(this, arguments);
  36245. this._canBeMerged = function (abstractMesh) {
  36246. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  36247. return false;
  36248. }
  36249. var mesh = abstractMesh;
  36250. if (!mesh.isVisible || !mesh.isEnabled()) {
  36251. return false;
  36252. }
  36253. if (mesh.instances.length > 0) {
  36254. return false;
  36255. }
  36256. if (mesh.skeleton || mesh.hasLODLevels) {
  36257. return false;
  36258. }
  36259. if (mesh.parent) {
  36260. return false;
  36261. }
  36262. return true;
  36263. };
  36264. this.apply = function (scene, updateSelectionTree) {
  36265. var globalPool = scene.meshes.slice(0);
  36266. var globalLength = globalPool.length;
  36267. for (var index = 0; index < globalLength; index++) {
  36268. var currentPool = new Array();
  36269. var current = globalPool[index];
  36270. // Checks
  36271. if (!_this._canBeMerged(current)) {
  36272. continue;
  36273. }
  36274. currentPool.push(current);
  36275. // Find compatible meshes
  36276. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  36277. var otherMesh = globalPool[subIndex];
  36278. if (!_this._canBeMerged(otherMesh)) {
  36279. continue;
  36280. }
  36281. if (otherMesh.material !== current.material) {
  36282. continue;
  36283. }
  36284. if (otherMesh.checkCollisions !== current.checkCollisions) {
  36285. continue;
  36286. }
  36287. currentPool.push(otherMesh);
  36288. globalLength--;
  36289. globalPool.splice(subIndex, 1);
  36290. subIndex--;
  36291. }
  36292. if (currentPool.length < 2) {
  36293. continue;
  36294. }
  36295. // Merge meshes
  36296. BABYLON.Mesh.MergeMeshes(currentPool);
  36297. }
  36298. if (updateSelectionTree != undefined) {
  36299. if (updateSelectionTree) {
  36300. scene.createOrUpdateSelectionOctree();
  36301. }
  36302. }
  36303. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  36304. scene.createOrUpdateSelectionOctree();
  36305. }
  36306. return true;
  36307. };
  36308. }
  36309. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  36310. get: function () {
  36311. return MergeMeshesOptimization._UpdateSelectionTree;
  36312. },
  36313. set: function (value) {
  36314. MergeMeshesOptimization._UpdateSelectionTree = value;
  36315. },
  36316. enumerable: true,
  36317. configurable: true
  36318. });
  36319. MergeMeshesOptimization._UpdateSelectionTree = false;
  36320. return MergeMeshesOptimization;
  36321. })(SceneOptimization);
  36322. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  36323. // Options
  36324. var SceneOptimizerOptions = (function () {
  36325. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  36326. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  36327. if (trackerDuration === void 0) { trackerDuration = 2000; }
  36328. this.targetFrameRate = targetFrameRate;
  36329. this.trackerDuration = trackerDuration;
  36330. this.optimizations = new Array();
  36331. }
  36332. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  36333. var result = new SceneOptimizerOptions(targetFrameRate);
  36334. var priority = 0;
  36335. result.optimizations.push(new MergeMeshesOptimization(priority));
  36336. result.optimizations.push(new ShadowsOptimization(priority));
  36337. result.optimizations.push(new LensFlaresOptimization(priority));
  36338. // Next priority
  36339. priority++;
  36340. result.optimizations.push(new PostProcessesOptimization(priority));
  36341. result.optimizations.push(new ParticlesOptimization(priority));
  36342. // Next priority
  36343. priority++;
  36344. result.optimizations.push(new TextureOptimization(priority, 1024));
  36345. return result;
  36346. };
  36347. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  36348. var result = new SceneOptimizerOptions(targetFrameRate);
  36349. var priority = 0;
  36350. result.optimizations.push(new MergeMeshesOptimization(priority));
  36351. result.optimizations.push(new ShadowsOptimization(priority));
  36352. result.optimizations.push(new LensFlaresOptimization(priority));
  36353. // Next priority
  36354. priority++;
  36355. result.optimizations.push(new PostProcessesOptimization(priority));
  36356. result.optimizations.push(new ParticlesOptimization(priority));
  36357. // Next priority
  36358. priority++;
  36359. result.optimizations.push(new TextureOptimization(priority, 512));
  36360. // Next priority
  36361. priority++;
  36362. result.optimizations.push(new RenderTargetsOptimization(priority));
  36363. // Next priority
  36364. priority++;
  36365. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  36366. return result;
  36367. };
  36368. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  36369. var result = new SceneOptimizerOptions(targetFrameRate);
  36370. var priority = 0;
  36371. result.optimizations.push(new MergeMeshesOptimization(priority));
  36372. result.optimizations.push(new ShadowsOptimization(priority));
  36373. result.optimizations.push(new LensFlaresOptimization(priority));
  36374. // Next priority
  36375. priority++;
  36376. result.optimizations.push(new PostProcessesOptimization(priority));
  36377. result.optimizations.push(new ParticlesOptimization(priority));
  36378. // Next priority
  36379. priority++;
  36380. result.optimizations.push(new TextureOptimization(priority, 256));
  36381. // Next priority
  36382. priority++;
  36383. result.optimizations.push(new RenderTargetsOptimization(priority));
  36384. // Next priority
  36385. priority++;
  36386. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  36387. return result;
  36388. };
  36389. return SceneOptimizerOptions;
  36390. })();
  36391. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  36392. // Scene optimizer tool
  36393. var SceneOptimizer = (function () {
  36394. function SceneOptimizer() {
  36395. }
  36396. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  36397. // TODO: add an epsilon
  36398. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  36399. if (onSuccess) {
  36400. onSuccess();
  36401. }
  36402. return;
  36403. }
  36404. // Apply current level of optimizations
  36405. var allDone = true;
  36406. var noOptimizationApplied = true;
  36407. for (var index = 0; index < options.optimizations.length; index++) {
  36408. var optimization = options.optimizations[index];
  36409. if (optimization.priority === currentPriorityLevel) {
  36410. noOptimizationApplied = false;
  36411. allDone = allDone && optimization.apply(scene);
  36412. }
  36413. }
  36414. // If no optimization was applied, this is a failure :(
  36415. if (noOptimizationApplied) {
  36416. if (onFailure) {
  36417. onFailure();
  36418. }
  36419. return;
  36420. }
  36421. // If all optimizations were done, move to next level
  36422. if (allDone) {
  36423. currentPriorityLevel++;
  36424. }
  36425. // Let's the system running for a specific amount of time before checking FPS
  36426. scene.executeWhenReady(function () {
  36427. setTimeout(function () {
  36428. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  36429. }, options.trackerDuration);
  36430. });
  36431. };
  36432. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  36433. if (!options) {
  36434. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  36435. }
  36436. // Let's the system running for a specific amount of time before checking FPS
  36437. scene.executeWhenReady(function () {
  36438. setTimeout(function () {
  36439. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  36440. }, options.trackerDuration);
  36441. });
  36442. };
  36443. return SceneOptimizer;
  36444. })();
  36445. BABYLON.SceneOptimizer = SceneOptimizer;
  36446. })(BABYLON || (BABYLON = {}));
  36447. var BABYLON;
  36448. (function (BABYLON) {
  36449. var Internals;
  36450. (function (Internals) {
  36451. var MeshLODLevel = (function () {
  36452. function MeshLODLevel(distance, mesh) {
  36453. this.distance = distance;
  36454. this.mesh = mesh;
  36455. }
  36456. return MeshLODLevel;
  36457. })();
  36458. Internals.MeshLODLevel = MeshLODLevel;
  36459. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36460. })(BABYLON || (BABYLON = {}));
  36461. var BABYLON;
  36462. (function (BABYLON) {
  36463. var RawTexture = (function (_super) {
  36464. __extends(RawTexture, _super);
  36465. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  36466. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36467. if (invertY === void 0) { invertY = false; }
  36468. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36469. _super.call(this, null, scene, !generateMipMaps, invertY);
  36470. this.format = format;
  36471. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  36472. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36473. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36474. }
  36475. RawTexture.prototype.update = function (data) {
  36476. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  36477. };
  36478. // Statics
  36479. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36480. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36481. if (invertY === void 0) { invertY = false; }
  36482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36483. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  36484. };
  36485. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36486. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36487. if (invertY === void 0) { invertY = false; }
  36488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36489. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  36490. };
  36491. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36492. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36493. if (invertY === void 0) { invertY = false; }
  36494. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36495. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  36496. };
  36497. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36498. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36499. if (invertY === void 0) { invertY = false; }
  36500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36501. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  36502. };
  36503. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36504. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36505. if (invertY === void 0) { invertY = false; }
  36506. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36507. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  36508. };
  36509. return RawTexture;
  36510. })(BABYLON.Texture);
  36511. BABYLON.RawTexture = RawTexture;
  36512. })(BABYLON || (BABYLON = {}));
  36513. var BABYLON;
  36514. (function (BABYLON) {
  36515. var IndexedVector2 = (function (_super) {
  36516. __extends(IndexedVector2, _super);
  36517. function IndexedVector2(original, index) {
  36518. _super.call(this, original.x, original.y);
  36519. this.index = index;
  36520. }
  36521. return IndexedVector2;
  36522. })(BABYLON.Vector2);
  36523. var PolygonPoints = (function () {
  36524. function PolygonPoints() {
  36525. this.elements = new Array();
  36526. }
  36527. PolygonPoints.prototype.add = function (originalPoints) {
  36528. var _this = this;
  36529. var result = new Array();
  36530. originalPoints.forEach(function (point) {
  36531. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  36532. var newPoint = new IndexedVector2(point, _this.elements.length);
  36533. result.push(newPoint);
  36534. _this.elements.push(newPoint);
  36535. }
  36536. });
  36537. return result;
  36538. };
  36539. PolygonPoints.prototype.computeBounds = function () {
  36540. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  36541. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  36542. this.elements.forEach(function (point) {
  36543. // x
  36544. if (point.x < lmin.x) {
  36545. lmin.x = point.x;
  36546. }
  36547. else if (point.x > lmax.x) {
  36548. lmax.x = point.x;
  36549. }
  36550. // y
  36551. if (point.y < lmin.y) {
  36552. lmin.y = point.y;
  36553. }
  36554. else if (point.y > lmax.y) {
  36555. lmax.y = point.y;
  36556. }
  36557. });
  36558. return {
  36559. min: lmin,
  36560. max: lmax,
  36561. width: lmax.x - lmin.x,
  36562. height: lmax.y - lmin.y
  36563. };
  36564. };
  36565. return PolygonPoints;
  36566. })();
  36567. var Polygon = (function () {
  36568. function Polygon() {
  36569. }
  36570. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  36571. return [
  36572. new BABYLON.Vector2(xmin, ymin),
  36573. new BABYLON.Vector2(xmax, ymin),
  36574. new BABYLON.Vector2(xmax, ymax),
  36575. new BABYLON.Vector2(xmin, ymax)
  36576. ];
  36577. };
  36578. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  36579. if (cx === void 0) { cx = 0; }
  36580. if (cy === void 0) { cy = 0; }
  36581. if (numberOfSides === void 0) { numberOfSides = 32; }
  36582. var result = new Array();
  36583. var angle = 0;
  36584. var increment = (Math.PI * 2) / numberOfSides;
  36585. for (var i = 0; i < numberOfSides; i++) {
  36586. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  36587. angle -= increment;
  36588. }
  36589. return result;
  36590. };
  36591. Polygon.Parse = function (input) {
  36592. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  36593. var i, result = [];
  36594. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  36595. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  36596. }
  36597. return result;
  36598. };
  36599. Polygon.StartingAt = function (x, y) {
  36600. return BABYLON.Path2.StartingAt(x, y);
  36601. };
  36602. return Polygon;
  36603. })();
  36604. BABYLON.Polygon = Polygon;
  36605. var PolygonMeshBuilder = (function () {
  36606. function PolygonMeshBuilder(name, contours, scene) {
  36607. this._points = new PolygonPoints();
  36608. this._outlinepoints = new PolygonPoints();
  36609. this._holes = [];
  36610. if (!("poly2tri" in window)) {
  36611. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  36612. }
  36613. this._name = name;
  36614. this._scene = scene;
  36615. var points;
  36616. if (contours instanceof BABYLON.Path2) {
  36617. points = contours.getPoints();
  36618. }
  36619. else {
  36620. points = contours;
  36621. }
  36622. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  36623. this._outlinepoints.add(points);
  36624. }
  36625. PolygonMeshBuilder.prototype.addHole = function (hole) {
  36626. this._swctx.addHole(this._points.add(hole));
  36627. var holepoints = new PolygonPoints();
  36628. holepoints.add(hole);
  36629. this._holes.push(holepoints);
  36630. return this;
  36631. };
  36632. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  36633. var _this = this;
  36634. if (updatable === void 0) { updatable = false; }
  36635. var result = new BABYLON.Mesh(this._name, this._scene);
  36636. var normals = [];
  36637. var positions = [];
  36638. var uvs = [];
  36639. var bounds = this._points.computeBounds();
  36640. this._points.elements.forEach(function (p) {
  36641. normals.push(0, 1.0, 0);
  36642. positions.push(p.x, 0, p.y);
  36643. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  36644. });
  36645. var indices = [];
  36646. this._swctx.triangulate();
  36647. this._swctx.getTriangles().forEach(function (triangle) {
  36648. triangle.getPoints().forEach(function (point) {
  36649. indices.push(point.index);
  36650. });
  36651. });
  36652. if (depth > 0) {
  36653. var positionscount = (positions.length / 3); //get the current pointcount
  36654. this._points.elements.forEach(function (p) {
  36655. normals.push(0, -1.0, 0);
  36656. positions.push(p.x, -depth, p.y);
  36657. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  36658. });
  36659. var p1; //we need to change order of point so the triangles are made in the rigth way.
  36660. var p2;
  36661. var poscounter = 0;
  36662. this._swctx.getTriangles().forEach(function (triangle) {
  36663. triangle.getPoints().forEach(function (point) {
  36664. switch (poscounter) {
  36665. case 0:
  36666. p1 = point;
  36667. break;
  36668. case 1:
  36669. p2 = point;
  36670. break;
  36671. case 2:
  36672. indices.push(point.index + positionscount);
  36673. indices.push(p2.index + positionscount);
  36674. indices.push(p1.index + positionscount);
  36675. poscounter = -1;
  36676. break;
  36677. }
  36678. poscounter++;
  36679. //indices.push((<IndexedVector2>point).index + positionscount);
  36680. });
  36681. });
  36682. //Add the sides
  36683. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  36684. this._holes.forEach(function (hole) {
  36685. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  36686. });
  36687. }
  36688. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  36689. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  36690. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  36691. result.setIndices(indices);
  36692. return result;
  36693. };
  36694. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  36695. var StartIndex = positions.length / 3;
  36696. var ulength = 0;
  36697. for (var i = 0; i < points.elements.length; i++) {
  36698. var p = points.elements[i];
  36699. var p1;
  36700. if ((i + 1) > points.elements.length - 1) {
  36701. p1 = points.elements[0];
  36702. }
  36703. else {
  36704. p1 = points.elements[i + 1];
  36705. }
  36706. positions.push(p.x, 0, p.y);
  36707. positions.push(p.x, -depth, p.y);
  36708. positions.push(p1.x, 0, p1.y);
  36709. positions.push(p1.x, -depth, p1.y);
  36710. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  36711. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  36712. var v3 = v2.subtract(v1);
  36713. var v4 = new BABYLON.Vector3(0, 1, 0);
  36714. var vn = BABYLON.Vector3.Cross(v3, v4);
  36715. vn = vn.normalize();
  36716. uvs.push(ulength / bounds.width, 0);
  36717. uvs.push(ulength / bounds.width, 1);
  36718. ulength += v3.length();
  36719. uvs.push((ulength / bounds.width), 0);
  36720. uvs.push((ulength / bounds.width), 1);
  36721. if (!flip) {
  36722. normals.push(-vn.x, -vn.y, -vn.z);
  36723. normals.push(-vn.x, -vn.y, -vn.z);
  36724. normals.push(-vn.x, -vn.y, -vn.z);
  36725. normals.push(-vn.x, -vn.y, -vn.z);
  36726. indices.push(StartIndex);
  36727. indices.push(StartIndex + 1);
  36728. indices.push(StartIndex + 2);
  36729. indices.push(StartIndex + 1);
  36730. indices.push(StartIndex + 3);
  36731. indices.push(StartIndex + 2);
  36732. }
  36733. else {
  36734. normals.push(vn.x, vn.y, vn.z);
  36735. normals.push(vn.x, vn.y, vn.z);
  36736. normals.push(vn.x, vn.y, vn.z);
  36737. normals.push(vn.x, vn.y, vn.z);
  36738. indices.push(StartIndex);
  36739. indices.push(StartIndex + 2);
  36740. indices.push(StartIndex + 1);
  36741. indices.push(StartIndex + 1);
  36742. indices.push(StartIndex + 2);
  36743. indices.push(StartIndex + 3);
  36744. }
  36745. StartIndex += 4;
  36746. }
  36747. ;
  36748. };
  36749. return PolygonMeshBuilder;
  36750. })();
  36751. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  36752. })(BABYLON || (BABYLON = {}));
  36753. var BABYLON;
  36754. (function (BABYLON) {
  36755. var Octree = (function () {
  36756. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  36757. if (maxDepth === void 0) { maxDepth = 2; }
  36758. this.maxDepth = maxDepth;
  36759. this.dynamicContent = new Array();
  36760. this._maxBlockCapacity = maxBlockCapacity || 64;
  36761. this._selectionContent = new BABYLON.SmartArray(1024);
  36762. this._creationFunc = creationFunc;
  36763. }
  36764. // Methods
  36765. Octree.prototype.update = function (worldMin, worldMax, entries) {
  36766. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  36767. };
  36768. Octree.prototype.addMesh = function (entry) {
  36769. for (var index = 0; index < this.blocks.length; index++) {
  36770. var block = this.blocks[index];
  36771. block.addEntry(entry);
  36772. }
  36773. };
  36774. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  36775. this._selectionContent.reset();
  36776. for (var index = 0; index < this.blocks.length; index++) {
  36777. var block = this.blocks[index];
  36778. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  36779. }
  36780. if (allowDuplicate) {
  36781. this._selectionContent.concat(this.dynamicContent);
  36782. }
  36783. else {
  36784. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36785. }
  36786. return this._selectionContent;
  36787. };
  36788. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  36789. this._selectionContent.reset();
  36790. for (var index = 0; index < this.blocks.length; index++) {
  36791. var block = this.blocks[index];
  36792. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  36793. }
  36794. if (allowDuplicate) {
  36795. this._selectionContent.concat(this.dynamicContent);
  36796. }
  36797. else {
  36798. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36799. }
  36800. return this._selectionContent;
  36801. };
  36802. Octree.prototype.intersectsRay = function (ray) {
  36803. this._selectionContent.reset();
  36804. for (var index = 0; index < this.blocks.length; index++) {
  36805. var block = this.blocks[index];
  36806. block.intersectsRay(ray, this._selectionContent);
  36807. }
  36808. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36809. return this._selectionContent;
  36810. };
  36811. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  36812. target.blocks = new Array();
  36813. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  36814. // Segmenting space
  36815. for (var x = 0; x < 2; x++) {
  36816. for (var y = 0; y < 2; y++) {
  36817. for (var z = 0; z < 2; z++) {
  36818. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  36819. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  36820. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  36821. block.addEntries(entries);
  36822. target.blocks.push(block);
  36823. }
  36824. }
  36825. }
  36826. };
  36827. Octree.CreationFuncForMeshes = function (entry, block) {
  36828. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  36829. block.entries.push(entry);
  36830. }
  36831. };
  36832. Octree.CreationFuncForSubMeshes = function (entry, block) {
  36833. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  36834. block.entries.push(entry);
  36835. }
  36836. };
  36837. return Octree;
  36838. })();
  36839. BABYLON.Octree = Octree;
  36840. })(BABYLON || (BABYLON = {}));
  36841. var BABYLON;
  36842. (function (BABYLON) {
  36843. var OctreeBlock = (function () {
  36844. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  36845. this.entries = new Array();
  36846. this._boundingVectors = new Array();
  36847. this._capacity = capacity;
  36848. this._depth = depth;
  36849. this._maxDepth = maxDepth;
  36850. this._creationFunc = creationFunc;
  36851. this._minPoint = minPoint;
  36852. this._maxPoint = maxPoint;
  36853. this._boundingVectors.push(minPoint.clone());
  36854. this._boundingVectors.push(maxPoint.clone());
  36855. this._boundingVectors.push(minPoint.clone());
  36856. this._boundingVectors[2].x = maxPoint.x;
  36857. this._boundingVectors.push(minPoint.clone());
  36858. this._boundingVectors[3].y = maxPoint.y;
  36859. this._boundingVectors.push(minPoint.clone());
  36860. this._boundingVectors[4].z = maxPoint.z;
  36861. this._boundingVectors.push(maxPoint.clone());
  36862. this._boundingVectors[5].z = minPoint.z;
  36863. this._boundingVectors.push(maxPoint.clone());
  36864. this._boundingVectors[6].x = minPoint.x;
  36865. this._boundingVectors.push(maxPoint.clone());
  36866. this._boundingVectors[7].y = minPoint.y;
  36867. }
  36868. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  36869. // Property
  36870. get: function () {
  36871. return this._capacity;
  36872. },
  36873. enumerable: true,
  36874. configurable: true
  36875. });
  36876. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  36877. get: function () {
  36878. return this._minPoint;
  36879. },
  36880. enumerable: true,
  36881. configurable: true
  36882. });
  36883. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  36884. get: function () {
  36885. return this._maxPoint;
  36886. },
  36887. enumerable: true,
  36888. configurable: true
  36889. });
  36890. // Methods
  36891. OctreeBlock.prototype.addEntry = function (entry) {
  36892. if (this.blocks) {
  36893. for (var index = 0; index < this.blocks.length; index++) {
  36894. var block = this.blocks[index];
  36895. block.addEntry(entry);
  36896. }
  36897. return;
  36898. }
  36899. this._creationFunc(entry, this);
  36900. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  36901. this.createInnerBlocks();
  36902. }
  36903. };
  36904. OctreeBlock.prototype.addEntries = function (entries) {
  36905. for (var index = 0; index < entries.length; index++) {
  36906. var mesh = entries[index];
  36907. this.addEntry(mesh);
  36908. }
  36909. };
  36910. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  36911. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  36912. if (this.blocks) {
  36913. for (var index = 0; index < this.blocks.length; index++) {
  36914. var block = this.blocks[index];
  36915. block.select(frustumPlanes, selection, allowDuplicate);
  36916. }
  36917. return;
  36918. }
  36919. if (allowDuplicate) {
  36920. selection.concat(this.entries);
  36921. }
  36922. else {
  36923. selection.concatWithNoDuplicate(this.entries);
  36924. }
  36925. }
  36926. };
  36927. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  36928. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  36929. if (this.blocks) {
  36930. for (var index = 0; index < this.blocks.length; index++) {
  36931. var block = this.blocks[index];
  36932. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  36933. }
  36934. return;
  36935. }
  36936. if (allowDuplicate) {
  36937. selection.concat(this.entries);
  36938. }
  36939. else {
  36940. selection.concatWithNoDuplicate(this.entries);
  36941. }
  36942. }
  36943. };
  36944. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  36945. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  36946. if (this.blocks) {
  36947. for (var index = 0; index < this.blocks.length; index++) {
  36948. var block = this.blocks[index];
  36949. block.intersectsRay(ray, selection);
  36950. }
  36951. return;
  36952. }
  36953. selection.concatWithNoDuplicate(this.entries);
  36954. }
  36955. };
  36956. OctreeBlock.prototype.createInnerBlocks = function () {
  36957. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  36958. };
  36959. return OctreeBlock;
  36960. })();
  36961. BABYLON.OctreeBlock = OctreeBlock;
  36962. })(BABYLON || (BABYLON = {}));
  36963. var BABYLON;
  36964. (function (BABYLON) {
  36965. var BlurPostProcess = (function (_super) {
  36966. __extends(BlurPostProcess, _super);
  36967. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  36968. var _this = this;
  36969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36970. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  36971. this.direction = direction;
  36972. this.blurWidth = blurWidth;
  36973. this.onApply = function (effect) {
  36974. effect.setFloat2("screenSize", _this.width, _this.height);
  36975. effect.setVector2("direction", _this.direction);
  36976. effect.setFloat("blurWidth", _this.blurWidth);
  36977. };
  36978. }
  36979. return BlurPostProcess;
  36980. })(BABYLON.PostProcess);
  36981. BABYLON.BlurPostProcess = BlurPostProcess;
  36982. })(BABYLON || (BABYLON = {}));
  36983. var BABYLON;
  36984. (function (BABYLON) {
  36985. var RefractionPostProcess = (function (_super) {
  36986. __extends(RefractionPostProcess, _super);
  36987. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  36988. var _this = this;
  36989. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  36990. this.color = color;
  36991. this.depth = depth;
  36992. this.colorLevel = colorLevel;
  36993. this.onActivate = function (cam) {
  36994. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  36995. };
  36996. this.onApply = function (effect) {
  36997. effect.setColor3("baseColor", _this.color);
  36998. effect.setFloat("depth", _this.depth);
  36999. effect.setFloat("colorLevel", _this.colorLevel);
  37000. effect.setTexture("refractionSampler", _this._refRexture);
  37001. };
  37002. }
  37003. // Methods
  37004. RefractionPostProcess.prototype.dispose = function (camera) {
  37005. if (this._refRexture) {
  37006. this._refRexture.dispose();
  37007. }
  37008. _super.prototype.dispose.call(this, camera);
  37009. };
  37010. return RefractionPostProcess;
  37011. })(BABYLON.PostProcess);
  37012. BABYLON.RefractionPostProcess = RefractionPostProcess;
  37013. })(BABYLON || (BABYLON = {}));
  37014. var BABYLON;
  37015. (function (BABYLON) {
  37016. var BlackAndWhitePostProcess = (function (_super) {
  37017. __extends(BlackAndWhitePostProcess, _super);
  37018. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37019. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  37020. }
  37021. return BlackAndWhitePostProcess;
  37022. })(BABYLON.PostProcess);
  37023. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  37024. })(BABYLON || (BABYLON = {}));
  37025. var BABYLON;
  37026. (function (BABYLON) {
  37027. var ConvolutionPostProcess = (function (_super) {
  37028. __extends(ConvolutionPostProcess, _super);
  37029. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  37030. var _this = this;
  37031. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  37032. this.kernel = kernel;
  37033. this.onApply = function (effect) {
  37034. effect.setFloat2("screenSize", _this.width, _this.height);
  37035. effect.setArray("kernel", _this.kernel);
  37036. };
  37037. }
  37038. // Statics
  37039. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  37040. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  37041. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  37042. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  37043. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  37044. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  37045. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  37046. return ConvolutionPostProcess;
  37047. })(BABYLON.PostProcess);
  37048. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  37049. })(BABYLON || (BABYLON = {}));
  37050. var BABYLON;
  37051. (function (BABYLON) {
  37052. var FilterPostProcess = (function (_super) {
  37053. __extends(FilterPostProcess, _super);
  37054. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  37055. var _this = this;
  37056. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  37057. this.kernelMatrix = kernelMatrix;
  37058. this.onApply = function (effect) {
  37059. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  37060. };
  37061. }
  37062. return FilterPostProcess;
  37063. })(BABYLON.PostProcess);
  37064. BABYLON.FilterPostProcess = FilterPostProcess;
  37065. })(BABYLON || (BABYLON = {}));
  37066. var BABYLON;
  37067. (function (BABYLON) {
  37068. var FxaaPostProcess = (function (_super) {
  37069. __extends(FxaaPostProcess, _super);
  37070. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37071. var _this = this;
  37072. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  37073. this.onSizeChanged = function () {
  37074. _this.texelWidth = 1.0 / _this.width;
  37075. _this.texelHeight = 1.0 / _this.height;
  37076. };
  37077. this.onApply = function (effect) {
  37078. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  37079. };
  37080. }
  37081. return FxaaPostProcess;
  37082. })(BABYLON.PostProcess);
  37083. BABYLON.FxaaPostProcess = FxaaPostProcess;
  37084. })(BABYLON || (BABYLON = {}));
  37085. var BABYLON;
  37086. (function (BABYLON) {
  37087. var StereoscopicInterlacePostProcess = (function (_super) {
  37088. __extends(StereoscopicInterlacePostProcess, _super);
  37089. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  37090. var _this = this;
  37091. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  37092. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  37093. this.onSizeChanged = function () {
  37094. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  37095. };
  37096. this.onApply = function (effect) {
  37097. effect.setTextureFromPostProcess("camASampler", postProcessA);
  37098. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  37099. };
  37100. }
  37101. return StereoscopicInterlacePostProcess;
  37102. })(BABYLON.PostProcess);
  37103. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  37104. })(BABYLON || (BABYLON = {}));
  37105. var BABYLON;
  37106. (function (BABYLON) {
  37107. var LensFlare = (function () {
  37108. function LensFlare(size, position, color, imgUrl, system) {
  37109. this.size = size;
  37110. this.position = position;
  37111. this.dispose = function () {
  37112. if (this.texture) {
  37113. this.texture.dispose();
  37114. }
  37115. // Remove from scene
  37116. var index = this._system.lensFlares.indexOf(this);
  37117. this._system.lensFlares.splice(index, 1);
  37118. };
  37119. this.color = color || new BABYLON.Color3(1, 1, 1);
  37120. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  37121. this._system = system;
  37122. system.lensFlares.push(this);
  37123. }
  37124. return LensFlare;
  37125. })();
  37126. BABYLON.LensFlare = LensFlare;
  37127. })(BABYLON || (BABYLON = {}));
  37128. var BABYLON;
  37129. (function (BABYLON) {
  37130. var LensFlareSystem = (function () {
  37131. function LensFlareSystem(name, emitter, scene) {
  37132. this.name = name;
  37133. this.lensFlares = new Array();
  37134. this.borderLimit = 300;
  37135. this.layerMask = 0x0FFFFFFF;
  37136. this._vertexDeclaration = [2];
  37137. this._vertexStrideSize = 2 * 4;
  37138. this._isEnabled = true;
  37139. this._scene = scene;
  37140. this._emitter = emitter;
  37141. scene.lensFlareSystems.push(this);
  37142. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  37143. // VBO
  37144. var vertices = [];
  37145. vertices.push(1, 1);
  37146. vertices.push(-1, 1);
  37147. vertices.push(-1, -1);
  37148. vertices.push(1, -1);
  37149. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  37150. // Indices
  37151. var indices = [];
  37152. indices.push(0);
  37153. indices.push(1);
  37154. indices.push(2);
  37155. indices.push(0);
  37156. indices.push(2);
  37157. indices.push(3);
  37158. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  37159. // Effects
  37160. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  37161. }
  37162. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  37163. get: function () {
  37164. return this._isEnabled;
  37165. },
  37166. set: function (value) {
  37167. this._isEnabled = value;
  37168. },
  37169. enumerable: true,
  37170. configurable: true
  37171. });
  37172. LensFlareSystem.prototype.getScene = function () {
  37173. return this._scene;
  37174. };
  37175. LensFlareSystem.prototype.getEmitter = function () {
  37176. return this._emitter;
  37177. };
  37178. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  37179. this._emitter = newEmitter;
  37180. };
  37181. LensFlareSystem.prototype.getEmitterPosition = function () {
  37182. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  37183. };
  37184. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  37185. var position = this.getEmitterPosition();
  37186. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  37187. this._positionX = position.x;
  37188. this._positionY = position.y;
  37189. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  37190. if (position.z > 0) {
  37191. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  37192. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  37193. return true;
  37194. }
  37195. }
  37196. return false;
  37197. };
  37198. LensFlareSystem.prototype._isVisible = function () {
  37199. if (!this._isEnabled) {
  37200. return false;
  37201. }
  37202. var emitterPosition = this.getEmitterPosition();
  37203. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  37204. var distance = direction.length();
  37205. direction.normalize();
  37206. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  37207. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  37208. return !pickInfo.hit || pickInfo.distance > distance;
  37209. };
  37210. LensFlareSystem.prototype.render = function () {
  37211. if (!this._effect.isReady())
  37212. return false;
  37213. var engine = this._scene.getEngine();
  37214. var viewport = this._scene.activeCamera.viewport;
  37215. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  37216. // Position
  37217. if (!this.computeEffectivePosition(globalViewport)) {
  37218. return false;
  37219. }
  37220. // Visibility
  37221. if (!this._isVisible()) {
  37222. return false;
  37223. }
  37224. // Intensity
  37225. var awayX;
  37226. var awayY;
  37227. if (this._positionX < this.borderLimit + globalViewport.x) {
  37228. awayX = this.borderLimit + globalViewport.x - this._positionX;
  37229. }
  37230. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  37231. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  37232. }
  37233. else {
  37234. awayX = 0;
  37235. }
  37236. if (this._positionY < this.borderLimit + globalViewport.y) {
  37237. awayY = this.borderLimit + globalViewport.y - this._positionY;
  37238. }
  37239. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  37240. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  37241. }
  37242. else {
  37243. awayY = 0;
  37244. }
  37245. var away = (awayX > awayY) ? awayX : awayY;
  37246. if (away > this.borderLimit) {
  37247. away = this.borderLimit;
  37248. }
  37249. var intensity = 1.0 - (away / this.borderLimit);
  37250. if (intensity < 0) {
  37251. return false;
  37252. }
  37253. if (intensity > 1.0) {
  37254. intensity = 1.0;
  37255. }
  37256. // Position
  37257. var centerX = globalViewport.x + globalViewport.width / 2;
  37258. var centerY = globalViewport.y + globalViewport.height / 2;
  37259. var distX = centerX - this._positionX;
  37260. var distY = centerY - this._positionY;
  37261. // Effects
  37262. engine.enableEffect(this._effect);
  37263. engine.setState(false);
  37264. engine.setDepthBuffer(false);
  37265. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  37266. // VBOs
  37267. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  37268. // Flares
  37269. for (var index = 0; index < this.lensFlares.length; index++) {
  37270. var flare = this.lensFlares[index];
  37271. var x = centerX - (distX * flare.position);
  37272. var y = centerY - (distY * flare.position);
  37273. var cw = flare.size;
  37274. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  37275. var cx = 2 * (x / globalViewport.width) - 1.0;
  37276. var cy = 1.0 - 2 * (y / globalViewport.height);
  37277. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  37278. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  37279. // Texture
  37280. this._effect.setTexture("textureSampler", flare.texture);
  37281. // Color
  37282. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  37283. // Draw order
  37284. engine.draw(true, 0, 6);
  37285. }
  37286. engine.setDepthBuffer(true);
  37287. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37288. return true;
  37289. };
  37290. LensFlareSystem.prototype.dispose = function () {
  37291. if (this._vertexBuffer) {
  37292. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  37293. this._vertexBuffer = null;
  37294. }
  37295. if (this._indexBuffer) {
  37296. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37297. this._indexBuffer = null;
  37298. }
  37299. while (this.lensFlares.length) {
  37300. this.lensFlares[0].dispose();
  37301. }
  37302. // Remove from scene
  37303. var index = this._scene.lensFlareSystems.indexOf(this);
  37304. this._scene.lensFlareSystems.splice(index, 1);
  37305. };
  37306. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  37307. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  37308. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  37309. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  37310. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  37311. var parsedFlare = parsedLensFlareSystem.flares[index];
  37312. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  37313. }
  37314. return lensFlareSystem;
  37315. };
  37316. LensFlareSystem.prototype.serialize = function () {
  37317. var serializationObject = {};
  37318. serializationObject.emitterId = this.getEmitter().id;
  37319. serializationObject.borderLimit = this.borderLimit;
  37320. serializationObject.flares = [];
  37321. for (var index = 0; index < this.lensFlares.length; index++) {
  37322. var flare = this.lensFlares[index];
  37323. serializationObject.flares.push({
  37324. size: flare.size,
  37325. position: flare.position,
  37326. color: flare.color.asArray(),
  37327. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  37328. });
  37329. }
  37330. return serializationObject;
  37331. };
  37332. return LensFlareSystem;
  37333. })();
  37334. BABYLON.LensFlareSystem = LensFlareSystem;
  37335. })(BABYLON || (BABYLON = {}));
  37336. var BABYLON;
  37337. (function (BABYLON) {
  37338. // We're mainly based on the logic defined into the FreeCamera code
  37339. var DeviceOrientationCamera = (function (_super) {
  37340. __extends(DeviceOrientationCamera, _super);
  37341. //-- end properties for backward compatibility for inputs
  37342. function DeviceOrientationCamera(name, position, scene) {
  37343. _super.call(this, name, position, scene);
  37344. this.inputs.addDeviceOrientation();
  37345. }
  37346. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  37347. //-- Begin properties for backward compatibility for inputs
  37348. get: function () {
  37349. var gamepad = this.inputs.attached["deviceOrientation"];
  37350. if (gamepad)
  37351. return gamepad.angularSensibility;
  37352. },
  37353. set: function (value) {
  37354. var gamepad = this.inputs.attached["deviceOrientation"];
  37355. if (gamepad)
  37356. gamepad.angularSensibility = value;
  37357. },
  37358. enumerable: true,
  37359. configurable: true
  37360. });
  37361. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  37362. get: function () {
  37363. var gamepad = this.inputs.attached["deviceOrientation"];
  37364. if (gamepad)
  37365. return gamepad.moveSensibility;
  37366. },
  37367. set: function (value) {
  37368. var gamepad = this.inputs.attached["deviceOrientation"];
  37369. if (gamepad)
  37370. gamepad.moveSensibility = value;
  37371. },
  37372. enumerable: true,
  37373. configurable: true
  37374. });
  37375. DeviceOrientationCamera.prototype.getTypeName = function () {
  37376. return "DeviceOrientationCamera";
  37377. };
  37378. return DeviceOrientationCamera;
  37379. })(BABYLON.FreeCamera);
  37380. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  37381. })(BABYLON || (BABYLON = {}));
  37382. var BABYLON;
  37383. (function (BABYLON) {
  37384. // We're mainly based on the logic defined into the FreeCamera code
  37385. var UniversalCamera = (function (_super) {
  37386. __extends(UniversalCamera, _super);
  37387. //-- end properties for backward compatibility for inputs
  37388. function UniversalCamera(name, position, scene) {
  37389. _super.call(this, name, position, scene);
  37390. this.inputs.addGamepad();
  37391. }
  37392. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  37393. //-- Begin properties for backward compatibility for inputs
  37394. get: function () {
  37395. var gamepad = this.inputs.attached["gamepad"];
  37396. if (gamepad)
  37397. return gamepad.gamepadAngularSensibility;
  37398. },
  37399. set: function (value) {
  37400. var gamepad = this.inputs.attached["gamepad"];
  37401. if (gamepad)
  37402. gamepad.gamepadAngularSensibility = value;
  37403. },
  37404. enumerable: true,
  37405. configurable: true
  37406. });
  37407. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  37408. get: function () {
  37409. var gamepad = this.inputs.attached["gamepad"];
  37410. if (gamepad)
  37411. return gamepad.gamepadMoveSensibility;
  37412. },
  37413. set: function (value) {
  37414. var gamepad = this.inputs.attached["gamepad"];
  37415. if (gamepad)
  37416. gamepad.gamepadMoveSensibility = value;
  37417. },
  37418. enumerable: true,
  37419. configurable: true
  37420. });
  37421. UniversalCamera.prototype.getTypeName = function () {
  37422. return "UniversalCamera";
  37423. };
  37424. return UniversalCamera;
  37425. })(BABYLON.TouchCamera);
  37426. BABYLON.UniversalCamera = UniversalCamera;
  37427. })(BABYLON || (BABYLON = {}));
  37428. var BABYLON;
  37429. (function (BABYLON) {
  37430. var Gamepads = (function () {
  37431. function Gamepads(ongamedpadconnected) {
  37432. var _this = this;
  37433. this.babylonGamepads = [];
  37434. this.oneGamepadConnected = false;
  37435. this.isMonitoring = false;
  37436. this.gamepadEventSupported = 'GamepadEvent' in window;
  37437. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37438. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37439. this._callbackGamepadConnected = ongamedpadconnected;
  37440. if (this.gamepadSupportAvailable) {
  37441. // Checking if the gamepad connected event is supported (like in Firefox)
  37442. if (this.gamepadEventSupported) {
  37443. this._onGamepadConnectedEvent = function (evt) {
  37444. _this._onGamepadConnected(evt);
  37445. };
  37446. this._onGamepadDisonnectedEvent = function (evt) {
  37447. _this._onGamepadDisconnected(evt);
  37448. };
  37449. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  37450. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  37451. }
  37452. else {
  37453. this._startMonitoringGamepads();
  37454. }
  37455. }
  37456. }
  37457. Gamepads.prototype.dispose = function () {
  37458. if (Gamepads.gamepadDOMInfo) {
  37459. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37460. }
  37461. if (this._onGamepadConnectedEvent) {
  37462. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  37463. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  37464. this._onGamepadConnectedEvent = null;
  37465. this._onGamepadDisonnectedEvent = null;
  37466. }
  37467. };
  37468. Gamepads.prototype._onGamepadConnected = function (evt) {
  37469. var newGamepad = this._addNewGamepad(evt.gamepad);
  37470. if (this._callbackGamepadConnected)
  37471. this._callbackGamepadConnected(newGamepad);
  37472. this._startMonitoringGamepads();
  37473. };
  37474. Gamepads.prototype._addNewGamepad = function (gamepad) {
  37475. if (!this.oneGamepadConnected) {
  37476. this.oneGamepadConnected = true;
  37477. if (Gamepads.gamepadDOMInfo) {
  37478. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37479. Gamepads.gamepadDOMInfo = null;
  37480. }
  37481. }
  37482. var newGamepad;
  37483. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  37484. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  37485. }
  37486. else {
  37487. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  37488. }
  37489. this.babylonGamepads.push(newGamepad);
  37490. return newGamepad;
  37491. };
  37492. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  37493. // Remove the gamepad from the list of gamepads to monitor.
  37494. for (var i in this.babylonGamepads) {
  37495. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  37496. this.babylonGamepads.splice(+i, 1);
  37497. break;
  37498. }
  37499. }
  37500. // If no gamepads are left, stop the polling loop.
  37501. if (this.babylonGamepads.length == 0) {
  37502. this._stopMonitoringGamepads();
  37503. }
  37504. };
  37505. Gamepads.prototype._startMonitoringGamepads = function () {
  37506. if (!this.isMonitoring) {
  37507. this.isMonitoring = true;
  37508. this._checkGamepadsStatus();
  37509. }
  37510. };
  37511. Gamepads.prototype._stopMonitoringGamepads = function () {
  37512. this.isMonitoring = false;
  37513. };
  37514. Gamepads.prototype._checkGamepadsStatus = function () {
  37515. var _this = this;
  37516. // updating gamepad objects
  37517. this._updateGamepadObjects();
  37518. for (var i in this.babylonGamepads) {
  37519. this.babylonGamepads[i].update();
  37520. }
  37521. if (this.isMonitoring) {
  37522. if (window.requestAnimationFrame) {
  37523. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37524. }
  37525. else if (window.mozRequestAnimationFrame) {
  37526. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37527. }
  37528. else if (window.webkitRequestAnimationFrame) {
  37529. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37530. }
  37531. }
  37532. };
  37533. // This function is called only on Chrome, which does not yet support
  37534. // connection/disconnection events, but requires you to monitor
  37535. // an array for changes.
  37536. Gamepads.prototype._updateGamepadObjects = function () {
  37537. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  37538. for (var i = 0; i < gamepads.length; i++) {
  37539. if (gamepads[i]) {
  37540. if (!(gamepads[i].index in this.babylonGamepads)) {
  37541. var newGamepad = this._addNewGamepad(gamepads[i]);
  37542. if (this._callbackGamepadConnected) {
  37543. this._callbackGamepadConnected(newGamepad);
  37544. }
  37545. }
  37546. else {
  37547. this.babylonGamepads[i].browserGamepad = gamepads[i];
  37548. }
  37549. }
  37550. }
  37551. };
  37552. return Gamepads;
  37553. })();
  37554. BABYLON.Gamepads = Gamepads;
  37555. var StickValues = (function () {
  37556. function StickValues(x, y) {
  37557. this.x = x;
  37558. this.y = y;
  37559. }
  37560. return StickValues;
  37561. })();
  37562. BABYLON.StickValues = StickValues;
  37563. var Gamepad = (function () {
  37564. function Gamepad(id, index, browserGamepad) {
  37565. this.id = id;
  37566. this.index = index;
  37567. this.browserGamepad = browserGamepad;
  37568. if (this.browserGamepad.axes.length >= 2) {
  37569. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37570. }
  37571. if (this.browserGamepad.axes.length >= 4) {
  37572. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37573. }
  37574. }
  37575. Gamepad.prototype.onleftstickchanged = function (callback) {
  37576. this._onleftstickchanged = callback;
  37577. };
  37578. Gamepad.prototype.onrightstickchanged = function (callback) {
  37579. this._onrightstickchanged = callback;
  37580. };
  37581. Object.defineProperty(Gamepad.prototype, "leftStick", {
  37582. get: function () {
  37583. return this._leftStick;
  37584. },
  37585. set: function (newValues) {
  37586. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  37587. this._onleftstickchanged(newValues);
  37588. }
  37589. this._leftStick = newValues;
  37590. },
  37591. enumerable: true,
  37592. configurable: true
  37593. });
  37594. Object.defineProperty(Gamepad.prototype, "rightStick", {
  37595. get: function () {
  37596. return this._rightStick;
  37597. },
  37598. set: function (newValues) {
  37599. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  37600. this._onrightstickchanged(newValues);
  37601. }
  37602. this._rightStick = newValues;
  37603. },
  37604. enumerable: true,
  37605. configurable: true
  37606. });
  37607. Gamepad.prototype.update = function () {
  37608. if (this._leftStick) {
  37609. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37610. }
  37611. if (this._rightStick) {
  37612. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37613. }
  37614. };
  37615. return Gamepad;
  37616. })();
  37617. BABYLON.Gamepad = Gamepad;
  37618. var GenericPad = (function (_super) {
  37619. __extends(GenericPad, _super);
  37620. function GenericPad(id, index, gamepad) {
  37621. _super.call(this, id, index, gamepad);
  37622. this.id = id;
  37623. this.index = index;
  37624. this.gamepad = gamepad;
  37625. this._buttons = new Array(gamepad.buttons.length);
  37626. }
  37627. GenericPad.prototype.onbuttondown = function (callback) {
  37628. this._onbuttondown = callback;
  37629. };
  37630. GenericPad.prototype.onbuttonup = function (callback) {
  37631. this._onbuttonup = callback;
  37632. };
  37633. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  37634. if (newValue !== currentValue) {
  37635. if (this._onbuttondown && newValue === 1) {
  37636. this._onbuttondown(buttonIndex);
  37637. }
  37638. if (this._onbuttonup && newValue === 0) {
  37639. this._onbuttonup(buttonIndex);
  37640. }
  37641. }
  37642. return newValue;
  37643. };
  37644. GenericPad.prototype.update = function () {
  37645. _super.prototype.update.call(this);
  37646. for (var index = 0; index < this._buttons.length; index++) {
  37647. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  37648. }
  37649. };
  37650. return GenericPad;
  37651. })(Gamepad);
  37652. BABYLON.GenericPad = GenericPad;
  37653. (function (Xbox360Button) {
  37654. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  37655. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  37656. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  37657. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  37658. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  37659. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  37660. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  37661. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  37662. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  37663. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  37664. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  37665. var Xbox360Button = BABYLON.Xbox360Button;
  37666. (function (Xbox360Dpad) {
  37667. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  37668. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  37669. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  37670. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  37671. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  37672. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  37673. var Xbox360Pad = (function (_super) {
  37674. __extends(Xbox360Pad, _super);
  37675. function Xbox360Pad() {
  37676. _super.apply(this, arguments);
  37677. this._leftTrigger = 0;
  37678. this._rightTrigger = 0;
  37679. this._buttonA = 0;
  37680. this._buttonB = 0;
  37681. this._buttonX = 0;
  37682. this._buttonY = 0;
  37683. this._buttonBack = 0;
  37684. this._buttonStart = 0;
  37685. this._buttonLB = 0;
  37686. this._buttonRB = 0;
  37687. this._buttonLeftStick = 0;
  37688. this._buttonRightStick = 0;
  37689. this._dPadUp = 0;
  37690. this._dPadDown = 0;
  37691. this._dPadLeft = 0;
  37692. this._dPadRight = 0;
  37693. }
  37694. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  37695. this._onlefttriggerchanged = callback;
  37696. };
  37697. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  37698. this._onrighttriggerchanged = callback;
  37699. };
  37700. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  37701. get: function () {
  37702. return this._leftTrigger;
  37703. },
  37704. set: function (newValue) {
  37705. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  37706. this._onlefttriggerchanged(newValue);
  37707. }
  37708. this._leftTrigger = newValue;
  37709. },
  37710. enumerable: true,
  37711. configurable: true
  37712. });
  37713. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  37714. get: function () {
  37715. return this._rightTrigger;
  37716. },
  37717. set: function (newValue) {
  37718. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  37719. this._onrighttriggerchanged(newValue);
  37720. }
  37721. this._rightTrigger = newValue;
  37722. },
  37723. enumerable: true,
  37724. configurable: true
  37725. });
  37726. Xbox360Pad.prototype.onbuttondown = function (callback) {
  37727. this._onbuttondown = callback;
  37728. };
  37729. Xbox360Pad.prototype.onbuttonup = function (callback) {
  37730. this._onbuttonup = callback;
  37731. };
  37732. Xbox360Pad.prototype.ondpaddown = function (callback) {
  37733. this._ondpaddown = callback;
  37734. };
  37735. Xbox360Pad.prototype.ondpadup = function (callback) {
  37736. this._ondpadup = callback;
  37737. };
  37738. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  37739. if (newValue !== currentValue) {
  37740. if (this._onbuttondown && newValue === 1) {
  37741. this._onbuttondown(buttonType);
  37742. }
  37743. if (this._onbuttonup && newValue === 0) {
  37744. this._onbuttonup(buttonType);
  37745. }
  37746. }
  37747. return newValue;
  37748. };
  37749. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  37750. if (newValue !== currentValue) {
  37751. if (this._ondpaddown && newValue === 1) {
  37752. this._ondpaddown(buttonType);
  37753. }
  37754. if (this._ondpadup && newValue === 0) {
  37755. this._ondpadup(buttonType);
  37756. }
  37757. }
  37758. return newValue;
  37759. };
  37760. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  37761. get: function () {
  37762. return this._buttonA;
  37763. },
  37764. set: function (value) {
  37765. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  37766. },
  37767. enumerable: true,
  37768. configurable: true
  37769. });
  37770. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  37771. get: function () {
  37772. return this._buttonB;
  37773. },
  37774. set: function (value) {
  37775. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  37776. },
  37777. enumerable: true,
  37778. configurable: true
  37779. });
  37780. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  37781. get: function () {
  37782. return this._buttonX;
  37783. },
  37784. set: function (value) {
  37785. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  37786. },
  37787. enumerable: true,
  37788. configurable: true
  37789. });
  37790. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  37791. get: function () {
  37792. return this._buttonY;
  37793. },
  37794. set: function (value) {
  37795. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  37796. },
  37797. enumerable: true,
  37798. configurable: true
  37799. });
  37800. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  37801. get: function () {
  37802. return this._buttonStart;
  37803. },
  37804. set: function (value) {
  37805. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  37806. },
  37807. enumerable: true,
  37808. configurable: true
  37809. });
  37810. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  37811. get: function () {
  37812. return this._buttonBack;
  37813. },
  37814. set: function (value) {
  37815. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  37816. },
  37817. enumerable: true,
  37818. configurable: true
  37819. });
  37820. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  37821. get: function () {
  37822. return this._buttonLB;
  37823. },
  37824. set: function (value) {
  37825. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  37826. },
  37827. enumerable: true,
  37828. configurable: true
  37829. });
  37830. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  37831. get: function () {
  37832. return this._buttonRB;
  37833. },
  37834. set: function (value) {
  37835. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  37836. },
  37837. enumerable: true,
  37838. configurable: true
  37839. });
  37840. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  37841. get: function () {
  37842. return this._buttonLeftStick;
  37843. },
  37844. set: function (value) {
  37845. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  37846. },
  37847. enumerable: true,
  37848. configurable: true
  37849. });
  37850. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  37851. get: function () {
  37852. return this._buttonRightStick;
  37853. },
  37854. set: function (value) {
  37855. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  37856. },
  37857. enumerable: true,
  37858. configurable: true
  37859. });
  37860. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  37861. get: function () {
  37862. return this._dPadUp;
  37863. },
  37864. set: function (value) {
  37865. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  37866. },
  37867. enumerable: true,
  37868. configurable: true
  37869. });
  37870. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  37871. get: function () {
  37872. return this._dPadDown;
  37873. },
  37874. set: function (value) {
  37875. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  37876. },
  37877. enumerable: true,
  37878. configurable: true
  37879. });
  37880. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  37881. get: function () {
  37882. return this._dPadLeft;
  37883. },
  37884. set: function (value) {
  37885. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  37886. },
  37887. enumerable: true,
  37888. configurable: true
  37889. });
  37890. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  37891. get: function () {
  37892. return this._dPadRight;
  37893. },
  37894. set: function (value) {
  37895. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  37896. },
  37897. enumerable: true,
  37898. configurable: true
  37899. });
  37900. Xbox360Pad.prototype.update = function () {
  37901. _super.prototype.update.call(this);
  37902. this.buttonA = this.browserGamepad.buttons[0].value;
  37903. this.buttonB = this.browserGamepad.buttons[1].value;
  37904. this.buttonX = this.browserGamepad.buttons[2].value;
  37905. this.buttonY = this.browserGamepad.buttons[3].value;
  37906. this.buttonLB = this.browserGamepad.buttons[4].value;
  37907. this.buttonRB = this.browserGamepad.buttons[5].value;
  37908. this.leftTrigger = this.browserGamepad.buttons[6].value;
  37909. this.rightTrigger = this.browserGamepad.buttons[7].value;
  37910. this.buttonBack = this.browserGamepad.buttons[8].value;
  37911. this.buttonStart = this.browserGamepad.buttons[9].value;
  37912. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  37913. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  37914. this.dPadUp = this.browserGamepad.buttons[12].value;
  37915. this.dPadDown = this.browserGamepad.buttons[13].value;
  37916. this.dPadLeft = this.browserGamepad.buttons[14].value;
  37917. this.dPadRight = this.browserGamepad.buttons[15].value;
  37918. };
  37919. return Xbox360Pad;
  37920. })(Gamepad);
  37921. BABYLON.Xbox360Pad = Xbox360Pad;
  37922. })(BABYLON || (BABYLON = {}));
  37923. var BABYLON;
  37924. (function (BABYLON) {
  37925. // We're mainly based on the logic defined into the FreeCamera code
  37926. var GamepadCamera = (function (_super) {
  37927. __extends(GamepadCamera, _super);
  37928. //-- end properties for backward compatibility for inputs
  37929. function GamepadCamera(name, position, scene) {
  37930. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  37931. _super.call(this, name, position, scene);
  37932. }
  37933. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  37934. //-- Begin properties for backward compatibility for inputs
  37935. get: function () {
  37936. var gamepad = this.inputs.attached["gamepad"];
  37937. if (gamepad)
  37938. return gamepad.gamepadAngularSensibility;
  37939. },
  37940. set: function (value) {
  37941. var gamepad = this.inputs.attached["gamepad"];
  37942. if (gamepad)
  37943. gamepad.gamepadAngularSensibility = value;
  37944. },
  37945. enumerable: true,
  37946. configurable: true
  37947. });
  37948. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  37949. get: function () {
  37950. var gamepad = this.inputs.attached["gamepad"];
  37951. if (gamepad)
  37952. return gamepad.gamepadMoveSensibility;
  37953. },
  37954. set: function (value) {
  37955. var gamepad = this.inputs.attached["gamepad"];
  37956. if (gamepad)
  37957. gamepad.gamepadMoveSensibility = value;
  37958. },
  37959. enumerable: true,
  37960. configurable: true
  37961. });
  37962. GamepadCamera.prototype.getTypeName = function () {
  37963. return "GamepadCamera";
  37964. };
  37965. return GamepadCamera;
  37966. })(BABYLON.UniversalCamera);
  37967. BABYLON.GamepadCamera = GamepadCamera;
  37968. })(BABYLON || (BABYLON = {}));
  37969. var BABYLON;
  37970. (function (BABYLON) {
  37971. var Analyser = (function () {
  37972. function Analyser(scene) {
  37973. this.SMOOTHING = 0.75;
  37974. this.FFT_SIZE = 512;
  37975. this.BARGRAPHAMPLITUDE = 256;
  37976. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  37977. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  37978. this._scene = scene;
  37979. this._audioEngine = BABYLON.Engine.audioEngine;
  37980. if (this._audioEngine.canUseWebAudio) {
  37981. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  37982. this._webAudioAnalyser.minDecibels = -140;
  37983. this._webAudioAnalyser.maxDecibels = 0;
  37984. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  37985. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  37986. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  37987. }
  37988. }
  37989. Analyser.prototype.getFrequencyBinCount = function () {
  37990. if (this._audioEngine.canUseWebAudio) {
  37991. return this._webAudioAnalyser.frequencyBinCount;
  37992. }
  37993. else {
  37994. return 0;
  37995. }
  37996. };
  37997. Analyser.prototype.getByteFrequencyData = function () {
  37998. if (this._audioEngine.canUseWebAudio) {
  37999. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38000. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38001. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  38002. }
  38003. return this._byteFreqs;
  38004. };
  38005. Analyser.prototype.getByteTimeDomainData = function () {
  38006. if (this._audioEngine.canUseWebAudio) {
  38007. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38008. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38009. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  38010. }
  38011. return this._byteTime;
  38012. };
  38013. Analyser.prototype.getFloatFrequencyData = function () {
  38014. if (this._audioEngine.canUseWebAudio) {
  38015. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38016. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38017. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  38018. }
  38019. return this._floatFreqs;
  38020. };
  38021. Analyser.prototype.drawDebugCanvas = function () {
  38022. var _this = this;
  38023. if (this._audioEngine.canUseWebAudio) {
  38024. if (!this._debugCanvas) {
  38025. this._debugCanvas = document.createElement("canvas");
  38026. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  38027. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  38028. this._debugCanvas.style.position = "absolute";
  38029. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  38030. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  38031. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  38032. document.body.appendChild(this._debugCanvas);
  38033. this._registerFunc = function () {
  38034. _this.drawDebugCanvas();
  38035. };
  38036. this._scene.registerBeforeRender(this._registerFunc);
  38037. }
  38038. if (this._registerFunc) {
  38039. var workingArray = this.getByteFrequencyData();
  38040. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  38041. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  38042. // Draw the frequency domain chart.
  38043. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  38044. var value = workingArray[i];
  38045. var percent = value / this.BARGRAPHAMPLITUDE;
  38046. var height = this.DEBUGCANVASSIZE.height * percent;
  38047. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  38048. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  38049. var hue = i / this.getFrequencyBinCount() * 360;
  38050. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  38051. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  38052. }
  38053. }
  38054. }
  38055. };
  38056. Analyser.prototype.stopDebugCanvas = function () {
  38057. if (this._debugCanvas) {
  38058. this._scene.unregisterBeforeRender(this._registerFunc);
  38059. this._registerFunc = null;
  38060. document.body.removeChild(this._debugCanvas);
  38061. this._debugCanvas = null;
  38062. this._debugCanvasContext = null;
  38063. }
  38064. };
  38065. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  38066. if (this._audioEngine.canUseWebAudio) {
  38067. inputAudioNode.connect(this._webAudioAnalyser);
  38068. this._webAudioAnalyser.connect(outputAudioNode);
  38069. }
  38070. };
  38071. Analyser.prototype.dispose = function () {
  38072. if (this._audioEngine.canUseWebAudio) {
  38073. this._webAudioAnalyser.disconnect();
  38074. }
  38075. };
  38076. return Analyser;
  38077. })();
  38078. BABYLON.Analyser = Analyser;
  38079. })(BABYLON || (BABYLON = {}));
  38080. var BABYLON;
  38081. (function (BABYLON) {
  38082. var DepthRenderer = (function () {
  38083. function DepthRenderer(scene, type) {
  38084. var _this = this;
  38085. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  38086. this._viewMatrix = BABYLON.Matrix.Zero();
  38087. this._projectionMatrix = BABYLON.Matrix.Zero();
  38088. this._transformMatrix = BABYLON.Matrix.Zero();
  38089. this._worldViewProjection = BABYLON.Matrix.Zero();
  38090. this._scene = scene;
  38091. var engine = scene.getEngine();
  38092. // Render target
  38093. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  38094. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38095. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38096. this._depthMap.refreshRate = 1;
  38097. this._depthMap.renderParticles = false;
  38098. this._depthMap.renderList = null;
  38099. // set default depth value to 1.0 (far away)
  38100. this._depthMap.onClear = function (engine) {
  38101. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  38102. };
  38103. // Custom render function
  38104. var renderSubMesh = function (subMesh) {
  38105. var mesh = subMesh.getRenderingMesh();
  38106. var scene = _this._scene;
  38107. var engine = scene.getEngine();
  38108. // Culling
  38109. engine.setState(subMesh.getMaterial().backFaceCulling);
  38110. // Managing instances
  38111. var batch = mesh._getInstancesRenderList(subMesh._id);
  38112. if (batch.mustReturn) {
  38113. return;
  38114. }
  38115. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  38116. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  38117. engine.enableEffect(_this._effect);
  38118. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  38119. var material = subMesh.getMaterial();
  38120. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  38121. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  38122. // Alpha test
  38123. if (material && material.needAlphaTesting()) {
  38124. var alphaTexture = material.getAlphaTestTexture();
  38125. _this._effect.setTexture("diffuseSampler", alphaTexture);
  38126. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38127. }
  38128. // Bones
  38129. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38130. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38131. }
  38132. // Draw
  38133. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  38134. }
  38135. };
  38136. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  38137. var index;
  38138. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38139. renderSubMesh(opaqueSubMeshes.data[index]);
  38140. }
  38141. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38142. renderSubMesh(alphaTestSubMeshes.data[index]);
  38143. }
  38144. };
  38145. }
  38146. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  38147. var defines = [];
  38148. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38149. var mesh = subMesh.getMesh();
  38150. var scene = mesh.getScene();
  38151. var material = subMesh.getMaterial();
  38152. // Alpha test
  38153. if (material && material.needAlphaTesting()) {
  38154. defines.push("#define ALPHATEST");
  38155. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38156. attribs.push(BABYLON.VertexBuffer.UVKind);
  38157. defines.push("#define UV1");
  38158. }
  38159. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38160. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38161. defines.push("#define UV2");
  38162. }
  38163. }
  38164. // Bones
  38165. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38166. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38167. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38168. if (mesh.numBoneInfluencers > 4) {
  38169. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38170. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38171. }
  38172. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38173. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38174. }
  38175. else {
  38176. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38177. }
  38178. // Instances
  38179. if (useInstances) {
  38180. defines.push("#define INSTANCES");
  38181. attribs.push("world0");
  38182. attribs.push("world1");
  38183. attribs.push("world2");
  38184. attribs.push("world3");
  38185. }
  38186. // Get correct effect
  38187. var join = defines.join("\n");
  38188. if (this._cachedDefines !== join) {
  38189. this._cachedDefines = join;
  38190. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  38191. }
  38192. return this._effect.isReady();
  38193. };
  38194. DepthRenderer.prototype.getDepthMap = function () {
  38195. return this._depthMap;
  38196. };
  38197. // Methods
  38198. DepthRenderer.prototype.dispose = function () {
  38199. this._depthMap.dispose();
  38200. };
  38201. return DepthRenderer;
  38202. })();
  38203. BABYLON.DepthRenderer = DepthRenderer;
  38204. })(BABYLON || (BABYLON = {}));
  38205. var BABYLON;
  38206. (function (BABYLON) {
  38207. var SSAORenderingPipeline = (function (_super) {
  38208. __extends(SSAORenderingPipeline, _super);
  38209. /**
  38210. * @constructor
  38211. * @param {string} name - The rendering pipeline name
  38212. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  38213. * @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 }
  38214. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  38215. */
  38216. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  38217. var _this = this;
  38218. _super.call(this, scene.getEngine(), name);
  38219. // Members
  38220. /**
  38221. * The PassPostProcess id in the pipeline that contains the original scene color
  38222. * @type {string}
  38223. */
  38224. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  38225. /**
  38226. * The SSAO PostProcess id in the pipeline
  38227. * @type {string}
  38228. */
  38229. this.SSAORenderEffect = "SSAORenderEffect";
  38230. /**
  38231. * The horizontal blur PostProcess id in the pipeline
  38232. * @type {string}
  38233. */
  38234. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  38235. /**
  38236. * The vertical blur PostProcess id in the pipeline
  38237. * @type {string}
  38238. */
  38239. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  38240. /**
  38241. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  38242. * @type {string}
  38243. */
  38244. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  38245. /**
  38246. * The output strength of the SSAO post-process. Default value is 1.0.
  38247. * @type {number}
  38248. */
  38249. this.totalStrength = 1.0;
  38250. /**
  38251. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  38252. * @type {number}
  38253. */
  38254. this.radius = 0.0001;
  38255. /**
  38256. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  38257. * Must not be equal to fallOff and superior to fallOff.
  38258. * Default value is 0.975
  38259. * @type {number}
  38260. */
  38261. this.area = 0.0075;
  38262. /**
  38263. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  38264. * Must not be equal to area and inferior to area.
  38265. * Default value is 0.0
  38266. * @type {number}
  38267. */
  38268. this.fallOff = 0.000001;
  38269. /**
  38270. * The base color of the SSAO post-process
  38271. * The final result is "base + ssao" between [0, 1]
  38272. * @type {number}
  38273. */
  38274. this.base = 0.5;
  38275. this._firstUpdate = true;
  38276. this._scene = scene;
  38277. // Set up assets
  38278. this._createRandomTexture();
  38279. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  38280. var ssaoRatio = ratio.ssaoRatio || ratio;
  38281. var combineRatio = ratio.combineRatio || ratio;
  38282. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38283. this._createSSAOPostProcess(ssaoRatio);
  38284. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38285. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38286. this._createSSAOCombinePostProcess(combineRatio);
  38287. // Set up pipeline
  38288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  38289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  38290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  38291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  38292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  38293. // Finish
  38294. scene.postProcessRenderPipelineManager.addPipeline(this);
  38295. if (cameras)
  38296. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38297. }
  38298. // Public Methods
  38299. /**
  38300. * Returns the horizontal blur PostProcess
  38301. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  38302. */
  38303. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  38304. return this._blurHPostProcess;
  38305. };
  38306. /**
  38307. * Returns the vertical blur PostProcess
  38308. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  38309. */
  38310. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  38311. return this._blurVPostProcess;
  38312. };
  38313. /**
  38314. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  38315. */
  38316. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  38317. if (disableDepthRender === void 0) { disableDepthRender = false; }
  38318. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38319. this._originalColorPostProcess = undefined;
  38320. this._ssaoPostProcess = undefined;
  38321. this._blurHPostProcess = undefined;
  38322. this._blurVPostProcess = undefined;
  38323. this._ssaoCombinePostProcess = undefined;
  38324. this._randomTexture.dispose();
  38325. if (disableDepthRender)
  38326. this._scene.disableDepthRenderer();
  38327. };
  38328. // Private Methods
  38329. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  38330. var _this = this;
  38331. var numSamples = 16;
  38332. var sampleSphere = [
  38333. 0.5381, 0.1856, -0.4319,
  38334. 0.1379, 0.2486, 0.4430,
  38335. 0.3371, 0.5679, -0.0057,
  38336. -0.6999, -0.0451, -0.0019,
  38337. 0.0689, -0.1598, -0.8547,
  38338. 0.0560, 0.0069, -0.1843,
  38339. -0.0146, 0.1402, 0.0762,
  38340. 0.0100, -0.1924, -0.0344,
  38341. -0.3577, -0.5301, -0.4358,
  38342. -0.3169, 0.1063, 0.0158,
  38343. 0.0103, -0.5869, 0.0046,
  38344. -0.0897, -0.4940, 0.3287,
  38345. 0.7119, -0.0154, -0.0918,
  38346. -0.0533, 0.0596, -0.5411,
  38347. 0.0352, -0.0631, 0.5460,
  38348. -0.4776, 0.2847, -0.0271
  38349. ];
  38350. var samplesFactor = 1.0 / numSamples;
  38351. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  38352. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  38353. "area", "fallOff", "base"
  38354. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  38355. this._ssaoPostProcess.onApply = function (effect) {
  38356. if (_this._firstUpdate) {
  38357. effect.setArray3("sampleSphere", sampleSphere);
  38358. effect.setFloat("samplesFactor", samplesFactor);
  38359. effect.setFloat("randTextureTiles", 4.0);
  38360. _this._firstUpdate = false;
  38361. }
  38362. effect.setFloat("totalStrength", _this.totalStrength);
  38363. effect.setFloat("radius", _this.radius);
  38364. effect.setFloat("area", _this.area);
  38365. effect.setFloat("fallOff", _this.fallOff);
  38366. effect.setFloat("base", _this.base);
  38367. effect.setTexture("textureSampler", _this._depthTexture);
  38368. effect.setTexture("randomSampler", _this._randomTexture);
  38369. };
  38370. };
  38371. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  38372. var _this = this;
  38373. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38374. this._ssaoCombinePostProcess.onApply = function (effect) {
  38375. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  38376. };
  38377. };
  38378. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  38379. var size = 512;
  38380. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38381. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  38382. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  38383. var context = this._randomTexture.getContext();
  38384. var rand = function (min, max) {
  38385. return Math.random() * (max - min) + min;
  38386. };
  38387. var randVector = BABYLON.Vector3.Zero();
  38388. for (var x = 0; x < size; x++) {
  38389. for (var y = 0; y < size; y++) {
  38390. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  38391. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  38392. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  38393. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  38394. context.fillRect(x, y, 1, 1);
  38395. }
  38396. }
  38397. this._randomTexture.update(false);
  38398. };
  38399. return SSAORenderingPipeline;
  38400. })(BABYLON.PostProcessRenderPipeline);
  38401. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  38402. })(BABYLON || (BABYLON = {}));
  38403. var BABYLON;
  38404. (function (BABYLON) {
  38405. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  38406. var VolumetricLightScatteringPostProcess = (function (_super) {
  38407. __extends(VolumetricLightScatteringPostProcess, _super);
  38408. /**
  38409. * @constructor
  38410. * @param {string} name - The post-process name
  38411. * @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)
  38412. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  38413. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  38414. * @param {number} samples - The post-process quality, default 100
  38415. * @param {number} samplingMode - The post-process filtering mode
  38416. * @param {BABYLON.Engine} engine - The babylon engine
  38417. * @param {boolean} reusable - If the post-process is reusable
  38418. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  38419. */
  38420. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  38421. var _this = this;
  38422. if (samples === void 0) { samples = 100; }
  38423. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38424. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  38425. this._screenCoordinates = BABYLON.Vector2.Zero();
  38426. /**
  38427. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  38428. * @type {boolean}
  38429. */
  38430. this.useCustomMeshPosition = false;
  38431. /**
  38432. * If the post-process should inverse the light scattering direction
  38433. * @type {boolean}
  38434. */
  38435. this.invert = true;
  38436. /**
  38437. * Set to true to use the diffuseColor instead of the diffuseTexture
  38438. * @type {boolean}
  38439. */
  38440. this.useDiffuseColor = false;
  38441. /**
  38442. * Array containing the excluded meshes not rendered in the internal pass
  38443. */
  38444. this.excludedMeshes = new Array();
  38445. /**
  38446. * Controls the overall intensity of the post-process
  38447. * @type {number}
  38448. */
  38449. this.exposure = 0.3;
  38450. /**
  38451. * Dissipates each sample's contribution in range [0, 1]
  38452. * @type {number}
  38453. */
  38454. this.decay = 0.96815;
  38455. /**
  38456. * Controls the overall intensity of each sample
  38457. * @type {number}
  38458. */
  38459. this.weight = 0.58767;
  38460. /**
  38461. * Controls the density of each sample
  38462. * @type {number}
  38463. */
  38464. this.density = 0.926;
  38465. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  38466. var engine = scene.getEngine();
  38467. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  38468. // Configure mesh
  38469. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  38470. // Configure
  38471. this._createPass(scene, ratio.passRatio || ratio);
  38472. this.onActivate = function (camera) {
  38473. if (!_this.isSupported) {
  38474. _this.dispose(camera);
  38475. }
  38476. _this.onActivate = null;
  38477. };
  38478. this.onApply = function (effect) {
  38479. _this._updateMeshScreenCoordinates(scene);
  38480. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  38481. effect.setFloat("exposure", _this.exposure);
  38482. effect.setFloat("decay", _this.decay);
  38483. effect.setFloat("weight", _this.weight);
  38484. effect.setFloat("density", _this.density);
  38485. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  38486. };
  38487. }
  38488. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  38489. var mesh = subMesh.getMesh();
  38490. var defines = [];
  38491. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38492. var material = subMesh.getMaterial();
  38493. var needUV = false;
  38494. // Render this.mesh as default
  38495. if (mesh === this.mesh) {
  38496. if (this.useDiffuseColor) {
  38497. defines.push("#define DIFFUSE_COLOR_RENDER");
  38498. }
  38499. else if (material) {
  38500. if (material.diffuseTexture !== undefined) {
  38501. defines.push("#define BASIC_RENDER");
  38502. }
  38503. else {
  38504. defines.push("#define DIFFUSE_COLOR_RENDER");
  38505. }
  38506. }
  38507. defines.push("#define NEED_UV");
  38508. needUV = true;
  38509. }
  38510. // Alpha test
  38511. if (material) {
  38512. if (material.needAlphaTesting()) {
  38513. defines.push("#define ALPHATEST");
  38514. }
  38515. if (material.opacityTexture !== undefined) {
  38516. defines.push("#define OPACITY");
  38517. if (material.opacityTexture.getAlphaFromRGB) {
  38518. defines.push("#define OPACITYRGB");
  38519. }
  38520. if (!needUV) {
  38521. defines.push("#define NEED_UV");
  38522. }
  38523. }
  38524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38525. attribs.push(BABYLON.VertexBuffer.UVKind);
  38526. defines.push("#define UV1");
  38527. }
  38528. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38529. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38530. defines.push("#define UV2");
  38531. }
  38532. }
  38533. // Bones
  38534. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38535. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38536. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38537. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38538. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38539. }
  38540. else {
  38541. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38542. }
  38543. // Instances
  38544. if (useInstances) {
  38545. defines.push("#define INSTANCES");
  38546. attribs.push("world0");
  38547. attribs.push("world1");
  38548. attribs.push("world2");
  38549. attribs.push("world3");
  38550. }
  38551. // Get correct effect
  38552. var join = defines.join("\n");
  38553. if (this._cachedDefines !== join) {
  38554. this._cachedDefines = join;
  38555. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  38556. }
  38557. return this._volumetricLightScatteringPass.isReady();
  38558. };
  38559. /**
  38560. * Sets the new light position for light scattering effect
  38561. * @param {BABYLON.Vector3} The new custom light position
  38562. */
  38563. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  38564. this._customMeshPosition = position;
  38565. };
  38566. /**
  38567. * Returns the light position for light scattering effect
  38568. * @return {BABYLON.Vector3} The custom light position
  38569. */
  38570. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  38571. return this._customMeshPosition;
  38572. };
  38573. /**
  38574. * Disposes the internal assets and detaches the post-process from the camera
  38575. */
  38576. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  38577. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  38578. if (rttIndex !== -1) {
  38579. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  38580. }
  38581. this._volumetricLightScatteringRTT.dispose();
  38582. _super.prototype.dispose.call(this, camera);
  38583. };
  38584. /**
  38585. * Returns the render target texture used by the post-process
  38586. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  38587. */
  38588. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  38589. return this._volumetricLightScatteringRTT;
  38590. };
  38591. // Private methods
  38592. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  38593. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  38594. return true;
  38595. }
  38596. return false;
  38597. };
  38598. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  38599. var _this = this;
  38600. var engine = scene.getEngine();
  38601. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38602. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38603. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38604. this._volumetricLightScatteringRTT.renderList = null;
  38605. this._volumetricLightScatteringRTT.renderParticles = false;
  38606. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  38607. // Custom render function for submeshes
  38608. var renderSubMesh = function (subMesh) {
  38609. var mesh = subMesh.getRenderingMesh();
  38610. if (_this._meshExcluded(mesh)) {
  38611. return;
  38612. }
  38613. var scene = mesh.getScene();
  38614. var engine = scene.getEngine();
  38615. // Culling
  38616. engine.setState(subMesh.getMaterial().backFaceCulling);
  38617. // Managing instances
  38618. var batch = mesh._getInstancesRenderList(subMesh._id);
  38619. if (batch.mustReturn) {
  38620. return;
  38621. }
  38622. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  38623. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  38624. engine.enableEffect(_this._volumetricLightScatteringPass);
  38625. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  38626. var material = subMesh.getMaterial();
  38627. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  38628. // Alpha test
  38629. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  38630. var alphaTexture = material.getAlphaTestTexture();
  38631. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  38632. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  38633. }
  38634. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  38635. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  38636. if (alphaTexture) {
  38637. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38638. }
  38639. }
  38640. if (material.opacityTexture !== undefined) {
  38641. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  38642. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  38643. }
  38644. }
  38645. // Bones
  38646. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38647. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38648. }
  38649. // Draw
  38650. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  38651. }
  38652. };
  38653. // Render target texture callbacks
  38654. var savedSceneClearColor;
  38655. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  38656. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  38657. savedSceneClearColor = scene.clearColor;
  38658. scene.clearColor = sceneClearColor;
  38659. };
  38660. this._volumetricLightScatteringRTT.onAfterRender = function () {
  38661. scene.clearColor = savedSceneClearColor;
  38662. };
  38663. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38664. var engine = scene.getEngine();
  38665. var index;
  38666. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38667. renderSubMesh(opaqueSubMeshes.data[index]);
  38668. }
  38669. engine.setAlphaTesting(true);
  38670. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38671. renderSubMesh(alphaTestSubMeshes.data[index]);
  38672. }
  38673. engine.setAlphaTesting(false);
  38674. if (transparentSubMeshes.length) {
  38675. // Sort sub meshes
  38676. for (index = 0; index < transparentSubMeshes.length; index++) {
  38677. var submesh = transparentSubMeshes.data[index];
  38678. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  38679. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  38680. }
  38681. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  38682. sortedArray.sort(function (a, b) {
  38683. // Alpha index first
  38684. if (a._alphaIndex > b._alphaIndex) {
  38685. return 1;
  38686. }
  38687. if (a._alphaIndex < b._alphaIndex) {
  38688. return -1;
  38689. }
  38690. // Then distance to camera
  38691. if (a._distanceToCamera < b._distanceToCamera) {
  38692. return 1;
  38693. }
  38694. if (a._distanceToCamera > b._distanceToCamera) {
  38695. return -1;
  38696. }
  38697. return 0;
  38698. });
  38699. // Render sub meshes
  38700. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38701. for (index = 0; index < sortedArray.length; index++) {
  38702. renderSubMesh(sortedArray[index]);
  38703. }
  38704. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38705. }
  38706. };
  38707. };
  38708. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  38709. var transform = scene.getTransformMatrix();
  38710. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  38711. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  38712. this._screenCoordinates.x = pos.x / this._viewPort.width;
  38713. this._screenCoordinates.y = pos.y / this._viewPort.height;
  38714. if (this.invert)
  38715. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  38716. };
  38717. // Static methods
  38718. /**
  38719. * Creates a default mesh for the Volumeric Light Scattering post-process
  38720. * @param {string} The mesh name
  38721. * @param {BABYLON.Scene} The scene where to create the mesh
  38722. * @return {BABYLON.Mesh} the default mesh
  38723. */
  38724. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  38725. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  38726. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  38727. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  38728. return mesh;
  38729. };
  38730. return VolumetricLightScatteringPostProcess;
  38731. })(BABYLON.PostProcess);
  38732. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  38733. })(BABYLON || (BABYLON = {}));
  38734. // BABYLON.JS Chromatic Aberration GLSL Shader
  38735. // Author: Olivier Guyot
  38736. // Separates very slightly R, G and B colors on the edges of the screen
  38737. // Inspired by Francois Tarlier & Martins Upitis
  38738. var BABYLON;
  38739. (function (BABYLON) {
  38740. var LensRenderingPipeline = (function (_super) {
  38741. __extends(LensRenderingPipeline, _super);
  38742. /**
  38743. * @constructor
  38744. *
  38745. * Effect parameters are as follow:
  38746. * {
  38747. * chromatic_aberration: number; // from 0 to x (1 for realism)
  38748. * edge_blur: number; // from 0 to x (1 for realism)
  38749. * distortion: number; // from 0 to x (1 for realism)
  38750. * grain_amount: number; // from 0 to 1
  38751. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  38752. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  38753. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  38754. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  38755. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  38756. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  38757. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  38758. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  38759. * }
  38760. * Note: if an effect parameter is unset, effect is disabled
  38761. *
  38762. * @param {string} name - The rendering pipeline name
  38763. * @param {object} parameters - An object containing all parameters (see above)
  38764. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  38765. * @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)
  38766. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  38767. */
  38768. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  38769. var _this = this;
  38770. if (ratio === void 0) { ratio = 1.0; }
  38771. _super.call(this, scene.getEngine(), name);
  38772. // Lens effects can be of the following:
  38773. // - chromatic aberration (slight shift of RGB colors)
  38774. // - blur on the edge of the lens
  38775. // - lens distortion
  38776. // - depth-of-field blur & highlights enhancing
  38777. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  38778. // - grain effect (noise or custom texture)
  38779. // Two additional texture samplers are needed:
  38780. // - depth map (for depth-of-field)
  38781. // - grain texture
  38782. /**
  38783. * The chromatic aberration PostProcess id in the pipeline
  38784. * @type {string}
  38785. */
  38786. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  38787. /**
  38788. * The highlights enhancing PostProcess id in the pipeline
  38789. * @type {string}
  38790. */
  38791. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  38792. /**
  38793. * The depth-of-field PostProcess id in the pipeline
  38794. * @type {string}
  38795. */
  38796. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  38797. this._scene = scene;
  38798. // Fetch texture samplers
  38799. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  38800. if (parameters.grain_texture) {
  38801. this._grainTexture = parameters.grain_texture;
  38802. }
  38803. else {
  38804. this._createGrainTexture();
  38805. }
  38806. // save parameters
  38807. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  38808. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  38809. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  38810. this._distortion = parameters.distortion ? parameters.distortion : 0;
  38811. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  38812. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  38813. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  38814. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  38815. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  38816. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  38817. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  38818. // Create effects
  38819. this._createChromaticAberrationPostProcess(ratio);
  38820. this._createHighlightsPostProcess(ratio);
  38821. this._createDepthOfFieldPostProcess(ratio / 4);
  38822. // Set up pipeline
  38823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  38824. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  38825. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  38826. if (this._highlightsGain === -1) {
  38827. this._disableEffect(this.HighlightsEnhancingEffect, null);
  38828. }
  38829. // Finish
  38830. scene.postProcessRenderPipelineManager.addPipeline(this);
  38831. if (cameras) {
  38832. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38833. }
  38834. }
  38835. // public methods (self explanatory)
  38836. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  38837. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  38838. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  38839. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  38840. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  38841. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  38842. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  38843. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  38844. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  38845. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  38846. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  38847. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  38848. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  38849. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  38850. };
  38851. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  38852. this._highlightsPostProcess.updateEffect();
  38853. };
  38854. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  38855. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  38856. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  38857. this._highlightsGain = amount;
  38858. };
  38859. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  38860. if (this._highlightsGain === -1) {
  38861. this._highlightsGain = 1.0;
  38862. }
  38863. this._highlightsThreshold = amount;
  38864. };
  38865. LensRenderingPipeline.prototype.disableHighlights = function () {
  38866. this._highlightsGain = -1;
  38867. };
  38868. /**
  38869. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  38870. */
  38871. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  38872. if (disableDepthRender === void 0) { disableDepthRender = false; }
  38873. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38874. this._chromaticAberrationPostProcess = undefined;
  38875. this._highlightsPostProcess = undefined;
  38876. this._depthOfFieldPostProcess = undefined;
  38877. this._grainTexture.dispose();
  38878. if (disableDepthRender)
  38879. this._scene.disableDepthRenderer();
  38880. };
  38881. // colors shifting and distortion
  38882. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  38883. var _this = this;
  38884. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  38885. [], // samplers
  38886. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38887. this._chromaticAberrationPostProcess.onApply = function (effect) {
  38888. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  38889. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38890. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38891. };
  38892. };
  38893. // highlights enhancing
  38894. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  38895. var _this = this;
  38896. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  38897. [], // samplers
  38898. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  38899. this._highlightsPostProcess.onApply = function (effect) {
  38900. effect.setFloat('gain', _this._highlightsGain);
  38901. effect.setFloat('threshold', _this._highlightsThreshold);
  38902. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  38903. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38904. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38905. };
  38906. };
  38907. // colors shifting and distortion
  38908. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  38909. var _this = this;
  38910. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  38911. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  38912. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  38913. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38914. this._depthOfFieldPostProcess.onApply = function (effect) {
  38915. effect.setTexture("depthSampler", _this._depthTexture);
  38916. effect.setTexture("grainSampler", _this._grainTexture);
  38917. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  38918. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  38919. effect.setFloat('grain_amount', _this._grainAmount);
  38920. effect.setBool('blur_noise', _this._blurNoise);
  38921. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38922. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38923. effect.setFloat('distortion', _this._distortion);
  38924. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  38925. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  38926. effect.setFloat('aperture', _this._dofAperture);
  38927. effect.setFloat('darken', _this._dofDarken);
  38928. effect.setFloat('edge_blur', _this._edgeBlur);
  38929. effect.setBool('highlights', (_this._highlightsGain !== -1));
  38930. effect.setFloat('near', _this._scene.activeCamera.minZ);
  38931. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  38932. };
  38933. };
  38934. // creates a black and white random noise texture, 512x512
  38935. LensRenderingPipeline.prototype._createGrainTexture = function () {
  38936. var size = 512;
  38937. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38938. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  38939. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  38940. var context = this._grainTexture.getContext();
  38941. var rand = function (min, max) {
  38942. return Math.random() * (max - min) + min;
  38943. };
  38944. var value;
  38945. for (var x = 0; x < size; x++) {
  38946. for (var y = 0; y < size; y++) {
  38947. value = Math.floor(rand(0.42, 0.58) * 255);
  38948. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  38949. context.fillRect(x, y, 1, 1);
  38950. }
  38951. }
  38952. this._grainTexture.update(false);
  38953. };
  38954. return LensRenderingPipeline;
  38955. })(BABYLON.PostProcessRenderPipeline);
  38956. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  38957. })(BABYLON || (BABYLON = {}));
  38958. //
  38959. // This post-process allows the modification of rendered colors by using
  38960. // a 'look-up table' (LUT). This effect is also called Color Grading.
  38961. //
  38962. // The object needs to be provided an url to a texture containing the color
  38963. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  38964. // Use an image editing software to tweak the LUT to match your needs.
  38965. //
  38966. // For an example of a color LUT, see here:
  38967. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  38968. // For explanations on color grading, see here:
  38969. // http://udn.epicgames.com/Three/ColorGrading.html
  38970. //
  38971. var BABYLON;
  38972. (function (BABYLON) {
  38973. var ColorCorrectionPostProcess = (function (_super) {
  38974. __extends(ColorCorrectionPostProcess, _super);
  38975. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  38976. var _this = this;
  38977. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  38978. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38979. this._colorTableTexture.anisotropicFilteringLevel = 1;
  38980. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38981. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38982. this.onApply = function (effect) {
  38983. effect.setTexture("colorTable", _this._colorTableTexture);
  38984. };
  38985. }
  38986. return ColorCorrectionPostProcess;
  38987. })(BABYLON.PostProcess);
  38988. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  38989. })(BABYLON || (BABYLON = {}));
  38990. var BABYLON;
  38991. (function (BABYLON) {
  38992. var AnaglyphFreeCamera = (function (_super) {
  38993. __extends(AnaglyphFreeCamera, _super);
  38994. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38995. _super.call(this, name, position, scene);
  38996. this.interaxialDistance = interaxialDistance;
  38997. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38998. }
  38999. AnaglyphFreeCamera.prototype.getTypeName = function () {
  39000. return "AnaglyphFreeCamera";
  39001. };
  39002. return AnaglyphFreeCamera;
  39003. })(BABYLON.FreeCamera);
  39004. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  39005. var AnaglyphArcRotateCamera = (function (_super) {
  39006. __extends(AnaglyphArcRotateCamera, _super);
  39007. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  39008. _super.call(this, name, alpha, beta, radius, target, scene);
  39009. this.interaxialDistance = interaxialDistance;
  39010. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39011. }
  39012. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  39013. return "AnaglyphArcRotateCamera";
  39014. };
  39015. return AnaglyphArcRotateCamera;
  39016. })(BABYLON.ArcRotateCamera);
  39017. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  39018. var AnaglyphGamepadCamera = (function (_super) {
  39019. __extends(AnaglyphGamepadCamera, _super);
  39020. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  39021. _super.call(this, name, position, scene);
  39022. this.interaxialDistance = interaxialDistance;
  39023. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39024. }
  39025. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  39026. return "AnaglyphGamepadCamera";
  39027. };
  39028. return AnaglyphGamepadCamera;
  39029. })(BABYLON.GamepadCamera);
  39030. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  39031. var AnaglyphUniversalCamera = (function (_super) {
  39032. __extends(AnaglyphUniversalCamera, _super);
  39033. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  39034. _super.call(this, name, position, scene);
  39035. this.interaxialDistance = interaxialDistance;
  39036. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39037. }
  39038. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  39039. return "AnaglyphUniversalCamera";
  39040. };
  39041. return AnaglyphUniversalCamera;
  39042. })(BABYLON.UniversalCamera);
  39043. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  39044. var StereoscopicFreeCamera = (function (_super) {
  39045. __extends(StereoscopicFreeCamera, _super);
  39046. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39047. _super.call(this, name, position, scene);
  39048. this.interaxialDistance = interaxialDistance;
  39049. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39050. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39051. }
  39052. StereoscopicFreeCamera.prototype.getTypeName = function () {
  39053. return "StereoscopicFreeCamera";
  39054. };
  39055. return StereoscopicFreeCamera;
  39056. })(BABYLON.FreeCamera);
  39057. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  39058. var StereoscopicArcRotateCamera = (function (_super) {
  39059. __extends(StereoscopicArcRotateCamera, _super);
  39060. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  39061. _super.call(this, name, alpha, beta, radius, target, scene);
  39062. this.interaxialDistance = interaxialDistance;
  39063. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39064. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39065. }
  39066. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  39067. return "StereoscopicArcRotateCamera";
  39068. };
  39069. return StereoscopicArcRotateCamera;
  39070. })(BABYLON.ArcRotateCamera);
  39071. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  39072. var StereoscopicGamepadCamera = (function (_super) {
  39073. __extends(StereoscopicGamepadCamera, _super);
  39074. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39075. _super.call(this, name, position, scene);
  39076. this.interaxialDistance = interaxialDistance;
  39077. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39078. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39079. }
  39080. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  39081. return "StereoscopicGamepadCamera";
  39082. };
  39083. return StereoscopicGamepadCamera;
  39084. })(BABYLON.GamepadCamera);
  39085. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  39086. var StereoscopicUniversalCamera = (function (_super) {
  39087. __extends(StereoscopicUniversalCamera, _super);
  39088. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39089. _super.call(this, name, position, scene);
  39090. this.interaxialDistance = interaxialDistance;
  39091. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39092. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39093. }
  39094. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  39095. return "StereoscopicUniversalCamera";
  39096. };
  39097. return StereoscopicUniversalCamera;
  39098. })(BABYLON.UniversalCamera);
  39099. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  39100. })(BABYLON || (BABYLON = {}));
  39101. var BABYLON;
  39102. (function (BABYLON) {
  39103. var HDRRenderingPipeline = (function (_super) {
  39104. __extends(HDRRenderingPipeline, _super);
  39105. /**
  39106. * @constructor
  39107. * @param {string} name - The rendering pipeline name
  39108. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39109. * @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)
  39110. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  39111. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39112. */
  39113. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  39114. var _this = this;
  39115. if (originalPostProcess === void 0) { originalPostProcess = null; }
  39116. _super.call(this, scene.getEngine(), name);
  39117. /**
  39118. * Public members
  39119. */
  39120. // Gaussian Blur
  39121. /**
  39122. * Gaussian blur coefficient
  39123. * @type {number}
  39124. */
  39125. this.gaussCoeff = 0.3;
  39126. /**
  39127. * Gaussian blur mean
  39128. * @type {number}
  39129. */
  39130. this.gaussMean = 1.0;
  39131. /**
  39132. * Gaussian blur standard deviation
  39133. * @type {number}
  39134. */
  39135. this.gaussStandDev = 0.8;
  39136. /**
  39137. * Gaussian blur multiplier. Multiplies the blur effect
  39138. * @type {number}
  39139. */
  39140. this.gaussMultiplier = 4.0;
  39141. // HDR
  39142. /**
  39143. * Exposure, controls the overall intensity of the pipeline
  39144. * @type {number}
  39145. */
  39146. this.exposure = 1.0;
  39147. /**
  39148. * Minimum luminance that the post-process can output. Luminance is >= 0
  39149. * @type {number}
  39150. */
  39151. this.minimumLuminance = 1.0;
  39152. /**
  39153. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  39154. * @type {number}
  39155. */
  39156. this.maximumLuminance = 1e20;
  39157. /**
  39158. * Increase rate for luminance: eye adaptation speed to dark
  39159. * @type {number}
  39160. */
  39161. this.luminanceIncreaserate = 0.5;
  39162. /**
  39163. * Decrease rate for luminance: eye adaptation speed to bright
  39164. * @type {number}
  39165. */
  39166. this.luminanceDecreaseRate = 0.5;
  39167. // Bright pass
  39168. /**
  39169. * Minimum luminance needed to compute HDR
  39170. * @type {number}
  39171. */
  39172. this.brightThreshold = 0.8;
  39173. this._needUpdate = true;
  39174. this._scene = scene;
  39175. // Bright pass
  39176. this._createBrightPassPostProcess(scene, ratio);
  39177. // Down sample X4
  39178. this._createDownSampleX4PostProcess(scene, ratio);
  39179. // Create gaussian blur post-processes
  39180. this._createGaussianBlurPostProcess(scene, ratio);
  39181. // Texture adder
  39182. this._createTextureAdderPostProcess(scene, ratio);
  39183. // Luminance generator
  39184. this._createLuminanceGeneratorPostProcess(scene);
  39185. // HDR
  39186. this._createHDRPostProcess(scene, ratio);
  39187. // Pass postprocess
  39188. if (originalPostProcess === null) {
  39189. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39190. }
  39191. else {
  39192. this._originalPostProcess = originalPostProcess;
  39193. }
  39194. // Configure pipeline
  39195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  39196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  39197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  39198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  39199. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  39200. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  39201. var addDownSamplerPostProcess = function (id) {
  39202. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  39203. };
  39204. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  39205. addDownSamplerPostProcess(i);
  39206. }
  39207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  39208. // Finish
  39209. scene.postProcessRenderPipelineManager.addPipeline(this);
  39210. if (cameras !== null) {
  39211. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39212. }
  39213. this.update();
  39214. }
  39215. /**
  39216. * Tells the pipeline to update its post-processes
  39217. */
  39218. HDRRenderingPipeline.prototype.update = function () {
  39219. this._needUpdate = true;
  39220. };
  39221. /**
  39222. * Returns the current calculated luminance
  39223. */
  39224. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  39225. return this._hdrCurrentLuminance;
  39226. };
  39227. /**
  39228. * Returns the currently drawn luminance
  39229. */
  39230. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  39231. return this._hdrOutputLuminance;
  39232. };
  39233. /**
  39234. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  39235. */
  39236. HDRRenderingPipeline.prototype.dispose = function () {
  39237. this._originalPostProcess = undefined;
  39238. this._brightPassPostProcess = undefined;
  39239. this._downSampleX4PostProcess = undefined;
  39240. this._guassianBlurHPostProcess = undefined;
  39241. this._guassianBlurVPostProcess = undefined;
  39242. this._textureAdderPostProcess = undefined;
  39243. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  39244. this._downSamplePostProcesses[i] = undefined;
  39245. }
  39246. this._hdrPostProcess = undefined;
  39247. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39248. };
  39249. /**
  39250. * Creates the HDR post-process and computes the luminance adaptation
  39251. */
  39252. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  39253. var _this = this;
  39254. var hdrLastLuminance = 0.0;
  39255. this._hdrOutputLuminance = -1.0;
  39256. this._hdrCurrentLuminance = 1.0;
  39257. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  39258. this._hdrPostProcess.onApply = function (effect) {
  39259. if (_this._hdrOutputLuminance < 0.0) {
  39260. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  39261. }
  39262. else {
  39263. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  39264. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  39265. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  39266. }
  39267. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  39268. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  39269. }
  39270. else {
  39271. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  39272. }
  39273. }
  39274. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  39275. hdrLastLuminance += scene.getEngine().getDeltaTime();
  39276. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  39277. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  39278. effect.setFloat("exposure", _this.exposure);
  39279. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  39280. _this._needUpdate = false;
  39281. };
  39282. };
  39283. /**
  39284. * Texture Adder post-process
  39285. */
  39286. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  39287. var _this = this;
  39288. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  39289. this._textureAdderPostProcess.onApply = function (effect) {
  39290. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  39291. };
  39292. };
  39293. /**
  39294. * Down sample X4 post-process
  39295. */
  39296. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  39297. var _this = this;
  39298. var downSampleX4Offsets = new Array(32);
  39299. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  39300. this._downSampleX4PostProcess.onApply = function (effect) {
  39301. if (_this._needUpdate) {
  39302. var id = 0;
  39303. for (var i = -2; i < 2; i++) {
  39304. for (var j = -2; j < 2; j++) {
  39305. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  39306. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  39307. id += 2;
  39308. }
  39309. }
  39310. }
  39311. effect.setArray2("dsOffsets", downSampleX4Offsets);
  39312. };
  39313. };
  39314. /**
  39315. * Bright pass post-process
  39316. */
  39317. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  39318. var _this = this;
  39319. var brightOffsets = new Array(8);
  39320. var brightPassCallback = function (effect) {
  39321. if (_this._needUpdate) {
  39322. var sU = (1.0 / _this._brightPassPostProcess.width);
  39323. var sV = (1.0 / _this._brightPassPostProcess.height);
  39324. brightOffsets[0] = -0.5 * sU;
  39325. brightOffsets[1] = 0.5 * sV;
  39326. brightOffsets[2] = 0.5 * sU;
  39327. brightOffsets[3] = 0.5 * sV;
  39328. brightOffsets[4] = -0.5 * sU;
  39329. brightOffsets[5] = -0.5 * sV;
  39330. brightOffsets[6] = 0.5 * sU;
  39331. brightOffsets[7] = -0.5 * sV;
  39332. }
  39333. effect.setArray2("dsOffsets", brightOffsets);
  39334. effect.setFloat("brightThreshold", _this.brightThreshold);
  39335. };
  39336. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  39337. this._brightPassPostProcess.onApply = brightPassCallback;
  39338. };
  39339. /**
  39340. * Luminance generator. Creates the luminance post-process and down sample post-processes
  39341. */
  39342. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  39343. var _this = this;
  39344. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  39345. var luminanceOffsets = new Array(8);
  39346. var downSampleOffsets = new Array(18);
  39347. var halfDestPixelSize;
  39348. this._downSamplePostProcesses = new Array(lumSteps);
  39349. // Utils for luminance
  39350. var luminanceUpdateSourceOffsets = function (width, height) {
  39351. var sU = (1.0 / width);
  39352. var sV = (1.0 / height);
  39353. luminanceOffsets[0] = -0.5 * sU;
  39354. luminanceOffsets[1] = 0.5 * sV;
  39355. luminanceOffsets[2] = 0.5 * sU;
  39356. luminanceOffsets[3] = 0.5 * sV;
  39357. luminanceOffsets[4] = -0.5 * sU;
  39358. luminanceOffsets[5] = -0.5 * sV;
  39359. luminanceOffsets[6] = 0.5 * sU;
  39360. luminanceOffsets[7] = -0.5 * sV;
  39361. };
  39362. var luminanceUpdateDestOffsets = function (width, height) {
  39363. var id = 0;
  39364. for (var x = -1; x < 2; x++) {
  39365. for (var y = -1; y < 2; y++) {
  39366. downSampleOffsets[id] = (x) / width;
  39367. downSampleOffsets[id + 1] = (y) / height;
  39368. id += 2;
  39369. }
  39370. }
  39371. };
  39372. // Luminance callback
  39373. var luminanceCallback = function (effect) {
  39374. if (_this._needUpdate) {
  39375. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  39376. }
  39377. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  39378. effect.setArray2("lumOffsets", luminanceOffsets);
  39379. };
  39380. // Down sample callbacks
  39381. var downSampleCallback = function (indice) {
  39382. var i = indice;
  39383. return function (effect) {
  39384. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  39385. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  39386. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  39387. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  39388. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  39389. effect.setArray2("dsOffsets", downSampleOffsets);
  39390. };
  39391. };
  39392. var downSampleAfterRenderCallback = function (effect) {
  39393. // Unpack result
  39394. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  39395. 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);
  39396. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  39397. };
  39398. // Create luminance post-process
  39399. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  39400. 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);
  39401. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  39402. // Create down sample post-processes
  39403. for (var i = lumSteps - 2; i >= 0; i--) {
  39404. var length = Math.pow(3, i);
  39405. ratio = { width: length, height: length };
  39406. var defines = "#define DOWN_SAMPLE\n";
  39407. if (i === 0) {
  39408. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  39409. }
  39410. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  39411. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  39412. if (i === 0) {
  39413. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  39414. }
  39415. }
  39416. };
  39417. /**
  39418. * Gaussian blur post-processes. Horizontal and Vertical
  39419. */
  39420. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  39421. var _this = this;
  39422. var blurOffsetsW = new Array(9);
  39423. var blurOffsetsH = new Array(9);
  39424. var blurWeights = new Array(9);
  39425. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  39426. // Utils for gaussian blur
  39427. var calculateBlurOffsets = function (height) {
  39428. var lastOutputDimensions = {
  39429. width: scene.getEngine().getRenderWidth(),
  39430. height: scene.getEngine().getRenderHeight()
  39431. };
  39432. for (var i = 0; i < 9; i++) {
  39433. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  39434. if (height) {
  39435. blurOffsetsH[i] = value;
  39436. }
  39437. else {
  39438. blurOffsetsW[i] = value;
  39439. }
  39440. }
  39441. };
  39442. var calculateWeights = function () {
  39443. var x = 0.0;
  39444. for (var i = 0; i < 9; i++) {
  39445. x = (i - 4.0) / 4.0;
  39446. 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));
  39447. }
  39448. };
  39449. // Callback
  39450. var gaussianBlurCallback = function (height) {
  39451. return function (effect) {
  39452. if (_this._needUpdate) {
  39453. calculateWeights();
  39454. calculateBlurOffsets(height);
  39455. }
  39456. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  39457. effect.setArray("blurWeights", blurWeights);
  39458. effect.setFloat("multiplier", _this.gaussMultiplier);
  39459. };
  39460. };
  39461. // Create horizontal gaussian blur post-processes
  39462. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  39463. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  39464. // Create vertical gaussian blur post-process
  39465. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  39466. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  39467. };
  39468. // Luminance generator
  39469. HDRRenderingPipeline.LUM_STEPS = 6;
  39470. return HDRRenderingPipeline;
  39471. })(BABYLON.PostProcessRenderPipeline);
  39472. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  39473. })(BABYLON || (BABYLON = {}));
  39474. var BABYLON;
  39475. (function (BABYLON) {
  39476. var FaceAdjacencies = (function () {
  39477. function FaceAdjacencies() {
  39478. this.edges = new Array();
  39479. this.edgesConnectedCount = 0;
  39480. }
  39481. return FaceAdjacencies;
  39482. })();
  39483. var EdgesRenderer = (function () {
  39484. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  39485. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  39486. if (epsilon === void 0) { epsilon = 0.95; }
  39487. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  39488. this.edgesWidthScalerForOrthographic = 1000.0;
  39489. this.edgesWidthScalerForPerspective = 50.0;
  39490. this._linesPositions = new Array();
  39491. this._linesNormals = new Array();
  39492. this._linesIndices = new Array();
  39493. this._buffers = new Array();
  39494. this._checkVerticesInsteadOfIndices = false;
  39495. this._source = source;
  39496. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  39497. this._epsilon = epsilon;
  39498. this._prepareRessources();
  39499. this._generateEdgesLines();
  39500. }
  39501. EdgesRenderer.prototype._prepareRessources = function () {
  39502. if (this._lineShader) {
  39503. return;
  39504. }
  39505. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  39506. attributes: ["position", "normal"],
  39507. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  39508. });
  39509. this._lineShader.disableDepthWrite = true;
  39510. this._lineShader.backFaceCulling = false;
  39511. };
  39512. EdgesRenderer.prototype.dispose = function () {
  39513. this._vb0.dispose();
  39514. this._vb1.dispose();
  39515. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  39516. this._lineShader.dispose();
  39517. };
  39518. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  39519. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  39520. return 0;
  39521. }
  39522. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  39523. return 1;
  39524. }
  39525. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  39526. return 2;
  39527. }
  39528. return -1;
  39529. };
  39530. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  39531. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  39532. return 0;
  39533. }
  39534. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  39535. return 1;
  39536. }
  39537. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  39538. return 2;
  39539. }
  39540. return -1;
  39541. };
  39542. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  39543. var needToCreateLine;
  39544. if (edge === undefined) {
  39545. needToCreateLine = true;
  39546. }
  39547. else {
  39548. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  39549. needToCreateLine = dotProduct < this._epsilon;
  39550. }
  39551. if (needToCreateLine) {
  39552. var offset = this._linesPositions.length / 3;
  39553. var normal = p0.subtract(p1);
  39554. normal.normalize();
  39555. // Positions
  39556. this._linesPositions.push(p0.x);
  39557. this._linesPositions.push(p0.y);
  39558. this._linesPositions.push(p0.z);
  39559. this._linesPositions.push(p0.x);
  39560. this._linesPositions.push(p0.y);
  39561. this._linesPositions.push(p0.z);
  39562. this._linesPositions.push(p1.x);
  39563. this._linesPositions.push(p1.y);
  39564. this._linesPositions.push(p1.z);
  39565. this._linesPositions.push(p1.x);
  39566. this._linesPositions.push(p1.y);
  39567. this._linesPositions.push(p1.z);
  39568. // Normals
  39569. this._linesNormals.push(p1.x);
  39570. this._linesNormals.push(p1.y);
  39571. this._linesNormals.push(p1.z);
  39572. this._linesNormals.push(-1);
  39573. this._linesNormals.push(p1.x);
  39574. this._linesNormals.push(p1.y);
  39575. this._linesNormals.push(p1.z);
  39576. this._linesNormals.push(1);
  39577. this._linesNormals.push(p0.x);
  39578. this._linesNormals.push(p0.y);
  39579. this._linesNormals.push(p0.z);
  39580. this._linesNormals.push(-1);
  39581. this._linesNormals.push(p0.x);
  39582. this._linesNormals.push(p0.y);
  39583. this._linesNormals.push(p0.z);
  39584. this._linesNormals.push(1);
  39585. // Indices
  39586. this._linesIndices.push(offset);
  39587. this._linesIndices.push(offset + 1);
  39588. this._linesIndices.push(offset + 2);
  39589. this._linesIndices.push(offset);
  39590. this._linesIndices.push(offset + 2);
  39591. this._linesIndices.push(offset + 3);
  39592. }
  39593. };
  39594. EdgesRenderer.prototype._generateEdgesLines = function () {
  39595. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39596. var indices = this._source.getIndices();
  39597. // First let's find adjacencies
  39598. var adjacencies = new Array();
  39599. var faceNormals = new Array();
  39600. var index;
  39601. var faceAdjacencies;
  39602. // Prepare faces
  39603. for (index = 0; index < indices.length; index += 3) {
  39604. faceAdjacencies = new FaceAdjacencies();
  39605. var p0Index = indices[index];
  39606. var p1Index = indices[index + 1];
  39607. var p2Index = indices[index + 2];
  39608. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  39609. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  39610. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  39611. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  39612. faceNormal.normalize();
  39613. faceNormals.push(faceNormal);
  39614. adjacencies.push(faceAdjacencies);
  39615. }
  39616. // Scan
  39617. for (index = 0; index < adjacencies.length; index++) {
  39618. faceAdjacencies = adjacencies[index];
  39619. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  39620. var otherFaceAdjacencies = adjacencies[otherIndex];
  39621. if (faceAdjacencies.edgesConnectedCount === 3) {
  39622. break;
  39623. }
  39624. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  39625. continue;
  39626. }
  39627. var otherP0 = indices[otherIndex * 3];
  39628. var otherP1 = indices[otherIndex * 3 + 1];
  39629. var otherP2 = indices[otherIndex * 3 + 2];
  39630. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  39631. var otherEdgeIndex;
  39632. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  39633. continue;
  39634. }
  39635. switch (edgeIndex) {
  39636. case 0:
  39637. if (this._checkVerticesInsteadOfIndices) {
  39638. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39639. }
  39640. else {
  39641. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  39642. }
  39643. break;
  39644. case 1:
  39645. if (this._checkVerticesInsteadOfIndices) {
  39646. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39647. }
  39648. else {
  39649. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  39650. }
  39651. break;
  39652. case 2:
  39653. if (this._checkVerticesInsteadOfIndices) {
  39654. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39655. }
  39656. else {
  39657. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  39658. }
  39659. break;
  39660. }
  39661. if (otherEdgeIndex === -1) {
  39662. continue;
  39663. }
  39664. faceAdjacencies.edges[edgeIndex] = otherIndex;
  39665. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  39666. faceAdjacencies.edgesConnectedCount++;
  39667. otherFaceAdjacencies.edgesConnectedCount++;
  39668. if (faceAdjacencies.edgesConnectedCount === 3) {
  39669. break;
  39670. }
  39671. }
  39672. }
  39673. }
  39674. // Create lines
  39675. for (index = 0; index < adjacencies.length; index++) {
  39676. // 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
  39677. var current = adjacencies[index];
  39678. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  39679. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  39680. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  39681. }
  39682. // Merge into a single mesh
  39683. var engine = this._source.getScene().getEngine();
  39684. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  39685. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  39686. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  39687. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  39688. this._ib = engine.createIndexBuffer(this._linesIndices);
  39689. this._indicesCount = this._linesIndices.length;
  39690. };
  39691. EdgesRenderer.prototype.render = function () {
  39692. if (!this._lineShader.isReady()) {
  39693. return;
  39694. }
  39695. var scene = this._source.getScene();
  39696. var engine = scene.getEngine();
  39697. this._lineShader._preBind();
  39698. // VBOs
  39699. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  39700. scene.resetCachedMaterial();
  39701. this._lineShader.setColor4("color", this._source.edgesColor);
  39702. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  39703. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  39704. }
  39705. else {
  39706. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  39707. }
  39708. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  39709. this._lineShader.bind(this._source.getWorldMatrix());
  39710. // Draw order
  39711. engine.draw(true, 0, this._indicesCount);
  39712. this._lineShader.unbind();
  39713. engine.setDepthWrite(true);
  39714. };
  39715. return EdgesRenderer;
  39716. })();
  39717. BABYLON.EdgesRenderer = EdgesRenderer;
  39718. })(BABYLON || (BABYLON = {}));
  39719. var BABYLON;
  39720. (function (BABYLON) {
  39721. (function (TonemappingOperator) {
  39722. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  39723. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  39724. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  39725. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  39726. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  39727. var TonemappingOperator = BABYLON.TonemappingOperator;
  39728. ;
  39729. var TonemapPostProcess = (function (_super) {
  39730. __extends(TonemapPostProcess, _super);
  39731. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  39732. var _this = this;
  39733. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39734. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39735. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  39736. this._operator = _operator;
  39737. this.exposureAdjustment = exposureAdjustment;
  39738. var defines = "#define ";
  39739. if (this._operator === TonemappingOperator.Hable)
  39740. defines += "HABLE_TONEMAPPING";
  39741. else if (this._operator === TonemappingOperator.Reinhard)
  39742. defines += "REINHARD_TONEMAPPING";
  39743. else if (this._operator === TonemappingOperator.HejiDawson)
  39744. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  39745. else if (this._operator === TonemappingOperator.Photographic)
  39746. defines += "PHOTOGRAPHIC_TONEMAPPING";
  39747. //sadly a second call to create the effect.
  39748. this.updateEffect(defines);
  39749. this.onApply = function (effect) {
  39750. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  39751. };
  39752. }
  39753. return TonemapPostProcess;
  39754. })(BABYLON.PostProcess);
  39755. BABYLON.TonemapPostProcess = TonemapPostProcess;
  39756. })(BABYLON || (BABYLON = {}));
  39757. var BABYLON;
  39758. (function (BABYLON) {
  39759. var ReflectionProbe = (function () {
  39760. function ReflectionProbe(name, size, scene, generateMipMaps) {
  39761. var _this = this;
  39762. if (generateMipMaps === void 0) { generateMipMaps = true; }
  39763. this.name = name;
  39764. this._viewMatrix = BABYLON.Matrix.Identity();
  39765. this._target = BABYLON.Vector3.Zero();
  39766. this._add = BABYLON.Vector3.Zero();
  39767. this.position = BABYLON.Vector3.Zero();
  39768. this._scene = scene;
  39769. this._scene.reflectionProbes.push(this);
  39770. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  39771. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  39772. switch (faceIndex) {
  39773. case 0:
  39774. _this._add.copyFromFloats(1, 0, 0);
  39775. break;
  39776. case 1:
  39777. _this._add.copyFromFloats(-1, 0, 0);
  39778. break;
  39779. case 2:
  39780. _this._add.copyFromFloats(0, -1, 0);
  39781. break;
  39782. case 3:
  39783. _this._add.copyFromFloats(0, 1, 0);
  39784. break;
  39785. case 4:
  39786. _this._add.copyFromFloats(0, 0, 1);
  39787. break;
  39788. case 5:
  39789. _this._add.copyFromFloats(0, 0, -1);
  39790. break;
  39791. }
  39792. if (_this._attachedMesh) {
  39793. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  39794. }
  39795. _this.position.addToRef(_this._add, _this._target);
  39796. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  39797. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  39798. };
  39799. this._renderTargetTexture.onAfterUnbind = function () {
  39800. scene.updateTransformMatrix(true);
  39801. };
  39802. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  39803. }
  39804. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  39805. get: function () {
  39806. return this._renderTargetTexture.refreshRate;
  39807. },
  39808. set: function (value) {
  39809. this._renderTargetTexture.refreshRate = value;
  39810. },
  39811. enumerable: true,
  39812. configurable: true
  39813. });
  39814. ReflectionProbe.prototype.getScene = function () {
  39815. return this._scene;
  39816. };
  39817. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  39818. get: function () {
  39819. return this._renderTargetTexture;
  39820. },
  39821. enumerable: true,
  39822. configurable: true
  39823. });
  39824. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  39825. get: function () {
  39826. return this._renderTargetTexture.renderList;
  39827. },
  39828. enumerable: true,
  39829. configurable: true
  39830. });
  39831. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  39832. this._attachedMesh = mesh;
  39833. };
  39834. ReflectionProbe.prototype.dispose = function () {
  39835. var index = this._scene.reflectionProbes.indexOf(this);
  39836. if (index !== -1) {
  39837. // Remove from the scene if found
  39838. this._scene.reflectionProbes.splice(index, 1);
  39839. }
  39840. if (this._renderTargetTexture) {
  39841. this._renderTargetTexture.dispose();
  39842. this._renderTargetTexture = null;
  39843. }
  39844. };
  39845. return ReflectionProbe;
  39846. })();
  39847. BABYLON.ReflectionProbe = ReflectionProbe;
  39848. })(BABYLON || (BABYLON = {}));
  39849. var BABYLON;
  39850. (function (BABYLON) {
  39851. var SolidParticle = (function () {
  39852. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  39853. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  39854. this.position = BABYLON.Vector3.Zero(); // position
  39855. this.rotation = BABYLON.Vector3.Zero(); // rotation
  39856. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  39857. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  39858. this.velocity = BABYLON.Vector3.Zero(); // velocity
  39859. this.alive = true; // alive
  39860. this.idx = particleIndex;
  39861. this._pos = positionIndex;
  39862. this._model = model;
  39863. this.shapeId = shapeId;
  39864. this.idxInShape = idxInShape;
  39865. }
  39866. return SolidParticle;
  39867. })();
  39868. BABYLON.SolidParticle = SolidParticle;
  39869. var ModelShape = (function () {
  39870. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  39871. this.shapeID = id;
  39872. this._shape = shape;
  39873. this._shapeUV = shapeUV;
  39874. this._positionFunction = posFunction;
  39875. this._vertexFunction = vtxFunction;
  39876. }
  39877. return ModelShape;
  39878. })();
  39879. BABYLON.ModelShape = ModelShape;
  39880. })(BABYLON || (BABYLON = {}));
  39881. var BABYLON;
  39882. (function (BABYLON) {
  39883. /**
  39884. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  39885. */
  39886. var SolidParticleSystem = (function () {
  39887. /**
  39888. * Creates a SPS (Solid Particle System) object.
  39889. * @param name the SPS name, this will be the underlying mesh name
  39890. * @param scene the scene in which the SPS is added
  39891. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  39892. */
  39893. function SolidParticleSystem(name, scene, options) {
  39894. // public members
  39895. /**
  39896. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  39897. * Example : var p = SPS.particles[i];
  39898. */
  39899. this.particles = new Array();
  39900. /**
  39901. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  39902. */
  39903. this.nbParticles = 0;
  39904. /**
  39905. * If the particles must ever face the camera (default false). Useful for planar particles.
  39906. */
  39907. this.billboard = false;
  39908. /**
  39909. * This a counter ofr your own usage. It's not set by any SPS functions.
  39910. */
  39911. this.counter = 0;
  39912. /**
  39913. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  39914. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  39915. */
  39916. this.vars = {};
  39917. this._positions = new Array();
  39918. this._indices = new Array();
  39919. this._normals = new Array();
  39920. this._colors = new Array();
  39921. this._uvs = new Array();
  39922. this._index = 0; // indices index
  39923. this._updatable = true;
  39924. this._pickable = false;
  39925. this._isVisibilityBoxLocked = false;
  39926. this._alwaysVisible = false;
  39927. this._shapeCounter = 0;
  39928. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  39929. this._color = new BABYLON.Color4(0, 0, 0, 0);
  39930. this._computeParticleColor = true;
  39931. this._computeParticleTexture = true;
  39932. this._computeParticleRotation = true;
  39933. this._computeParticleVertex = false;
  39934. this._computeBoundingBox = false;
  39935. this._cam_axisZ = BABYLON.Vector3.Zero();
  39936. this._cam_axisY = BABYLON.Vector3.Zero();
  39937. this._cam_axisX = BABYLON.Vector3.Zero();
  39938. this._axisX = BABYLON.Axis.X;
  39939. this._axisY = BABYLON.Axis.Y;
  39940. this._axisZ = BABYLON.Axis.Z;
  39941. this._fakeCamPos = BABYLON.Vector3.Zero();
  39942. this._rotMatrix = new BABYLON.Matrix();
  39943. this._invertMatrix = new BABYLON.Matrix();
  39944. this._rotated = BABYLON.Vector3.Zero();
  39945. this._quaternion = new BABYLON.Quaternion();
  39946. this._vertex = BABYLON.Vector3.Zero();
  39947. this._normal = BABYLON.Vector3.Zero();
  39948. this._yaw = 0.0;
  39949. this._pitch = 0.0;
  39950. this._roll = 0.0;
  39951. this._halfroll = 0.0;
  39952. this._halfpitch = 0.0;
  39953. this._halfyaw = 0.0;
  39954. this._sinRoll = 0.0;
  39955. this._cosRoll = 0.0;
  39956. this._sinPitch = 0.0;
  39957. this._cosPitch = 0.0;
  39958. this._sinYaw = 0.0;
  39959. this._cosYaw = 0.0;
  39960. this._w = 0.0;
  39961. this._minimum = BABYLON.Tmp.Vector3[0];
  39962. this._maximum = BABYLON.Tmp.Vector3[1];
  39963. this.name = name;
  39964. this._scene = scene;
  39965. this._camera = scene.activeCamera;
  39966. this._pickable = options ? options.isPickable : false;
  39967. if (options && options.updatable) {
  39968. this._updatable = options.updatable;
  39969. }
  39970. else {
  39971. this._updatable = true;
  39972. }
  39973. if (this._pickable) {
  39974. this.pickedParticles = [];
  39975. }
  39976. }
  39977. /**
  39978. * Builds the SPS underlying mesh. Returns a standard Mesh.
  39979. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  39980. */
  39981. SolidParticleSystem.prototype.buildMesh = function () {
  39982. if (this.nbParticles === 0) {
  39983. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  39984. this.addShape(triangle, 1);
  39985. triangle.dispose();
  39986. }
  39987. this._positions32 = new Float32Array(this._positions);
  39988. this._uvs32 = new Float32Array(this._uvs);
  39989. this._colors32 = new Float32Array(this._colors);
  39990. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  39991. this._normals32 = new Float32Array(this._normals);
  39992. this._fixedNormal32 = new Float32Array(this._normals);
  39993. var vertexData = new BABYLON.VertexData();
  39994. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  39995. vertexData.indices = this._indices;
  39996. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  39997. if (this._uvs32) {
  39998. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  39999. ;
  40000. }
  40001. if (this._colors32) {
  40002. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  40003. }
  40004. var mesh = new BABYLON.Mesh(this.name, this._scene);
  40005. vertexData.applyToMesh(mesh, this._updatable);
  40006. this.mesh = mesh;
  40007. this.mesh.isPickable = this._pickable;
  40008. // free memory
  40009. this._positions = null;
  40010. this._normals = null;
  40011. this._uvs = null;
  40012. this._colors = null;
  40013. if (!this._updatable) {
  40014. this.particles.length = 0;
  40015. }
  40016. return mesh;
  40017. };
  40018. /**
  40019. * Digests the mesh and generates as many solid particles in the system as wanted.
  40020. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  40021. * Thus the particles generated from digest() have their property "positiion" yet set.
  40022. * @param mesh the mesh to be digested
  40023. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  40024. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  40025. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  40026. */
  40027. SolidParticleSystem.prototype.digest = function (mesh, options) {
  40028. var size = (options && options.facetNb) || 1;
  40029. var number = (options && options.number);
  40030. var delta = (options && options.delta) || 0;
  40031. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40032. var meshInd = mesh.getIndices();
  40033. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40034. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40035. var f = 0; // facet counter
  40036. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  40037. // compute size from number
  40038. if (number) {
  40039. number = (number > totalFacets) ? totalFacets : number;
  40040. size = Math.round(totalFacets / number);
  40041. delta = 0;
  40042. }
  40043. else {
  40044. size = (size > totalFacets) ? totalFacets : size;
  40045. }
  40046. var facetPos = []; // submesh positions
  40047. var facetInd = []; // submesh indices
  40048. var facetUV = []; // submesh UV
  40049. var facetCol = []; // submesh colors
  40050. var barycenter = BABYLON.Tmp.Vector3[0];
  40051. var rand;
  40052. var sizeO = size;
  40053. while (f < totalFacets) {
  40054. size = sizeO + Math.floor((1 + delta) * Math.random());
  40055. if (f > totalFacets - size) {
  40056. size = totalFacets - f;
  40057. }
  40058. // reset temp arrays
  40059. facetPos.length = 0;
  40060. facetInd.length = 0;
  40061. facetUV.length = 0;
  40062. facetCol.length = 0;
  40063. // iterate over "size" facets
  40064. var fi = 0;
  40065. for (var j = f * 3; j < (f + size) * 3; j++) {
  40066. facetInd.push(fi);
  40067. var i = meshInd[j];
  40068. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  40069. if (meshUV) {
  40070. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  40071. }
  40072. if (meshCol) {
  40073. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  40074. }
  40075. fi++;
  40076. }
  40077. // create a model shape for each single particle
  40078. var idx = this.nbParticles;
  40079. var shape = this._posToShape(facetPos);
  40080. var shapeUV = this._uvsToShapeUV(facetUV);
  40081. // compute the barycenter of the shape
  40082. var v;
  40083. for (v = 0; v < shape.length; v++) {
  40084. barycenter.addInPlace(shape[v]);
  40085. }
  40086. barycenter.scaleInPlace(1 / shape.length);
  40087. // shift the shape from its barycenter to the origin
  40088. for (v = 0; v < shape.length; v++) {
  40089. shape[v].subtractInPlace(barycenter);
  40090. }
  40091. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  40092. // add the particle in the SPS
  40093. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  40094. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  40095. // initialize the particle position
  40096. this.particles[this.nbParticles].position.addInPlace(barycenter);
  40097. this._index += shape.length;
  40098. idx++;
  40099. this.nbParticles++;
  40100. this._shapeCounter++;
  40101. f += size;
  40102. }
  40103. };
  40104. //reset copy
  40105. SolidParticleSystem.prototype._resetCopy = function () {
  40106. this._copy.position.x = 0;
  40107. this._copy.position.y = 0;
  40108. this._copy.position.z = 0;
  40109. this._copy.rotation.x = 0;
  40110. this._copy.rotation.y = 0;
  40111. this._copy.rotation.z = 0;
  40112. this._copy.quaternion = null;
  40113. this._copy.scale.x = 1;
  40114. this._copy.scale.y = 1;
  40115. this._copy.scale.z = 1;
  40116. this._copy.uvs.x = 0;
  40117. this._copy.uvs.y = 0;
  40118. this._copy.uvs.z = 1;
  40119. this._copy.uvs.w = 1;
  40120. this._copy.color = null;
  40121. };
  40122. // _meshBuilder : inserts the shape model in the global SPS mesh
  40123. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  40124. var i;
  40125. var u = 0;
  40126. var c = 0;
  40127. this._resetCopy();
  40128. if (options && options.positionFunction) {
  40129. options.positionFunction(this._copy, idx, idxInShape);
  40130. }
  40131. if (this._copy.quaternion) {
  40132. this._quaternion.x = this._copy.quaternion.x;
  40133. this._quaternion.y = this._copy.quaternion.y;
  40134. this._quaternion.z = this._copy.quaternion.z;
  40135. this._quaternion.w = this._copy.quaternion.w;
  40136. }
  40137. else {
  40138. this._yaw = this._copy.rotation.y;
  40139. this._pitch = this._copy.rotation.x;
  40140. this._roll = this._copy.rotation.z;
  40141. this._quaternionRotationYPR();
  40142. }
  40143. this._quaternionToRotationMatrix();
  40144. for (i = 0; i < shape.length; i++) {
  40145. this._vertex.x = shape[i].x;
  40146. this._vertex.y = shape[i].y;
  40147. this._vertex.z = shape[i].z;
  40148. if (options && options.vertexFunction) {
  40149. options.vertexFunction(this._copy, this._vertex, i);
  40150. }
  40151. this._vertex.x *= this._copy.scale.x;
  40152. this._vertex.y *= this._copy.scale.y;
  40153. this._vertex.z *= this._copy.scale.z;
  40154. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40155. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  40156. if (meshUV) {
  40157. 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);
  40158. u += 2;
  40159. }
  40160. if (this._copy.color) {
  40161. this._color = this._copy.color;
  40162. }
  40163. else if (meshCol && meshCol[c]) {
  40164. this._color.r = meshCol[c];
  40165. this._color.g = meshCol[c + 1];
  40166. this._color.b = meshCol[c + 2];
  40167. this._color.a = meshCol[c + 3];
  40168. }
  40169. else {
  40170. this._color.r = 1;
  40171. this._color.g = 1;
  40172. this._color.b = 1;
  40173. this._color.a = 1;
  40174. }
  40175. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  40176. c += 4;
  40177. }
  40178. for (i = 0; i < meshInd.length; i++) {
  40179. indices.push(p + meshInd[i]);
  40180. }
  40181. if (this._pickable) {
  40182. var nbfaces = meshInd.length / 3;
  40183. for (i = 0; i < nbfaces; i++) {
  40184. this.pickedParticles.push({ idx: idx, faceId: i });
  40185. }
  40186. }
  40187. };
  40188. // returns a shape array from positions array
  40189. SolidParticleSystem.prototype._posToShape = function (positions) {
  40190. var shape = [];
  40191. for (var i = 0; i < positions.length; i += 3) {
  40192. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  40193. }
  40194. return shape;
  40195. };
  40196. // returns a shapeUV array from a Vector4 uvs
  40197. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  40198. var shapeUV = [];
  40199. if (uvs) {
  40200. for (var i = 0; i < uvs.length; i++)
  40201. shapeUV.push(uvs[i]);
  40202. }
  40203. return shapeUV;
  40204. };
  40205. // adds a new particle object in the particles array
  40206. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  40207. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  40208. };
  40209. /**
  40210. * Adds some particles to the SPS from the model shape.
  40211. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  40212. * @param mesh any Mesh object that will be used as a model for the solid particles.
  40213. * @param nb the number of particles to be created from this model
  40214. * @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
  40215. */
  40216. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  40217. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40218. var meshInd = mesh.getIndices();
  40219. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40220. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40221. var shape = this._posToShape(meshPos);
  40222. var shapeUV = this._uvsToShapeUV(meshUV);
  40223. var posfunc = options ? options.positionFunction : null;
  40224. var vtxfunc = options ? options.vertexFunction : null;
  40225. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  40226. // particles
  40227. var idx = this.nbParticles;
  40228. for (var i = 0; i < nb; i++) {
  40229. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  40230. if (this._updatable) {
  40231. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  40232. }
  40233. this._index += shape.length;
  40234. idx++;
  40235. }
  40236. this.nbParticles += nb;
  40237. this._shapeCounter++;
  40238. return this._shapeCounter - 1;
  40239. };
  40240. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  40241. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  40242. this._resetCopy();
  40243. if (particle._model._positionFunction) {
  40244. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  40245. }
  40246. if (this._copy.quaternion) {
  40247. this._quaternion.x = this._copy.quaternion.x;
  40248. this._quaternion.y = this._copy.quaternion.y;
  40249. this._quaternion.z = this._copy.quaternion.z;
  40250. this._quaternion.w = this._copy.quaternion.w;
  40251. }
  40252. else {
  40253. this._yaw = this._copy.rotation.y;
  40254. this._pitch = this._copy.rotation.x;
  40255. this._roll = this._copy.rotation.z;
  40256. this._quaternionRotationYPR();
  40257. }
  40258. this._quaternionToRotationMatrix();
  40259. this._shape = particle._model._shape;
  40260. for (var pt = 0; pt < this._shape.length; pt++) {
  40261. this._vertex.x = this._shape[pt].x;
  40262. this._vertex.y = this._shape[pt].y;
  40263. this._vertex.z = this._shape[pt].z;
  40264. if (particle._model._vertexFunction) {
  40265. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  40266. }
  40267. this._vertex.x *= this._copy.scale.x;
  40268. this._vertex.y *= this._copy.scale.y;
  40269. this._vertex.z *= this._copy.scale.z;
  40270. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40271. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  40272. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  40273. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  40274. }
  40275. particle.position.x = 0;
  40276. particle.position.y = 0;
  40277. particle.position.z = 0;
  40278. particle.rotation.x = 0;
  40279. particle.rotation.y = 0;
  40280. particle.rotation.z = 0;
  40281. particle.quaternion = null;
  40282. particle.scale.x = 1;
  40283. particle.scale.y = 1;
  40284. particle.scale.z = 1;
  40285. };
  40286. /**
  40287. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  40288. */
  40289. SolidParticleSystem.prototype.rebuildMesh = function () {
  40290. for (var p = 0; p < this.particles.length; p++) {
  40291. this._rebuildParticle(this.particles[p]);
  40292. }
  40293. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40294. };
  40295. /**
  40296. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  40297. * This method calls updateParticle() for each particles of the SPS.
  40298. * For an animated SPS, it is usually called within the render loop.
  40299. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  40300. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  40301. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  40302. */
  40303. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  40304. if (start === void 0) { start = 0; }
  40305. if (end === void 0) { end = this.nbParticles - 1; }
  40306. if (update === void 0) { update = true; }
  40307. if (!this._updatable) {
  40308. return;
  40309. }
  40310. // custom beforeUpdate
  40311. this.beforeUpdateParticles(start, end, update);
  40312. this._cam_axisX.x = 1;
  40313. this._cam_axisX.y = 0;
  40314. this._cam_axisX.z = 0;
  40315. this._cam_axisY.x = 0;
  40316. this._cam_axisY.y = 1;
  40317. this._cam_axisY.z = 0;
  40318. this._cam_axisZ.x = 0;
  40319. this._cam_axisZ.y = 0;
  40320. this._cam_axisZ.z = 1;
  40321. // if the particles will always face the camera
  40322. if (this.billboard) {
  40323. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  40324. this._yaw = this.mesh.rotation.y;
  40325. this._pitch = this.mesh.rotation.x;
  40326. this._roll = this.mesh.rotation.z;
  40327. this._quaternionRotationYPR();
  40328. this._quaternionToRotationMatrix();
  40329. this._rotMatrix.invertToRef(this._invertMatrix);
  40330. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  40331. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  40332. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  40333. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  40334. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  40335. this._cam_axisY.normalize();
  40336. this._cam_axisX.normalize();
  40337. this._cam_axisZ.normalize();
  40338. }
  40339. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  40340. var idx = 0;
  40341. var index = 0;
  40342. var colidx = 0;
  40343. var colorIndex = 0;
  40344. var uvidx = 0;
  40345. var uvIndex = 0;
  40346. if (this._computeBoundingBox) {
  40347. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  40348. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  40349. }
  40350. // particle loop
  40351. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  40352. for (var p = start; p <= end; p++) {
  40353. this._particle = this.particles[p];
  40354. this._shape = this._particle._model._shape;
  40355. this._shapeUV = this._particle._model._shapeUV;
  40356. // call to custom user function to update the particle properties
  40357. this.updateParticle(this._particle);
  40358. // particle rotation matrix
  40359. if (this.billboard) {
  40360. this._particle.rotation.x = 0.0;
  40361. this._particle.rotation.y = 0.0;
  40362. }
  40363. if (this._computeParticleRotation) {
  40364. if (this._particle.quaternion) {
  40365. this._quaternion.x = this._particle.quaternion.x;
  40366. this._quaternion.y = this._particle.quaternion.y;
  40367. this._quaternion.z = this._particle.quaternion.z;
  40368. this._quaternion.w = this._particle.quaternion.w;
  40369. }
  40370. else {
  40371. this._yaw = this._particle.rotation.y;
  40372. this._pitch = this._particle.rotation.x;
  40373. this._roll = this._particle.rotation.z;
  40374. this._quaternionRotationYPR();
  40375. }
  40376. this._quaternionToRotationMatrix();
  40377. }
  40378. for (var pt = 0; pt < this._shape.length; pt++) {
  40379. idx = index + pt * 3;
  40380. colidx = colorIndex + pt * 4;
  40381. uvidx = uvIndex + pt * 2;
  40382. this._vertex.x = this._shape[pt].x;
  40383. this._vertex.y = this._shape[pt].y;
  40384. this._vertex.z = this._shape[pt].z;
  40385. if (this._computeParticleVertex) {
  40386. this.updateParticleVertex(this._particle, this._vertex, pt);
  40387. }
  40388. // positions
  40389. this._vertex.x *= this._particle.scale.x;
  40390. this._vertex.y *= this._particle.scale.y;
  40391. this._vertex.z *= this._particle.scale.z;
  40392. 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];
  40393. 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;
  40394. 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;
  40395. 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;
  40396. 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;
  40397. 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;
  40398. 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;
  40399. if (this._computeBoundingBox) {
  40400. if (this._positions32[idx] < this._minimum.x) {
  40401. this._minimum.x = this._positions32[idx];
  40402. }
  40403. if (this._positions32[idx] > this._maximum.x) {
  40404. this._maximum.x = this._positions32[idx];
  40405. }
  40406. if (this._positions32[idx + 1] < this._minimum.y) {
  40407. this._minimum.y = this._positions32[idx + 1];
  40408. }
  40409. if (this._positions32[idx + 1] > this._maximum.y) {
  40410. this._maximum.y = this._positions32[idx + 1];
  40411. }
  40412. if (this._positions32[idx + 2] < this._minimum.z) {
  40413. this._minimum.z = this._positions32[idx + 2];
  40414. }
  40415. if (this._positions32[idx + 2] > this._maximum.z) {
  40416. this._maximum.z = this._positions32[idx + 2];
  40417. }
  40418. }
  40419. // normals : if the particles can't be morphed then just rotate the normals
  40420. if (!this._computeParticleVertex && !this.billboard) {
  40421. this._normal.x = this._fixedNormal32[idx];
  40422. this._normal.y = this._fixedNormal32[idx + 1];
  40423. this._normal.z = this._fixedNormal32[idx + 2];
  40424. 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];
  40425. 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;
  40426. 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;
  40427. 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;
  40428. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  40429. 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;
  40430. 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;
  40431. }
  40432. if (this._computeParticleColor) {
  40433. this._colors32[colidx] = this._particle.color.r;
  40434. this._colors32[colidx + 1] = this._particle.color.g;
  40435. this._colors32[colidx + 2] = this._particle.color.b;
  40436. this._colors32[colidx + 3] = this._particle.color.a;
  40437. }
  40438. if (this._computeParticleTexture) {
  40439. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40440. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40441. }
  40442. }
  40443. index = idx + 3;
  40444. colorIndex = colidx + 4;
  40445. uvIndex = uvidx + 2;
  40446. }
  40447. if (update) {
  40448. if (this._computeParticleColor) {
  40449. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  40450. }
  40451. if (this._computeParticleTexture) {
  40452. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  40453. }
  40454. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40455. if (!this.mesh.areNormalsFrozen) {
  40456. if (this._computeParticleVertex || this.billboard) {
  40457. // recompute the normals only if the particles can be morphed, update then the normal reference array
  40458. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  40459. for (var i = 0; i < this._normals32.length; i++) {
  40460. this._fixedNormal32[i] = this._normals32[i];
  40461. }
  40462. }
  40463. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  40464. }
  40465. }
  40466. if (this._computeBoundingBox) {
  40467. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  40468. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  40469. }
  40470. this.afterUpdateParticles(start, end, update);
  40471. };
  40472. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  40473. this._halfroll = this._roll * 0.5;
  40474. this._halfpitch = this._pitch * 0.5;
  40475. this._halfyaw = this._yaw * 0.5;
  40476. this._sinRoll = Math.sin(this._halfroll);
  40477. this._cosRoll = Math.cos(this._halfroll);
  40478. this._sinPitch = Math.sin(this._halfpitch);
  40479. this._cosPitch = Math.cos(this._halfpitch);
  40480. this._sinYaw = Math.sin(this._halfyaw);
  40481. this._cosYaw = Math.cos(this._halfyaw);
  40482. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  40483. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  40484. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  40485. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  40486. };
  40487. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  40488. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  40489. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  40490. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  40491. this._rotMatrix.m[3] = 0;
  40492. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  40493. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  40494. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  40495. this._rotMatrix.m[7] = 0;
  40496. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  40497. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  40498. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  40499. this._rotMatrix.m[11] = 0;
  40500. this._rotMatrix.m[12] = 0;
  40501. this._rotMatrix.m[13] = 0;
  40502. this._rotMatrix.m[14] = 0;
  40503. this._rotMatrix.m[15] = 1.0;
  40504. };
  40505. /**
  40506. * Disposes the SPS
  40507. */
  40508. SolidParticleSystem.prototype.dispose = function () {
  40509. this.mesh.dispose();
  40510. this.vars = null;
  40511. // drop references to internal big arrays for the GC
  40512. this._positions = null;
  40513. this._indices = null;
  40514. this._normals = null;
  40515. this._uvs = null;
  40516. this._colors = null;
  40517. this._positions32 = null;
  40518. this._normals32 = null;
  40519. this._fixedNormal32 = null;
  40520. this._uvs32 = null;
  40521. this._colors32 = null;
  40522. this.pickedParticles = null;
  40523. };
  40524. /**
  40525. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  40526. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40527. */
  40528. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  40529. if (!this._isVisibilityBoxLocked) {
  40530. this.mesh.refreshBoundingInfo();
  40531. }
  40532. };
  40533. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  40534. * @param size the size (float) of the visibility box
  40535. * note : this doesn't lock the SPS mesh bounding box.
  40536. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40537. */
  40538. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  40539. var vis = size / 2;
  40540. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  40541. };
  40542. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  40543. // getter and setter
  40544. /**
  40545. * True if the SPS is set as always visible
  40546. */
  40547. get: function () {
  40548. return this._alwaysVisible;
  40549. },
  40550. /**
  40551. * Sets the SPS as always visible or not
  40552. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40553. */
  40554. set: function (val) {
  40555. this._alwaysVisible = val;
  40556. this.mesh.alwaysSelectAsActiveMesh = val;
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  40562. /**
  40563. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  40564. */
  40565. get: function () {
  40566. return this._isVisibilityBoxLocked;
  40567. },
  40568. /**
  40569. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  40570. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40571. */
  40572. set: function (val) {
  40573. this._isVisibilityBoxLocked = val;
  40574. this.mesh.getBoundingInfo().isLocked = val;
  40575. },
  40576. enumerable: true,
  40577. configurable: true
  40578. });
  40579. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  40580. // getters
  40581. get: function () {
  40582. return this._computeParticleRotation;
  40583. },
  40584. // Optimizer setters
  40585. /**
  40586. * Tells to setParticles() to compute the particle rotations or not.
  40587. * Default value : true. The SPS is faster when it's set to false.
  40588. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  40589. */
  40590. set: function (val) {
  40591. this._computeParticleRotation = val;
  40592. },
  40593. enumerable: true,
  40594. configurable: true
  40595. });
  40596. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  40597. get: function () {
  40598. return this._computeParticleColor;
  40599. },
  40600. /**
  40601. * Tells to setParticles() to compute the particle colors or not.
  40602. * Default value : true. The SPS is faster when it's set to false.
  40603. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  40604. */
  40605. set: function (val) {
  40606. this._computeParticleColor = val;
  40607. },
  40608. enumerable: true,
  40609. configurable: true
  40610. });
  40611. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  40612. get: function () {
  40613. return this._computeParticleTexture;
  40614. },
  40615. /**
  40616. * Tells to setParticles() to compute the particle textures or not.
  40617. * Default value : true. The SPS is faster when it's set to false.
  40618. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  40619. */
  40620. set: function (val) {
  40621. this._computeParticleTexture = val;
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  40627. get: function () {
  40628. return this._computeParticleVertex;
  40629. },
  40630. /**
  40631. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  40632. * Default value : false. The SPS is faster when it's set to false.
  40633. * Note : the particle custom vertex positions aren't stored values.
  40634. */
  40635. set: function (val) {
  40636. this._computeParticleVertex = val;
  40637. },
  40638. enumerable: true,
  40639. configurable: true
  40640. });
  40641. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  40642. get: function () {
  40643. return this._computeBoundingBox;
  40644. },
  40645. /**
  40646. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  40647. */
  40648. set: function (val) {
  40649. this._computeBoundingBox = val;
  40650. },
  40651. enumerable: true,
  40652. configurable: true
  40653. });
  40654. // =======================================================================
  40655. // Particle behavior logic
  40656. // these following methods may be overwritten by the user to fit his needs
  40657. /**
  40658. * This function does nothing. It may be overwritten to set all the particles first values.
  40659. * The SPS doesn't call this function, you may have to call it by your own.
  40660. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40661. */
  40662. SolidParticleSystem.prototype.initParticles = function () {
  40663. };
  40664. /**
  40665. * This function does nothing. It may be overwritten to recycle a particle.
  40666. * The SPS doesn't call this function, you may have to call it by your own.
  40667. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40668. */
  40669. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  40670. return particle;
  40671. };
  40672. /**
  40673. * Updates a particle : this function should be overwritten by the user.
  40674. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  40675. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40676. * ex : just set a particle position or velocity and recycle conditions
  40677. */
  40678. SolidParticleSystem.prototype.updateParticle = function (particle) {
  40679. return particle;
  40680. };
  40681. /**
  40682. * Updates a vertex of a particle : it can be overwritten by the user.
  40683. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  40684. * @param particle the current particle
  40685. * @param vertex the current index of the current particle
  40686. * @param pt the index of the current vertex in the particle shape
  40687. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  40688. * ex : just set a vertex particle position
  40689. */
  40690. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  40691. return vertex;
  40692. };
  40693. /**
  40694. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  40695. * This does nothing and may be overwritten by the user.
  40696. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40697. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40698. * @param update the boolean update value actually passed to setParticles()
  40699. */
  40700. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  40701. };
  40702. /**
  40703. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  40704. * This will be passed three parameters.
  40705. * This does nothing and may be overwritten by the user.
  40706. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40707. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40708. * @param update the boolean update value actually passed to setParticles()
  40709. */
  40710. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  40711. };
  40712. return SolidParticleSystem;
  40713. })();
  40714. BABYLON.SolidParticleSystem = SolidParticleSystem;
  40715. })(BABYLON || (BABYLON = {}));
  40716. var BABYLON;
  40717. (function (BABYLON) {
  40718. var Internals;
  40719. (function (Internals) {
  40720. var FileFaceOrientation = (function () {
  40721. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40722. this.name = name;
  40723. this.worldAxisForNormal = worldAxisForNormal;
  40724. this.worldAxisForFileX = worldAxisForFileX;
  40725. this.worldAxisForFileY = worldAxisForFileY;
  40726. }
  40727. return FileFaceOrientation;
  40728. })();
  40729. ;
  40730. /**
  40731. * Helper class dealing with the extraction of spherical polynomial dataArray
  40732. * from a cube map.
  40733. */
  40734. var CubeMapToSphericalPolynomialTools = (function () {
  40735. function CubeMapToSphericalPolynomialTools() {
  40736. }
  40737. /**
  40738. * Converts a cubemap to the according Spherical Polynomial data.
  40739. * This extracts the first 3 orders only as they are the only one used in the lighting.
  40740. *
  40741. * @param cubeInfo The Cube map to extract the information from.
  40742. * @return The Spherical Polynomial data.
  40743. */
  40744. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40745. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40746. var totalSolidAngle = 0.0;
  40747. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40748. var du = 2.0 / cubeInfo.size;
  40749. var dv = du;
  40750. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40751. var minUV = du * 0.5 - 1.0;
  40752. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40753. var fileFace = this.FileFaces[faceIndex];
  40754. var dataArray = cubeInfo[fileFace.name];
  40755. var v = minUV;
  40756. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40757. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40758. // Because SP is still linear, so summation is fine in that basis.
  40759. for (var y = 0; y < cubeInfo.size; y++) {
  40760. var u = minUV;
  40761. for (var x = 0; x < cubeInfo.size; x++) {
  40762. // World direction (not normalised)
  40763. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40764. worldDirection.normalize();
  40765. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40766. if (1) {
  40767. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40768. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40769. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40770. var color = new BABYLON.Color3(r, g, b);
  40771. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40772. }
  40773. else {
  40774. if (faceIndex == 0) {
  40775. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40776. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40777. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40778. }
  40779. else if (faceIndex == 1) {
  40780. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40781. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40782. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40783. }
  40784. else if (faceIndex == 2) {
  40785. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40786. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40787. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40788. }
  40789. else if (faceIndex == 3) {
  40790. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40791. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40792. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40793. }
  40794. else if (faceIndex == 4) {
  40795. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40796. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40797. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40798. }
  40799. else if (faceIndex == 5) {
  40800. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40801. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40802. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40803. }
  40804. 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]);
  40805. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40806. }
  40807. totalSolidAngle += deltaSolidAngle;
  40808. u += du;
  40809. }
  40810. v += dv;
  40811. }
  40812. }
  40813. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40814. var correction = correctSolidAngle / totalSolidAngle;
  40815. sphericalHarmonics.scale(correction);
  40816. // Additionally scale by pi -- audit needed
  40817. sphericalHarmonics.scale(1.0 / Math.PI);
  40818. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40819. };
  40820. CubeMapToSphericalPolynomialTools.FileFaces = [
  40821. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40822. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40823. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40824. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40825. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40826. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40827. ];
  40828. return CubeMapToSphericalPolynomialTools;
  40829. })();
  40830. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40831. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40832. })(BABYLON || (BABYLON = {}));
  40833. var BABYLON;
  40834. (function (BABYLON) {
  40835. var Internals;
  40836. (function (Internals) {
  40837. /**
  40838. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  40839. */
  40840. var PanoramaToCubeMapTools = (function () {
  40841. function PanoramaToCubeMapTools() {
  40842. }
  40843. /**
  40844. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  40845. *
  40846. * @param float32Array The source data.
  40847. * @param inputWidth The width of the input panorama.
  40848. * @param inputhHeight The height of the input panorama.
  40849. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  40850. * @return The cubemap data
  40851. */
  40852. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40853. if (!float32Array) {
  40854. throw "ConvertPanoramaToCubemap: input cannot be null";
  40855. }
  40856. if (float32Array.length != inputWidth * inputHeight * 3) {
  40857. throw "ConvertPanoramaToCubemap: input size is wrong";
  40858. }
  40859. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40860. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40861. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40862. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40863. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40864. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40865. return {
  40866. front: textureFront,
  40867. back: textureBack,
  40868. left: textureLeft,
  40869. right: textureRight,
  40870. up: textureUp,
  40871. down: textureDown,
  40872. size: size
  40873. };
  40874. };
  40875. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40876. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40877. var textureArray = new Float32Array(buffer);
  40878. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40879. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40880. var dy = 1 / texSize;
  40881. var fy = 0;
  40882. for (var y = 0; y < texSize; y++) {
  40883. var xv1 = faceData[0];
  40884. var xv2 = faceData[2];
  40885. for (var x = 0; x < texSize; x++) {
  40886. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40887. v.normalize();
  40888. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40889. // 3 channels per pixels
  40890. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40891. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40892. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40893. xv1 = xv1.add(rotDX1);
  40894. xv2 = xv2.add(rotDX2);
  40895. }
  40896. fy += dy;
  40897. }
  40898. return textureArray;
  40899. };
  40900. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  40901. var theta = Math.atan2(vDir.z, vDir.x);
  40902. var phi = Math.acos(vDir.y);
  40903. while (theta < -Math.PI)
  40904. theta += 2 * Math.PI;
  40905. while (theta > Math.PI)
  40906. theta -= 2 * Math.PI;
  40907. var dx = theta / Math.PI;
  40908. var dy = phi / Math.PI;
  40909. // recenter.
  40910. dx = dx * 0.5 + 0.5;
  40911. var px = Math.round(dx * inputWidth);
  40912. if (px < 0)
  40913. px = 0;
  40914. else if (px >= inputWidth)
  40915. px = inputWidth - 1;
  40916. var py = Math.round(dy * inputHeight);
  40917. if (py < 0)
  40918. py = 0;
  40919. else if (py >= inputHeight)
  40920. py = inputHeight - 1;
  40921. var inputY = (inputHeight - py - 1);
  40922. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  40923. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  40924. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  40925. return {
  40926. r: r,
  40927. g: g,
  40928. b: b
  40929. };
  40930. };
  40931. PanoramaToCubeMapTools.FACE_FRONT = [
  40932. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40933. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40934. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40935. new BABYLON.Vector3(1.0, 1.0, -1.0)
  40936. ];
  40937. PanoramaToCubeMapTools.FACE_BACK = [
  40938. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40939. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40940. new BABYLON.Vector3(1.0, 1.0, 1.0),
  40941. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  40942. ];
  40943. PanoramaToCubeMapTools.FACE_RIGHT = [
  40944. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40945. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40946. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40947. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40948. ];
  40949. PanoramaToCubeMapTools.FACE_LEFT = [
  40950. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40951. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40952. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40953. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  40954. ];
  40955. PanoramaToCubeMapTools.FACE_DOWN = [
  40956. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40957. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40958. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40959. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40960. ];
  40961. PanoramaToCubeMapTools.FACE_UP = [
  40962. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40963. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40964. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40965. new BABYLON.Vector3(1.0, -1.0, -1.0)
  40966. ];
  40967. return PanoramaToCubeMapTools;
  40968. })();
  40969. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  40970. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40971. })(BABYLON || (BABYLON = {}));
  40972. var BABYLON;
  40973. (function (BABYLON) {
  40974. var Internals;
  40975. (function (Internals) {
  40976. ;
  40977. /**
  40978. * This groups tools to convert HDR texture to native colors array.
  40979. */
  40980. var HDRTools = (function () {
  40981. function HDRTools() {
  40982. }
  40983. HDRTools.Ldexp = function (mantissa, exponent) {
  40984. if (exponent > 1023) {
  40985. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  40986. }
  40987. if (exponent < -1074) {
  40988. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  40989. }
  40990. return mantissa * Math.pow(2, exponent);
  40991. };
  40992. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  40993. if (exponent > 0) {
  40994. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  40995. float32array[index + 0] = red * exponent;
  40996. float32array[index + 1] = green * exponent;
  40997. float32array[index + 2] = blue * exponent;
  40998. }
  40999. else {
  41000. float32array[index + 0] = 0;
  41001. float32array[index + 1] = 0;
  41002. float32array[index + 2] = 0;
  41003. }
  41004. };
  41005. HDRTools.readStringLine = function (uint8array, startIndex) {
  41006. var line = "";
  41007. var character = "";
  41008. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  41009. character = String.fromCharCode(uint8array[i]);
  41010. if (character == "\n") {
  41011. break;
  41012. }
  41013. line += character;
  41014. }
  41015. return line;
  41016. };
  41017. /**
  41018. * Reads header information from an RGBE texture stored in a native array.
  41019. * More information on this format are available here:
  41020. * https://en.wikipedia.org/wiki/RGBE_image_format
  41021. *
  41022. * @param uint8array The binary file stored in native array.
  41023. * @return The header information.
  41024. */
  41025. HDRTools.RGBE_ReadHeader = function (uint8array) {
  41026. var height = 0;
  41027. var width = 0;
  41028. var line = this.readStringLine(uint8array, 0);
  41029. if (line[0] != '#' || line[1] != '?') {
  41030. throw "Bad HDR Format.";
  41031. }
  41032. var endOfHeader = false;
  41033. var findFormat = false;
  41034. var lineIndex = 0;
  41035. do {
  41036. lineIndex += (line.length + 1);
  41037. line = this.readStringLine(uint8array, lineIndex);
  41038. if (line == "FORMAT=32-bit_rle_rgbe") {
  41039. findFormat = true;
  41040. }
  41041. else if (line.length == 0) {
  41042. endOfHeader = true;
  41043. }
  41044. } while (!endOfHeader);
  41045. if (!findFormat) {
  41046. throw "HDR Bad header format, unsupported FORMAT";
  41047. }
  41048. lineIndex += (line.length + 1);
  41049. line = this.readStringLine(uint8array, lineIndex);
  41050. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  41051. var match = sizeRegexp.exec(line);
  41052. // TODO. Support +Y and -X if needed.
  41053. if (match.length < 3) {
  41054. throw "HDR Bad header format, no size";
  41055. }
  41056. width = parseInt(match[2]);
  41057. height = parseInt(match[1]);
  41058. if (width < 8 || width > 0x7fff) {
  41059. throw "HDR Bad header format, unsupported size";
  41060. }
  41061. lineIndex += (line.length + 1);
  41062. return {
  41063. height: height,
  41064. width: width,
  41065. dataPosition: lineIndex
  41066. };
  41067. };
  41068. /**
  41069. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  41070. * This RGBE texture needs to store the information as a panorama.
  41071. *
  41072. * More information on this format are available here:
  41073. * https://en.wikipedia.org/wiki/RGBE_image_format
  41074. *
  41075. * @param buffer The binary file stored in an array buffer.
  41076. * @param size The expected size of the extracted cubemap.
  41077. * @return The Cube Map information.
  41078. */
  41079. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  41080. var uint8array = new Uint8Array(buffer);
  41081. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  41082. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  41083. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  41084. return cubeMapData;
  41085. };
  41086. /**
  41087. * Returns the pixels data extracted from an RGBE texture.
  41088. * This pixels will be stored left to right up to down in the R G B order in one array.
  41089. *
  41090. * More information on this format are available here:
  41091. * https://en.wikipedia.org/wiki/RGBE_image_format
  41092. *
  41093. * @param uint8array The binary file stored in an array buffer.
  41094. * @param hdrInfo The header information of the file.
  41095. * @return The pixels data in RGB right to left up to down order.
  41096. */
  41097. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  41098. // Keep for multi format supports.
  41099. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  41100. };
  41101. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  41102. var num_scanlines = hdrInfo.height;
  41103. var scanline_width = hdrInfo.width;
  41104. var a, b, c, d, count;
  41105. var dataIndex = hdrInfo.dataPosition;
  41106. var index = 0, endIndex = 0, i = 0;
  41107. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  41108. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  41109. // 3 channels of 4 bytes per pixel in float.
  41110. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  41111. var resultArray = new Float32Array(resultBuffer);
  41112. // read in each successive scanline
  41113. while (num_scanlines > 0) {
  41114. a = uint8array[dataIndex++];
  41115. b = uint8array[dataIndex++];
  41116. c = uint8array[dataIndex++];
  41117. d = uint8array[dataIndex++];
  41118. if (a != 2 || b != 2 || (c & 0x80)) {
  41119. // this file is not run length encoded
  41120. throw "HDR Bad header format, not RLE";
  41121. }
  41122. if (((c << 8) | d) != scanline_width) {
  41123. throw "HDR Bad header format, wrong scan line width";
  41124. }
  41125. index = 0;
  41126. // read each of the four channels for the scanline into the buffer
  41127. for (i = 0; i < 4; i++) {
  41128. endIndex = (i + 1) * scanline_width;
  41129. while (index < endIndex) {
  41130. a = uint8array[dataIndex++];
  41131. b = uint8array[dataIndex++];
  41132. if (a > 128) {
  41133. // a run of the same value
  41134. count = a - 128;
  41135. if ((count == 0) || (count > endIndex - index)) {
  41136. throw "HDR Bad Format, bad scanline data (run)";
  41137. }
  41138. while (count-- > 0) {
  41139. scanLineArray[index++] = b;
  41140. }
  41141. }
  41142. else {
  41143. // a non-run
  41144. count = a;
  41145. if ((count == 0) || (count > endIndex - index)) {
  41146. throw "HDR Bad Format, bad scanline data (non-run)";
  41147. }
  41148. scanLineArray[index++] = b;
  41149. if (--count > 0) {
  41150. for (var j = 0; j < count; j++) {
  41151. scanLineArray[index++] = uint8array[dataIndex++];
  41152. }
  41153. }
  41154. }
  41155. }
  41156. }
  41157. // now convert data from buffer into floats
  41158. for (i = 0; i < scanline_width; i++) {
  41159. a = scanLineArray[i];
  41160. b = scanLineArray[i + scanline_width];
  41161. c = scanLineArray[i + 2 * scanline_width];
  41162. d = scanLineArray[i + 3 * scanline_width];
  41163. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  41164. }
  41165. num_scanlines--;
  41166. }
  41167. return resultArray;
  41168. };
  41169. return HDRTools;
  41170. })();
  41171. Internals.HDRTools = HDRTools;
  41172. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41173. })(BABYLON || (BABYLON = {}));
  41174. //_______________________________________________________________
  41175. // Extracted from CubeMapGen:
  41176. // https://code.google.com/archive/p/cubemapgen/
  41177. //
  41178. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  41179. //_______________________________________________________________
  41180. var BABYLON;
  41181. (function (BABYLON) {
  41182. var Internals;
  41183. (function (Internals) {
  41184. /**
  41185. * The bounding box information used during the conversion process.
  41186. */
  41187. var CMGBoundinBox = (function () {
  41188. function CMGBoundinBox() {
  41189. this.min = new BABYLON.Vector3(0, 0, 0);
  41190. this.max = new BABYLON.Vector3(0, 0, 0);
  41191. this.clear();
  41192. }
  41193. CMGBoundinBox.prototype.clear = function () {
  41194. this.min.x = CMGBoundinBox.MAX;
  41195. this.min.y = CMGBoundinBox.MAX;
  41196. this.min.z = CMGBoundinBox.MAX;
  41197. this.max.x = CMGBoundinBox.MIN;
  41198. this.max.y = CMGBoundinBox.MIN;
  41199. this.max.z = CMGBoundinBox.MIN;
  41200. };
  41201. CMGBoundinBox.prototype.augment = function (x, y, z) {
  41202. this.min.x = Math.min(this.min.x, x);
  41203. this.min.y = Math.min(this.min.y, y);
  41204. this.min.z = Math.min(this.min.z, z);
  41205. this.max.x = Math.max(this.max.x, x);
  41206. this.max.y = Math.max(this.max.y, y);
  41207. this.max.z = Math.max(this.max.z, z);
  41208. };
  41209. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  41210. this.min.x = Math.max(this.min.x, x);
  41211. this.min.y = Math.max(this.min.y, y);
  41212. this.min.z = Math.max(this.min.z, z);
  41213. };
  41214. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  41215. this.max.x = Math.min(this.max.x, x);
  41216. this.max.y = Math.min(this.max.y, y);
  41217. this.max.z = Math.min(this.max.z, z);
  41218. };
  41219. CMGBoundinBox.prototype.empty = function () {
  41220. if ((this.min.x > this.max.y) ||
  41221. (this.min.y > this.max.y) ||
  41222. (this.min.z > this.max.y)) {
  41223. return true;
  41224. }
  41225. else {
  41226. return false;
  41227. }
  41228. };
  41229. CMGBoundinBox.MAX = Number.MAX_VALUE;
  41230. CMGBoundinBox.MIN = Number.MIN_VALUE;
  41231. return CMGBoundinBox;
  41232. })();
  41233. /**
  41234. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  41235. * required by the glossinees of a material.
  41236. *
  41237. * This only supports the cosine drop power as well as Warp fixup generation method.
  41238. *
  41239. * This is using the process from CubeMapGen described here:
  41240. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  41241. */
  41242. var PMREMGenerator = (function () {
  41243. /**
  41244. * Constructor of the generator.
  41245. *
  41246. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  41247. * @param inputSize The size of the cubemap faces
  41248. * @param outputSize The size of the output cubemap faces
  41249. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  41250. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  41251. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  41252. * @param specularPower The max specular level of the desired cubemap
  41253. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  41254. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  41255. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  41256. */
  41257. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  41258. this.input = input;
  41259. this.inputSize = inputSize;
  41260. this.outputSize = outputSize;
  41261. this.maxNumMipLevels = maxNumMipLevels;
  41262. this.numChannels = numChannels;
  41263. this.isFloat = isFloat;
  41264. this.specularPower = specularPower;
  41265. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  41266. this.excludeBase = excludeBase;
  41267. this.fixup = fixup;
  41268. this._outputSurface = [];
  41269. this._numMipLevels = 0;
  41270. }
  41271. /**
  41272. * Launches the filter process and return the result.
  41273. *
  41274. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  41275. */
  41276. PMREMGenerator.prototype.filterCubeMap = function () {
  41277. // Init cubemap processor
  41278. this.init();
  41279. // Filters the cubemap
  41280. this.filterCubeMapMipChain();
  41281. // Returns the filtered mips.
  41282. return this._outputSurface;
  41283. };
  41284. PMREMGenerator.prototype.init = function () {
  41285. var i;
  41286. var j;
  41287. var mipLevelSize;
  41288. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  41289. if (this.maxNumMipLevels == 0) {
  41290. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  41291. }
  41292. //first miplevel size
  41293. mipLevelSize = this.outputSize;
  41294. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  41295. for (j = 0; j < this.maxNumMipLevels; j++) {
  41296. this._outputSurface.length++;
  41297. this._outputSurface[j] = [];
  41298. //Iterate over faces for output images
  41299. for (i = 0; i < 6; i++) {
  41300. this._outputSurface[j].length++;
  41301. // Initializes a new array for the output.
  41302. if (this.isFloat) {
  41303. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  41304. }
  41305. else {
  41306. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  41307. }
  41308. }
  41309. //next mip level is half size
  41310. mipLevelSize >>= 1;
  41311. this._numMipLevels++;
  41312. //terminate if mip chain becomes too small
  41313. if (mipLevelSize == 0) {
  41314. this.maxNumMipLevels = j;
  41315. return;
  41316. }
  41317. }
  41318. };
  41319. //--------------------------------------------------------------------------------------
  41320. //Cube map filtering and mip chain generation.
  41321. // the cube map filtereing is specified using a number of parameters:
  41322. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  41323. // indicates the region of the hemisphere to filter over for each tap.
  41324. //
  41325. // Note that the top mip level is also a filtered version of the original input images
  41326. // as well in order to create mip chains for diffuse environment illumination.
  41327. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  41328. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  41329. //
  41330. // Then the mip angle used to genreate the next level of the mip chain from the first level
  41331. // is a_InitialMipAngle
  41332. //
  41333. // The angle for the subsequent levels of the mip chain are specified by their parents
  41334. // filtering angle and a per-level scale and bias
  41335. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  41336. //
  41337. //--------------------------------------------------------------------------------------
  41338. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  41339. // First, take count of the lighting model to modify SpecularPower
  41340. // 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;
  41341. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  41342. //Cone angle start (for generating subsequent mip levels)
  41343. var currentSpecularPower = this.specularPower;
  41344. //Build filter lookup tables based on the source miplevel size
  41345. this.precomputeFilterLookupTables(this.inputSize);
  41346. // Note that we need to filter the first level before generating mipmap
  41347. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  41348. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  41349. // TODO : Write a function to copy and scale the base mipmap in output
  41350. // I am just lazy here and just put a high specular power value, and do some if.
  41351. if (this.excludeBase && (levelIndex == 0)) {
  41352. // 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).
  41353. currentSpecularPower = 100000.0;
  41354. }
  41355. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  41356. var srcCubeImage = this.input;
  41357. var dstCubeImage = this._outputSurface[levelIndex];
  41358. var dstSize = this.outputSize >> levelIndex;
  41359. // Compute required angle.
  41360. var angle = this.getBaseFilterAngle(currentSpecularPower);
  41361. // filter cube surfaces
  41362. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  41363. // fix seams
  41364. if (this.fixup) {
  41365. this.fixupCubeEdges(dstCubeImage, dstSize);
  41366. }
  41367. // Decrease the specular power to generate the mipmap chain
  41368. // TODO : Use another method for Exclude (see first comment at start of the function
  41369. if (this.excludeBase && (levelIndex == 0)) {
  41370. currentSpecularPower = this.specularPower;
  41371. }
  41372. currentSpecularPower *= this.cosinePowerDropPerMip;
  41373. }
  41374. };
  41375. //--------------------------------------------------------------------------------------
  41376. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  41377. // It allow to optimize the texel to access base on the specular power.
  41378. //--------------------------------------------------------------------------------------
  41379. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  41380. // We want to find the alpha such that:
  41381. // cos(alpha)^cosinePower = epsilon
  41382. // That's: acos(epsilon^(1/cosinePower))
  41383. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  41384. var angle = 180.0;
  41385. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  41386. angle *= 180.0 / Math.PI; // Convert to degree
  41387. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  41388. return angle;
  41389. };
  41390. //--------------------------------------------------------------------------------------
  41391. //Builds the following lookup tables prior to filtering:
  41392. // -normalizer cube map
  41393. // -tap weight lookup table
  41394. //
  41395. //--------------------------------------------------------------------------------------
  41396. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  41397. var srcTexelAngle;
  41398. var iCubeFace;
  41399. //clear pre-existing normalizer cube map
  41400. this._normCubeMap = [];
  41401. //Normalized vectors per cubeface and per-texel solid angle
  41402. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  41403. };
  41404. //--------------------------------------------------------------------------------------
  41405. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  41406. //
  41407. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  41408. //
  41409. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  41410. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  41411. // below
  41412. //--------------------------------------------------------------------------------------
  41413. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  41414. var iCubeFace;
  41415. var u;
  41416. var v;
  41417. //iterate over cube faces
  41418. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41419. //First three channels for norm cube, and last channel for solid angle
  41420. this._normCubeMap.push(new Float32Array(size * size * 4));
  41421. //fast texture walk, build normalizer cube map
  41422. var facesData = this.input[iCubeFace];
  41423. for (v = 0; v < size; v++) {
  41424. for (u = 0; u < size; u++) {
  41425. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  41426. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  41427. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  41428. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  41429. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  41430. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  41431. }
  41432. }
  41433. }
  41434. };
  41435. //--------------------------------------------------------------------------------------
  41436. // Convert cubemap face texel coordinates and face idx to 3D vector
  41437. // note the U and V coords are integer coords and range from 0 to size-1
  41438. // this routine can be used to generate a normalizer cube map
  41439. //--------------------------------------------------------------------------------------
  41440. // SL BEGIN
  41441. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  41442. var nvcU;
  41443. var nvcV;
  41444. var tempVec;
  41445. // Change from original AMD code
  41446. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  41447. // + 0.5f is for texel center addressing
  41448. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  41449. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  41450. // warp fixup
  41451. if (fixup && size > 1) {
  41452. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  41453. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  41454. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  41455. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  41456. }
  41457. // Get current vector
  41458. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  41459. // U contribution
  41460. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  41461. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  41462. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  41463. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  41464. // V contribution and Sum
  41465. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  41466. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  41467. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  41468. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  41469. //add face axis
  41470. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  41471. PMREMGenerator._vectorTemp.x += faceAxis[0];
  41472. PMREMGenerator._vectorTemp.y += faceAxis[1];
  41473. PMREMGenerator._vectorTemp.z += faceAxis[2];
  41474. //normalize vector
  41475. PMREMGenerator._vectorTemp.normalize();
  41476. return PMREMGenerator._vectorTemp;
  41477. };
  41478. //--------------------------------------------------------------------------------------
  41479. // Convert 3D vector to cubemap face texel coordinates and face idx
  41480. // note the U and V coords are integer coords and range from 0 to size-1
  41481. // this routine can be used to generate a normalizer cube map
  41482. //
  41483. // returns face IDX and texel coords
  41484. //--------------------------------------------------------------------------------------
  41485. // SL BEGIN
  41486. /*
  41487. Mapping Texture Coordinates to Cube Map Faces
  41488. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  41489. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  41490. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  41491. map arrangement in Pixar's RenderMan package.
  41492. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  41493. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  41494. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  41495. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  41496. the major axis direction). The target column in the table below explains how the major axis direction
  41497. maps to the 2D image of a particular cube map target.
  41498. major axis
  41499. direction target sc tc ma
  41500. ---------- --------------------------------- --- --- ---
  41501. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  41502. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  41503. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  41504. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  41505. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  41506. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  41507. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  41508. an updated (s,t) is calculated as follows
  41509. s = ( sc/|ma| + 1 ) / 2
  41510. t = ( tc/|ma| + 1 ) / 2
  41511. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  41512. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  41513. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  41514. */
  41515. // Note this method return U and V in range from 0 to size-1
  41516. // SL END
  41517. // Store the information in vector3 for convenience (faceindex, u, v)
  41518. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  41519. var maxCoord;
  41520. var faceIdx;
  41521. //absolute value 3
  41522. var absX = Math.abs(x);
  41523. var absY = Math.abs(y);
  41524. var absZ = Math.abs(z);
  41525. if (absX >= absY && absX >= absZ) {
  41526. maxCoord = absX;
  41527. if (x >= 0) {
  41528. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  41529. }
  41530. else {
  41531. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  41532. }
  41533. }
  41534. else if (absY >= absX && absY >= absZ) {
  41535. maxCoord = absY;
  41536. if (y >= 0) {
  41537. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  41538. }
  41539. else {
  41540. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  41541. }
  41542. }
  41543. else {
  41544. maxCoord = absZ;
  41545. if (z >= 0) {
  41546. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  41547. }
  41548. else {
  41549. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  41550. }
  41551. }
  41552. //divide through by max coord so face vector lies on cube face
  41553. var scale = 1 / maxCoord;
  41554. x *= scale;
  41555. y *= scale;
  41556. z *= scale;
  41557. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  41558. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  41559. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  41560. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  41561. // Modify original AMD code to return value from 0 to Size - 1
  41562. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  41563. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  41564. PMREMGenerator._vectorTemp.x = faceIdx;
  41565. PMREMGenerator._vectorTemp.y = u;
  41566. PMREMGenerator._vectorTemp.z = v;
  41567. return PMREMGenerator._vectorTemp;
  41568. };
  41569. //--------------------------------------------------------------------------------------
  41570. //Original code from Ignacio CastaÒo
  41571. // This formula is from Manne ÷hrstrˆm's thesis.
  41572. // Take two coordiantes in the range [-1, 1] that define a portion of a
  41573. // cube face and return the area of the projection of that portion on the
  41574. // surface of the sphere.
  41575. //--------------------------------------------------------------------------------------
  41576. PMREMGenerator.prototype.areaElement = function (x, y) {
  41577. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  41578. };
  41579. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  41580. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  41581. // (+ 0.5f is for texel center addressing)
  41582. u = (2.0 * (u + 0.5) / size) - 1.0;
  41583. v = (2.0 * (v + 0.5) / size) - 1.0;
  41584. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  41585. var invResolution = 1.0 / size;
  41586. // U and V are the -1..1 texture coordinate on the current face.
  41587. // Get projected area for this texel
  41588. var x0 = u - invResolution;
  41589. var y0 = v - invResolution;
  41590. var x1 = u + invResolution;
  41591. var y1 = v + invResolution;
  41592. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  41593. return solidAngle;
  41594. };
  41595. //--------------------------------------------------------------------------------------
  41596. //The key to the speed of these filtering routines is to quickly define a per-face
  41597. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  41598. // Later these pixels are selectively processed based on their dot products to see if
  41599. // they reside within the filtering cone.
  41600. //
  41601. //This is done by computing the smallest per-texel angle to get a conservative estimate
  41602. // of the number of texels needed to be covered in width and height order to filter the
  41603. // region. the bounding box for the center taps face is defined first, and if the
  41604. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  41605. // defined next
  41606. //--------------------------------------------------------------------------------------
  41607. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  41608. // note that pixels within these regions may be rejected
  41609. // based on the anlge
  41610. var iCubeFace;
  41611. var u;
  41612. var v;
  41613. // bounding box per face to specify region to process
  41614. var filterExtents = [];
  41615. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41616. filterExtents.push(new CMGBoundinBox());
  41617. }
  41618. // min angle a src texel can cover (in degrees)
  41619. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  41620. // angle about center tap to define filter cone
  41621. // filter angle is 1/2 the cone angle
  41622. var filterAngle = filterConeAngle / 2.0;
  41623. //ensure filter angle is larger than a texel
  41624. if (filterAngle < srcTexelAngle) {
  41625. filterAngle = srcTexelAngle;
  41626. }
  41627. //ensure filter cone is always smaller than the hemisphere
  41628. if (filterAngle > 90.0) {
  41629. filterAngle = 90.0;
  41630. }
  41631. // the maximum number of texels in 1D the filter cone angle will cover
  41632. // used to determine bounding box size for filter extents
  41633. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  41634. // ensure conservative region always covers at least one texel
  41635. if (filterSize < 1) {
  41636. filterSize = 1;
  41637. }
  41638. // dotProdThresh threshold based on cone angle to determine whether or not taps
  41639. // reside within the cone angle
  41640. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  41641. // process required faces
  41642. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41643. //iterate over dst cube map face texel
  41644. for (v = 0; v < dstSize; v++) {
  41645. for (u = 0; u < dstSize; u++) {
  41646. //get center tap direction
  41647. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  41648. //clear old per-face filter extents
  41649. this.clearFilterExtents(filterExtents);
  41650. //define per-face filter extents
  41651. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  41652. //perform filtering of src faces using filter extents
  41653. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  41654. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  41655. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  41656. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  41657. }
  41658. }
  41659. }
  41660. };
  41661. //--------------------------------------------------------------------------------------
  41662. //Clear filter extents for the 6 cube map faces
  41663. //--------------------------------------------------------------------------------------
  41664. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  41665. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  41666. filterExtents[iCubeFaces].clear();
  41667. }
  41668. };
  41669. //--------------------------------------------------------------------------------------
  41670. //Define per-face bounding box filter extents
  41671. //
  41672. // These define conservative texel regions in each of the faces the filter can possibly
  41673. // process. When the pixels in the regions are actually processed, the dot product
  41674. // between the tap vector and the center tap vector is used to determine the weight of
  41675. // the tap and whether or not the tap is within the cone.
  41676. //
  41677. //--------------------------------------------------------------------------------------
  41678. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  41679. //neighboring face and bleed over amount, and width of BBOX for
  41680. // left, right, top, and bottom edges of this face
  41681. var bleedOverAmount = [0, 0, 0, 0];
  41682. var bleedOverBBoxMin = [0, 0, 0, 0];
  41683. var bleedOverBBoxMax = [0, 0, 0, 0];
  41684. var neighborFace;
  41685. var neighborEdge;
  41686. var oppositeFaceIdx;
  41687. //get face idx, and u, v info from center tap dir
  41688. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  41689. var faceIdx = result.x;
  41690. var u = result.y;
  41691. var v = result.z;
  41692. //define bbox size within face
  41693. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  41694. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  41695. filterExtents[faceIdx].clampMin(0, 0, 0);
  41696. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  41697. //u and v extent in face corresponding to center tap
  41698. var minU = filterExtents[faceIdx].min.x;
  41699. var minV = filterExtents[faceIdx].min.y;
  41700. var maxU = filterExtents[faceIdx].max.x;
  41701. var maxV = filterExtents[faceIdx].max.y;
  41702. //bleed over amounts for face across u=0 edge (left)
  41703. bleedOverAmount[0] = (bboxSize - u);
  41704. bleedOverBBoxMin[0] = minV;
  41705. bleedOverBBoxMax[0] = maxV;
  41706. //bleed over amounts for face across u=1 edge (right)
  41707. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  41708. bleedOverBBoxMin[1] = minV;
  41709. bleedOverBBoxMax[1] = maxV;
  41710. //bleed over to face across v=0 edge (up)
  41711. bleedOverAmount[2] = (bboxSize - v);
  41712. bleedOverBBoxMin[2] = minU;
  41713. bleedOverBBoxMax[2] = maxU;
  41714. //bleed over to face across v=1 edge (down)
  41715. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  41716. bleedOverBBoxMin[3] = minU;
  41717. bleedOverBBoxMax[3] = maxU;
  41718. //compute bleed over regions in neighboring faces
  41719. for (var i = 0; i < 4; i++) {
  41720. if (bleedOverAmount[i] > 0) {
  41721. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  41722. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  41723. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  41724. // be flipped: the cases are
  41725. // if a left edge mates with a left or bottom edge on the neighbor
  41726. // if a top edge mates with a top or right edge on the neighbor
  41727. // if a right edge mates with a right or top edge on the neighbor
  41728. // if a bottom edge mates with a bottom or left edge on the neighbor
  41729. //Seeing as the edges are enumerated as follows
  41730. // left =0
  41731. // right =1
  41732. // top =2
  41733. // bottom =3
  41734. //
  41735. // so if the edge enums are the same, or the sum of the enums == 3,
  41736. // the bbox needs to be flipped
  41737. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  41738. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  41739. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  41740. }
  41741. //The way the bounding box is extended onto the neighboring face
  41742. // depends on which edge of neighboring face abuts with this one
  41743. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  41744. case PMREMGenerator.CP_EDGE_LEFT:
  41745. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  41746. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  41747. break;
  41748. case PMREMGenerator.CP_EDGE_RIGHT:
  41749. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  41750. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  41751. break;
  41752. case PMREMGenerator.CP_EDGE_TOP:
  41753. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  41754. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  41755. break;
  41756. case PMREMGenerator.CP_EDGE_BOTTOM:
  41757. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  41758. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  41759. break;
  41760. }
  41761. //clamp filter extents in non-center tap faces to remain within surface
  41762. filterExtents[neighborFace].clampMin(0, 0, 0);
  41763. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  41764. }
  41765. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  41766. // from the center tap face, then process the opposite face entirely for now.
  41767. //Note that the cases in which this happens, what usually happens is that
  41768. // more than one edge bleeds onto the opposite face, and the bounding box
  41769. // encompasses the entire cube map face.
  41770. if (bleedOverAmount[i] > srcSize) {
  41771. //determine opposite face
  41772. switch (faceIdx) {
  41773. case PMREMGenerator.CP_FACE_X_POS:
  41774. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  41775. break;
  41776. case PMREMGenerator.CP_FACE_X_NEG:
  41777. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  41778. break;
  41779. case PMREMGenerator.CP_FACE_Y_POS:
  41780. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  41781. break;
  41782. case PMREMGenerator.CP_FACE_Y_NEG:
  41783. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  41784. break;
  41785. case PMREMGenerator.CP_FACE_Z_POS:
  41786. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  41787. break;
  41788. case PMREMGenerator.CP_FACE_Z_NEG:
  41789. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  41790. break;
  41791. default:
  41792. break;
  41793. }
  41794. //just encompass entire face for now
  41795. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  41796. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  41797. }
  41798. }
  41799. };
  41800. //--------------------------------------------------------------------------------------
  41801. //ProcessFilterExtents
  41802. // Process bounding box in each cube face
  41803. //
  41804. //--------------------------------------------------------------------------------------
  41805. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  41806. //accumulators are 64-bit floats in order to have the precision needed
  41807. // over a summation of a large number of pixels
  41808. var dstAccum = [0, 0, 0, 0];
  41809. var weightAccum = 0;
  41810. var k = 0;
  41811. var nSrcChannels = this.numChannels;
  41812. // norm cube map and srcCubeMap have same face width
  41813. var faceWidth = srcSize;
  41814. //amount to add to pointer to move to next scanline in images
  41815. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  41816. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  41817. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  41818. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  41819. // iterate over cubefaces
  41820. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  41821. //if bbox is non empty
  41822. if (!filterExtents[iFaceIdx].empty()) {
  41823. var uStart = filterExtents[iFaceIdx].min.x;
  41824. var vStart = filterExtents[iFaceIdx].min.y;
  41825. var uEnd = filterExtents[iFaceIdx].max.x;
  41826. var vEnd = filterExtents[iFaceIdx].max.y;
  41827. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  41828. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  41829. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  41830. for (var v = vStart; v <= vEnd; v++) {
  41831. var normCubeRowWalk = 0;
  41832. var srcCubeRowWalk = 0;
  41833. for (var u = uStart; u <= uEnd; u++) {
  41834. //pointer to direction in cube map associated with texel
  41835. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  41836. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  41837. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  41838. //check dot product to see if texel is within cone
  41839. var tapDotProd = texelVectX * centerTapDir.x +
  41840. texelVectY * centerTapDir.y +
  41841. texelVectZ * centerTapDir.z;
  41842. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  41843. //solid angle stored in 4th channel of normalizer/solid angle cube map
  41844. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  41845. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  41846. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  41847. // so just adding one to specularpower do the trick.
  41848. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  41849. //iterate over channels
  41850. for (k = 0; k < nSrcChannels; k++) {
  41851. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  41852. srcCubeRowWalk++;
  41853. }
  41854. weightAccum += weight; //accumulate weight
  41855. }
  41856. else {
  41857. //step across source pixel
  41858. srcCubeRowWalk += nSrcChannels;
  41859. }
  41860. normCubeRowWalk += 4; // 4 channels per norm cube map.
  41861. }
  41862. startIndexNormCubeMap += normCubePitch;
  41863. startIndexSrcCubeMap += srcCubePitch;
  41864. }
  41865. }
  41866. }
  41867. //divide through by weights if weight is non zero
  41868. if (weightAccum != 0.0) {
  41869. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  41870. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  41871. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  41872. if (this.numChannels > 3) {
  41873. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  41874. }
  41875. }
  41876. else {
  41877. // otherwise sample nearest
  41878. // get face idx and u, v texel coordinate in face
  41879. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  41880. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  41881. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  41882. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  41883. if (this.numChannels > 3) {
  41884. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  41885. }
  41886. }
  41887. return PMREMGenerator._vectorTemp;
  41888. };
  41889. //--------------------------------------------------------------------------------------
  41890. // Fixup cube edges
  41891. //
  41892. // average texels on cube map faces across the edges
  41893. // WARP/BENT Method Only.
  41894. //--------------------------------------------------------------------------------------
  41895. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  41896. var k;
  41897. var j;
  41898. var i;
  41899. var iFace;
  41900. var iCorner = 0;
  41901. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  41902. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  41903. // note that if functionality to filter across the three texels for each corner, then
  41904. //indexed by corner and face idx. the array contains the face the start points belongs to.
  41905. var cornerPtr = [
  41906. [[], [], []],
  41907. [[], [], []],
  41908. [[], [], []],
  41909. [[], [], []],
  41910. [[], [], []],
  41911. [[], [], []],
  41912. [[], [], []],
  41913. [[], [], []]
  41914. ];
  41915. //if there is no fixup, or fixup width = 0, do nothing
  41916. if (cubeMapSize < 1) {
  41917. return;
  41918. }
  41919. //special case 1x1 cubemap, average face colors
  41920. if (cubeMapSize == 1) {
  41921. //iterate over channels
  41922. for (k = 0; k < this.numChannels; k++) {
  41923. var accum = 0.0;
  41924. //iterate over faces to accumulate face colors
  41925. for (iFace = 0; iFace < 6; iFace++) {
  41926. accum += cubeMap[iFace][k];
  41927. }
  41928. //compute average over 6 face colors
  41929. accum /= 6.0;
  41930. //iterate over faces to distribute face colors
  41931. for (iFace = 0; iFace < 6; iFace++) {
  41932. cubeMap[iFace][k] = accum;
  41933. }
  41934. }
  41935. return;
  41936. }
  41937. //iterate over faces to collect list of corner texel pointers
  41938. for (iFace = 0; iFace < 6; iFace++) {
  41939. //the 4 corner pointers for this face
  41940. faceCornerStartIndicies[0] = [iFace, 0];
  41941. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  41942. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  41943. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  41944. //iterate over face corners to collect cube corner pointers
  41945. for (iCorner = 0; iCorner < 4; iCorner++) {
  41946. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  41947. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  41948. cornerNumPtrs[corner]++;
  41949. }
  41950. }
  41951. //iterate over corners to average across corner tap values
  41952. for (iCorner = 0; iCorner < 8; iCorner++) {
  41953. for (k = 0; k < this.numChannels; k++) {
  41954. var cornerTapAccum = 0.0;
  41955. //iterate over corner texels and average results
  41956. for (i = 0; i < 3; i++) {
  41957. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  41958. }
  41959. //divide by 3 to compute average of corner tap values
  41960. cornerTapAccum *= (1.0 / 3.0);
  41961. //iterate over corner texels and average results
  41962. for (i = 0; i < 3; i++) {
  41963. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  41964. }
  41965. }
  41966. }
  41967. //iterate over the twelve edges of the cube to average across edges
  41968. for (i = 0; i < 12; i++) {
  41969. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  41970. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  41971. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  41972. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  41973. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  41974. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  41975. var edgeWalk = 0;
  41976. var neighborEdgeWalk = 0;
  41977. //Determine walking pointers based on edge type
  41978. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  41979. switch (edge) {
  41980. case PMREMGenerator.CP_EDGE_LEFT:
  41981. // no change to faceEdgeStartPtr
  41982. edgeWalk = this.numChannels * cubeMapSize;
  41983. break;
  41984. case PMREMGenerator.CP_EDGE_RIGHT:
  41985. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  41986. edgeWalk = this.numChannels * cubeMapSize;
  41987. break;
  41988. case PMREMGenerator.CP_EDGE_TOP:
  41989. // no change to faceEdgeStartPtr
  41990. edgeWalk = this.numChannels;
  41991. break;
  41992. case PMREMGenerator.CP_EDGE_BOTTOM:
  41993. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  41994. edgeWalk = this.numChannels;
  41995. break;
  41996. }
  41997. //For certain types of edge abutments, the neighbor edge walk needs to
  41998. // be flipped: the cases are
  41999. // if a left edge mates with a left or bottom edge on the neighbor
  42000. // if a top edge mates with a top or right edge on the neighbor
  42001. // if a right edge mates with a right or top edge on the neighbor
  42002. // if a bottom edge mates with a bottom or left edge on the neighbor
  42003. //Seeing as the edges are enumerated as follows
  42004. // left =0
  42005. // right =1
  42006. // top =2
  42007. // bottom =3
  42008. //
  42009. //If the edge enums are the same, or the sum of the enums == 3,
  42010. // the neighbor edge walk needs to be flipped
  42011. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  42012. switch (neighborEdge) {
  42013. case PMREMGenerator.CP_EDGE_LEFT:
  42014. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  42015. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  42016. break;
  42017. case PMREMGenerator.CP_EDGE_RIGHT:
  42018. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  42019. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  42020. break;
  42021. case PMREMGenerator.CP_EDGE_TOP:
  42022. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  42023. neighborEdgeWalk = -this.numChannels;
  42024. break;
  42025. case PMREMGenerator.CP_EDGE_BOTTOM:
  42026. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  42027. neighborEdgeWalk = -this.numChannels;
  42028. break;
  42029. }
  42030. }
  42031. else {
  42032. //swapped direction neighbor edge walk
  42033. switch (neighborEdge) {
  42034. case PMREMGenerator.CP_EDGE_LEFT:
  42035. //no change to neighborEdgeStartPtr for this case since it points
  42036. // to the upper left corner already
  42037. neighborEdgeWalk = this.numChannels * cubeMapSize;
  42038. break;
  42039. case PMREMGenerator.CP_EDGE_RIGHT:
  42040. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  42041. neighborEdgeWalk = this.numChannels * cubeMapSize;
  42042. break;
  42043. case PMREMGenerator.CP_EDGE_TOP:
  42044. //no change to neighborEdgeStartPtr for this case since it points
  42045. // to the upper left corner already
  42046. neighborEdgeWalk = this.numChannels;
  42047. break;
  42048. case PMREMGenerator.CP_EDGE_BOTTOM:
  42049. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  42050. neighborEdgeWalk = this.numChannels;
  42051. break;
  42052. }
  42053. }
  42054. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  42055. //nearby neighborhood
  42056. //step ahead one texel on edge
  42057. edgeStartIndex += edgeWalk;
  42058. neighborEdgeStartIndex += neighborEdgeWalk;
  42059. // note that this loop does not process the corner texels, since they have already been
  42060. // averaged across faces across earlier
  42061. for (j = 1; j < (cubeMapSize - 1); j++) {
  42062. //for each set of taps along edge, average them
  42063. // and rewrite the results into the edges
  42064. for (k = 0; k < this.numChannels; k++) {
  42065. var edgeTap = cubeMap[face][edgeStartIndex + k];
  42066. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  42067. //compute average of tap intensity values
  42068. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  42069. //propagate average of taps to edge taps
  42070. cubeMap[face][edgeStartIndex + k] = avgTap;
  42071. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  42072. }
  42073. edgeStartIndex += edgeWalk;
  42074. neighborEdgeStartIndex += neighborEdgeWalk;
  42075. }
  42076. }
  42077. };
  42078. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  42079. PMREMGenerator.CP_UDIR = 0;
  42080. PMREMGenerator.CP_VDIR = 1;
  42081. PMREMGenerator.CP_FACEAXIS = 2;
  42082. //used to index cube faces
  42083. PMREMGenerator.CP_FACE_X_POS = 0;
  42084. PMREMGenerator.CP_FACE_X_NEG = 1;
  42085. PMREMGenerator.CP_FACE_Y_POS = 2;
  42086. PMREMGenerator.CP_FACE_Y_NEG = 3;
  42087. PMREMGenerator.CP_FACE_Z_POS = 4;
  42088. PMREMGenerator.CP_FACE_Z_NEG = 5;
  42089. //used to index image edges
  42090. // NOTE.. the actual number corresponding to the edge is important
  42091. // do not change these, or the code will break
  42092. //
  42093. // CP_EDGE_LEFT is u = 0
  42094. // CP_EDGE_RIGHT is u = width-1
  42095. // CP_EDGE_TOP is v = 0
  42096. // CP_EDGE_BOTTOM is v = height-1
  42097. PMREMGenerator.CP_EDGE_LEFT = 0;
  42098. PMREMGenerator.CP_EDGE_RIGHT = 1;
  42099. PMREMGenerator.CP_EDGE_TOP = 2;
  42100. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  42101. //corners of CUBE map (P or N specifys if it corresponds to the
  42102. // positive or negative direction each of X, Y, and Z
  42103. PMREMGenerator.CP_CORNER_NNN = 0;
  42104. PMREMGenerator.CP_CORNER_NNP = 1;
  42105. PMREMGenerator.CP_CORNER_NPN = 2;
  42106. PMREMGenerator.CP_CORNER_NPP = 3;
  42107. PMREMGenerator.CP_CORNER_PNN = 4;
  42108. PMREMGenerator.CP_CORNER_PNP = 5;
  42109. PMREMGenerator.CP_CORNER_PPN = 6;
  42110. PMREMGenerator.CP_CORNER_PPP = 7;
  42111. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  42112. //3x2 matrices that map cube map indexing vectors in 3d
  42113. // (after face selection and divide through by the
  42114. // _ABSOLUTE VALUE_ of the max coord)
  42115. // into NVC space
  42116. //Note this currently assumes the D3D cube face ordering and orientation
  42117. PMREMGenerator._sgFace2DMapping = [
  42118. //XPOS face
  42119. [[0, 0, -1],
  42120. [0, -1, 0],
  42121. [1, 0, 0]],
  42122. //XNEG face
  42123. [[0, 0, 1],
  42124. [0, -1, 0],
  42125. [-1, 0, 0]],
  42126. //YPOS face
  42127. [[1, 0, 0],
  42128. [0, 0, 1],
  42129. [0, 1, 0]],
  42130. //YNEG face
  42131. [[1, 0, 0],
  42132. [0, 0, -1],
  42133. [0, -1, 0]],
  42134. //ZPOS face
  42135. [[1, 0, 0],
  42136. [0, -1, 0],
  42137. [0, 0, 1]],
  42138. //ZNEG face
  42139. [[-1, 0, 0],
  42140. [0, -1, 0],
  42141. [0, 0, -1]],
  42142. ];
  42143. //------------------------------------------------------------------------------
  42144. // D3D cube map face specification
  42145. // mapping from 3D x,y,z cube map lookup coordinates
  42146. // to 2D within face u,v coordinates
  42147. //
  42148. // --------------------> U direction
  42149. // | (within-face texture space)
  42150. // | _____
  42151. // | | |
  42152. // | | +Y |
  42153. // | _____|_____|_____ _____
  42154. // | | | | | |
  42155. // | | -X | +Z | +X | -Z |
  42156. // | |_____|_____|_____|_____|
  42157. // | | |
  42158. // | | -Y |
  42159. // | |_____|
  42160. // |
  42161. // v V direction
  42162. // (within-face texture space)
  42163. //------------------------------------------------------------------------------
  42164. //Information about neighbors and how texture coorrdinates change across faces
  42165. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  42166. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  42167. //Note this currently assumes the D3D cube face ordering and orientation
  42168. PMREMGenerator._sgCubeNgh = [
  42169. //XPOS face
  42170. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42171. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42172. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42173. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  42174. //XNEG face
  42175. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42176. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  42177. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  42178. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  42179. //YPOS face
  42180. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  42181. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  42182. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  42183. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  42184. //YNEG face
  42185. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  42186. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42187. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42188. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  42189. //ZPOS face
  42190. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42191. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  42192. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42193. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  42194. //ZNEG face
  42195. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42196. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42197. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  42198. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  42199. ];
  42200. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  42201. // this table is used to average over the edges.
  42202. PMREMGenerator._sgCubeEdgeList = [
  42203. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  42204. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42205. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  42206. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42207. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42208. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42209. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  42210. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  42211. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  42212. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42213. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  42214. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  42215. ];
  42216. //Information about which of the 8 cube corners are correspond to the
  42217. // the 4 corners in each cube face
  42218. // the order is upper left, upper right, lower left, lower right
  42219. PMREMGenerator._sgCubeCornerList = [
  42220. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  42221. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  42222. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  42223. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  42224. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  42225. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  42226. ];
  42227. return PMREMGenerator;
  42228. })();
  42229. Internals.PMREMGenerator = PMREMGenerator;
  42230. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42231. })(BABYLON || (BABYLON = {}));
  42232. var BABYLON;
  42233. (function (BABYLON) {
  42234. /**
  42235. * This represents a texture coming from an HDR input.
  42236. *
  42237. * The only supported format is currently panorama picture stored in RGBE format.
  42238. * Example of such files can be found on HDRLib: http://hdrlib.com/
  42239. */
  42240. var HDRCubeTexture = (function (_super) {
  42241. __extends(HDRCubeTexture, _super);
  42242. /**
  42243. * Instantiates an HDRTexture from the following parameters.
  42244. *
  42245. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  42246. * @param scene The scene the texture will be used in
  42247. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  42248. * @param noMipmap Forces to not generate the mipmap if true
  42249. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  42250. * @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)
  42251. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  42252. */
  42253. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  42254. if (noMipmap === void 0) { noMipmap = false; }
  42255. if (generateHarmonics === void 0) { generateHarmonics = true; }
  42256. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  42257. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  42258. _super.call(this, scene);
  42259. this._useInGammaSpace = false;
  42260. this._generateHarmonics = true;
  42261. /**
  42262. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  42263. */
  42264. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42265. /**
  42266. * The spherical polynomial data extracted from the texture.
  42267. */
  42268. this.sphericalPolynomial = null;
  42269. /**
  42270. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  42271. * This is usefull at run time to apply the good shader.
  42272. */
  42273. this.isPMREM = false;
  42274. this.name = url;
  42275. this.url = url;
  42276. this._noMipmap = noMipmap;
  42277. this.hasAlpha = false;
  42278. this._size = size;
  42279. this._useInGammaSpace = useInGammaSpace;
  42280. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  42281. this.isPMREM = this._usePMREMGenerator;
  42282. if (!url) {
  42283. return;
  42284. }
  42285. this._texture = this._getFromCache(url, noMipmap);
  42286. if (!this._texture) {
  42287. if (!scene.useDelayedTextureLoading) {
  42288. this.loadTexture();
  42289. }
  42290. else {
  42291. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42292. }
  42293. }
  42294. this.isCube = true;
  42295. this._textureMatrix = BABYLON.Matrix.Identity();
  42296. }
  42297. HDRCubeTexture.prototype.loadTexture = function () {
  42298. var _this = this;
  42299. var callback = function (buffer) {
  42300. // Extract the raw linear data.
  42301. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  42302. // Generate harmonics if needed.
  42303. if (_this._generateHarmonics) {
  42304. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  42305. }
  42306. var results = [];
  42307. var byteArray = null;
  42308. // Create uintarray fallback.
  42309. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  42310. // 3 channels of 1 bytes per pixel in bytes.
  42311. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  42312. byteArray = new Uint8Array(byteBuffer);
  42313. }
  42314. // Push each faces.
  42315. for (var j = 0; j < 6; j++) {
  42316. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  42317. // If special cases.
  42318. if (_this._useInGammaSpace || byteArray) {
  42319. for (var i = 0; i < _this._size * _this._size; i++) {
  42320. // Put in gamma space if requested.
  42321. if (_this._useInGammaSpace) {
  42322. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  42323. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  42324. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  42325. }
  42326. // Convert to int texture for fallback.
  42327. if (byteArray) {
  42328. // R
  42329. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  42330. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  42331. // G
  42332. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  42333. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  42334. // B
  42335. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  42336. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  42337. }
  42338. }
  42339. }
  42340. results.push(dataFace);
  42341. }
  42342. return results;
  42343. };
  42344. var mipmapGenerator = null;
  42345. if (!this._noMipmap && this._usePMREMGenerator) {
  42346. mipmapGenerator = function (data) {
  42347. // Custom setup of the generator matching with the PBR shader values.
  42348. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  42349. return generator.filterCubeMap();
  42350. };
  42351. }
  42352. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  42353. };
  42354. HDRCubeTexture.prototype.clone = function () {
  42355. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  42356. // Base texture
  42357. newTexture.level = this.level;
  42358. newTexture.wrapU = this.wrapU;
  42359. newTexture.wrapV = this.wrapV;
  42360. newTexture.coordinatesIndex = this.coordinatesIndex;
  42361. newTexture.coordinatesMode = this.coordinatesMode;
  42362. return newTexture;
  42363. };
  42364. // Methods
  42365. HDRCubeTexture.prototype.delayLoad = function () {
  42366. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42367. return;
  42368. }
  42369. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42370. this._texture = this._getFromCache(this.url, this._noMipmap);
  42371. if (!this._texture) {
  42372. this.loadTexture();
  42373. }
  42374. };
  42375. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  42376. return this._textureMatrix;
  42377. };
  42378. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42379. var texture = null;
  42380. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  42381. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  42382. texture.name = parsedTexture.name;
  42383. texture.hasAlpha = parsedTexture.hasAlpha;
  42384. texture.level = parsedTexture.level;
  42385. texture.coordinatesMode = parsedTexture.coordinatesMode;
  42386. }
  42387. return texture;
  42388. };
  42389. HDRCubeTexture.prototype.serialize = function () {
  42390. if (!this.name) {
  42391. return null;
  42392. }
  42393. var serializationObject = {};
  42394. serializationObject.name = this.name;
  42395. serializationObject.hasAlpha = this.hasAlpha;
  42396. serializationObject.isCube = true;
  42397. serializationObject.level = this.level;
  42398. serializationObject.size = this._size;
  42399. serializationObject.coordinatesMode = this.coordinatesMode;
  42400. serializationObject.useInGammaSpace = this._useInGammaSpace;
  42401. serializationObject.generateHarmonics = this._generateHarmonics;
  42402. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  42403. return serializationObject;
  42404. };
  42405. HDRCubeTexture._facesMapping = [
  42406. "right",
  42407. "up",
  42408. "front",
  42409. "left",
  42410. "down",
  42411. "back"
  42412. ];
  42413. return HDRCubeTexture;
  42414. })(BABYLON.BaseTexture);
  42415. BABYLON.HDRCubeTexture = HDRCubeTexture;
  42416. })(BABYLON || (BABYLON = {}));
  42417. var BABYLON;
  42418. (function (BABYLON) {
  42419. var Debug;
  42420. (function (Debug) {
  42421. /**
  42422. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  42423. */
  42424. var SkeletonViewer = (function () {
  42425. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  42426. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  42427. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  42428. this.skeleton = skeleton;
  42429. this.mesh = mesh;
  42430. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  42431. this.renderingGroupId = renderingGroupId;
  42432. this.color = BABYLON.Color3.White();
  42433. this._debugLines = [];
  42434. this._isEnabled = false;
  42435. this._scene = scene;
  42436. this.update();
  42437. this._renderFunction = this.update.bind(this);
  42438. }
  42439. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  42440. get: function () {
  42441. return this._isEnabled;
  42442. },
  42443. set: function (value) {
  42444. if (this._isEnabled === value) {
  42445. return;
  42446. }
  42447. this._isEnabled = value;
  42448. if (value) {
  42449. this._scene.registerBeforeRender(this._renderFunction);
  42450. }
  42451. else {
  42452. this._scene.unregisterBeforeRender(this._renderFunction);
  42453. }
  42454. },
  42455. enumerable: true,
  42456. configurable: true
  42457. });
  42458. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  42459. if (x === void 0) { x = 0; }
  42460. if (y === void 0) { y = 0; }
  42461. if (z === void 0) { z = 0; }
  42462. var tmat = BABYLON.Tmp.Matrix[0];
  42463. var parentBone = bone.getParent();
  42464. tmat.copyFrom(bone.getLocalMatrix());
  42465. if (x !== 0 || y !== 0 || z !== 0) {
  42466. var tmat2 = BABYLON.Tmp.Matrix[1];
  42467. BABYLON.Matrix.IdentityToRef(tmat2);
  42468. tmat2.m[12] = x;
  42469. tmat2.m[13] = y;
  42470. tmat2.m[14] = z;
  42471. tmat2.multiplyToRef(tmat, tmat);
  42472. }
  42473. if (parentBone) {
  42474. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  42475. }
  42476. tmat.multiplyToRef(meshMat, tmat);
  42477. position.x = tmat.m[12];
  42478. position.y = tmat.m[13];
  42479. position.z = tmat.m[14];
  42480. };
  42481. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  42482. var len = bones.length;
  42483. for (var i = 0; i < len; i++) {
  42484. var bone = bones[i];
  42485. var points = this._debugLines[i];
  42486. if (!points) {
  42487. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  42488. this._debugLines[i] = points;
  42489. }
  42490. this._getBonePosition(points[0], bone, meshMat);
  42491. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  42492. }
  42493. };
  42494. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  42495. var len = bones.length;
  42496. var boneNum = 0;
  42497. for (var i = len - 1; i >= 0; i--) {
  42498. var childBone = bones[i];
  42499. var parentBone = childBone.getParent();
  42500. if (!parentBone) {
  42501. continue;
  42502. }
  42503. var points = this._debugLines[boneNum];
  42504. if (!points) {
  42505. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  42506. this._debugLines[boneNum] = points;
  42507. }
  42508. this._getBonePosition(points[0], childBone, meshMat);
  42509. this._getBonePosition(points[1], parentBone, meshMat);
  42510. boneNum++;
  42511. }
  42512. };
  42513. SkeletonViewer.prototype.update = function () {
  42514. if (this.autoUpdateBonesMatrices) {
  42515. this._updateBoneMatrix(this.skeleton.bones[0]);
  42516. }
  42517. if (this.skeleton.bones[0].length === undefined) {
  42518. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  42519. }
  42520. else {
  42521. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  42522. }
  42523. if (!this._debugMesh) {
  42524. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  42525. this._debugMesh.renderingGroupId = this.renderingGroupId;
  42526. }
  42527. else {
  42528. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  42529. }
  42530. this._debugMesh.color = this.color;
  42531. };
  42532. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  42533. if (bone.getParent()) {
  42534. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  42535. }
  42536. var children = bone.children;
  42537. var len = children.length;
  42538. for (var i = 0; i < len; i++) {
  42539. this._updateBoneMatrix(children[i]);
  42540. }
  42541. };
  42542. SkeletonViewer.prototype.dispose = function () {
  42543. if (this._debugMesh) {
  42544. this.isEnabled = false;
  42545. this._debugMesh.dispose();
  42546. this._debugMesh = null;
  42547. }
  42548. };
  42549. return SkeletonViewer;
  42550. })();
  42551. Debug.SkeletonViewer = SkeletonViewer;
  42552. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  42553. })(BABYLON || (BABYLON = {}));
  42554. 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}"};
  42555. 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"};
  42556. 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={}));";
  42557. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  42558. module.exports = BABYLON;
  42559. };