babylon.max.js 2.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232
  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. Object.defineProperty(Node.prototype, "parent", {
  7122. get: function () {
  7123. return this._parentNode;
  7124. },
  7125. set: function (parent) {
  7126. if (this._parentNode === parent) {
  7127. return;
  7128. }
  7129. if (this._parentNode) {
  7130. var index = this._parentNode._children.indexOf(this);
  7131. if (index !== -1) {
  7132. this._parentNode._children.splice(index, 1);
  7133. }
  7134. }
  7135. this._parentNode = parent;
  7136. if (this._parentNode) {
  7137. if (!this._parentNode._children) {
  7138. this._parentNode._children = new Array();
  7139. }
  7140. this._parentNode._children.push(this);
  7141. }
  7142. },
  7143. enumerable: true,
  7144. configurable: true
  7145. });
  7146. Node.prototype.getScene = function () {
  7147. return this._scene;
  7148. };
  7149. Node.prototype.getEngine = function () {
  7150. return this._scene.getEngine();
  7151. };
  7152. // override it in derived class
  7153. Node.prototype.getWorldMatrix = function () {
  7154. return BABYLON.Matrix.Identity();
  7155. };
  7156. // override it in derived class if you add new variables to the cache
  7157. // and call the parent class method
  7158. Node.prototype._initCache = function () {
  7159. this._cache = {};
  7160. this._cache.parent = undefined;
  7161. };
  7162. Node.prototype.updateCache = function (force) {
  7163. if (!force && this.isSynchronized())
  7164. return;
  7165. this._cache.parent = this.parent;
  7166. this._updateCache();
  7167. };
  7168. // override it in derived class if you add new variables to the cache
  7169. // and call the parent class method if !ignoreParentClass
  7170. Node.prototype._updateCache = function (ignoreParentClass) {
  7171. };
  7172. // override it in derived class if you add new variables to the cache
  7173. Node.prototype._isSynchronized = function () {
  7174. return true;
  7175. };
  7176. Node.prototype._markSyncedWithParent = function () {
  7177. this._parentRenderId = this.parent._currentRenderId;
  7178. };
  7179. Node.prototype.isSynchronizedWithParent = function () {
  7180. if (!this.parent) {
  7181. return true;
  7182. }
  7183. if (this._parentRenderId !== this.parent._currentRenderId) {
  7184. return false;
  7185. }
  7186. return this.parent.isSynchronized();
  7187. };
  7188. Node.prototype.isSynchronized = function (updateCache) {
  7189. var check = this.hasNewParent();
  7190. check = check || !this.isSynchronizedWithParent();
  7191. check = check || !this._isSynchronized();
  7192. if (updateCache)
  7193. this.updateCache(true);
  7194. return !check;
  7195. };
  7196. Node.prototype.hasNewParent = function (update) {
  7197. if (this._cache.parent === this.parent)
  7198. return false;
  7199. if (update)
  7200. this._cache.parent = this.parent;
  7201. return true;
  7202. };
  7203. /**
  7204. * Is this node ready to be used/rendered
  7205. * @return {boolean} is it ready
  7206. */
  7207. Node.prototype.isReady = function () {
  7208. return this._isReady;
  7209. };
  7210. /**
  7211. * Is this node enabled.
  7212. * If the node has a parent and is enabled, the parent will be inspected as well.
  7213. * @return {boolean} whether this node (and its parent) is enabled.
  7214. * @see setEnabled
  7215. */
  7216. Node.prototype.isEnabled = function () {
  7217. if (!this._isEnabled) {
  7218. return false;
  7219. }
  7220. if (this.parent) {
  7221. return this.parent.isEnabled();
  7222. }
  7223. return true;
  7224. };
  7225. /**
  7226. * Set the enabled state of this node.
  7227. * @param {boolean} value - the new enabled state
  7228. * @see isEnabled
  7229. */
  7230. Node.prototype.setEnabled = function (value) {
  7231. this._isEnabled = value;
  7232. };
  7233. /**
  7234. * Is this node a descendant of the given node.
  7235. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7236. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7237. * @see parent
  7238. */
  7239. Node.prototype.isDescendantOf = function (ancestor) {
  7240. if (this.parent) {
  7241. if (this.parent === ancestor) {
  7242. return true;
  7243. }
  7244. return this.parent.isDescendantOf(ancestor);
  7245. }
  7246. return false;
  7247. };
  7248. /**
  7249. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7250. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7251. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7252. * @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.
  7253. */
  7254. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7255. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7256. if (!this._children) {
  7257. return;
  7258. }
  7259. for (var index = 0; index < this._children.length; index++) {
  7260. var item = this._children[index];
  7261. if (!predicate || predicate(item)) {
  7262. results.push(item);
  7263. }
  7264. if (!directDescendantsOnly) {
  7265. item._getDescendants(results, false, predicate);
  7266. }
  7267. }
  7268. };
  7269. /**
  7270. * Will return all nodes that have this node as ascendant.
  7271. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7272. * @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.
  7273. * @return {BABYLON.Node[]} all children nodes of all types.
  7274. */
  7275. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7276. var results = [];
  7277. this._getDescendants(results, directDescendantsOnly, predicate);
  7278. return results;
  7279. };
  7280. /**
  7281. * @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.
  7282. * @Deprecated, legacy support.
  7283. * use getDecendants instead.
  7284. */
  7285. Node.prototype.getChildren = function (predicate) {
  7286. return this.getDescendants(true, predicate);
  7287. };
  7288. /**
  7289. * Get all child-meshes of this node.
  7290. */
  7291. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7292. var results = [];
  7293. this._getDescendants(results, directDecendantsOnly, function (node) {
  7294. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7295. });
  7296. return results;
  7297. };
  7298. Node.prototype._setReady = function (state) {
  7299. if (state === this._isReady) {
  7300. return;
  7301. }
  7302. if (!state) {
  7303. this._isReady = false;
  7304. return;
  7305. }
  7306. this._isReady = true;
  7307. if (this.onReady) {
  7308. this.onReady(this);
  7309. }
  7310. };
  7311. Node.prototype.getAnimationByName = function (name) {
  7312. for (var i = 0; i < this.animations.length; i++) {
  7313. var animation = this.animations[i];
  7314. if (animation.name === name) {
  7315. return animation;
  7316. }
  7317. }
  7318. return null;
  7319. };
  7320. Node.prototype.createAnimationRange = function (name, from, to) {
  7321. // check name not already in use
  7322. if (!this._ranges[name]) {
  7323. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7324. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7325. if (this.animations[i]) {
  7326. this.animations[i].createRange(name, from, to);
  7327. }
  7328. }
  7329. }
  7330. };
  7331. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7332. if (deleteFrames === void 0) { deleteFrames = true; }
  7333. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7334. if (this.animations[i]) {
  7335. this.animations[i].deleteRange(name, deleteFrames);
  7336. }
  7337. }
  7338. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7339. };
  7340. Node.prototype.getAnimationRange = function (name) {
  7341. return this._ranges[name];
  7342. };
  7343. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7344. var range = this.getAnimationRange(name);
  7345. if (!range) {
  7346. return null;
  7347. }
  7348. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7349. };
  7350. Node.prototype.serializeAnimationRanges = function () {
  7351. var serializationRanges = [];
  7352. for (var name in this._ranges) {
  7353. var range = {};
  7354. range.name = name;
  7355. range.from = this._ranges[name].from;
  7356. range.to = this._ranges[name].to;
  7357. serializationRanges.push(range);
  7358. }
  7359. return serializationRanges;
  7360. };
  7361. Node.prototype.dispose = function () {
  7362. this.parent = null;
  7363. };
  7364. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7365. if (parsedNode.ranges) {
  7366. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7367. var data = parsedNode.ranges[index];
  7368. node.createAnimationRange(data.name, data.from, data.to);
  7369. }
  7370. }
  7371. };
  7372. __decorate([
  7373. BABYLON.serialize()
  7374. ], Node.prototype, "name", void 0);
  7375. __decorate([
  7376. BABYLON.serialize()
  7377. ], Node.prototype, "id", void 0);
  7378. __decorate([
  7379. BABYLON.serialize()
  7380. ], Node.prototype, "uniqueId", void 0);
  7381. __decorate([
  7382. BABYLON.serialize()
  7383. ], Node.prototype, "state", void 0);
  7384. return Node;
  7385. })();
  7386. BABYLON.Node = Node;
  7387. })(BABYLON || (BABYLON = {}));
  7388. var BABYLON;
  7389. (function (BABYLON) {
  7390. var FilesInput = (function () {
  7391. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7392. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7393. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7394. this._engine = p_engine;
  7395. this._canvas = p_canvas;
  7396. this._currentScene = p_scene;
  7397. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7398. this._progressCallback = p_progressCallback;
  7399. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7400. this._textureLoadingCallback = p_textureLoadingCallback;
  7401. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7402. }
  7403. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7404. var _this = this;
  7405. if (p_elementToMonitor) {
  7406. this._elementToMonitor = p_elementToMonitor;
  7407. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7408. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7409. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7410. }
  7411. };
  7412. FilesInput.prototype.renderFunction = function () {
  7413. if (this._additionnalRenderLoopLogicCallback) {
  7414. this._additionnalRenderLoopLogicCallback();
  7415. }
  7416. if (this._currentScene) {
  7417. if (this._textureLoadingCallback) {
  7418. var remaining = this._currentScene.getWaitingItemsCount();
  7419. if (remaining > 0) {
  7420. this._textureLoadingCallback(remaining);
  7421. }
  7422. }
  7423. this._currentScene.render();
  7424. }
  7425. };
  7426. FilesInput.prototype.drag = function (e) {
  7427. e.stopPropagation();
  7428. e.preventDefault();
  7429. };
  7430. FilesInput.prototype.drop = function (eventDrop) {
  7431. eventDrop.stopPropagation();
  7432. eventDrop.preventDefault();
  7433. this.loadFiles(eventDrop);
  7434. };
  7435. FilesInput.prototype.loadFiles = function (event) {
  7436. if (this._startingProcessingFilesCallback)
  7437. this._startingProcessingFilesCallback();
  7438. // Handling data transfer via drag'n'drop
  7439. if (event && event.dataTransfer && event.dataTransfer.files) {
  7440. this._filesToLoad = event.dataTransfer.files;
  7441. }
  7442. // Handling files from input files
  7443. if (event && event.target && event.target.files) {
  7444. this._filesToLoad = event.target.files;
  7445. }
  7446. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7447. for (var i = 0; i < this._filesToLoad.length; i++) {
  7448. switch (this._filesToLoad[i].type) {
  7449. case "image/jpeg":
  7450. case "image/png":
  7451. case "image/bmp":
  7452. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7453. break;
  7454. case "image/targa":
  7455. case "image/vnd.ms-dds":
  7456. case "audio/wav":
  7457. case "audio/x-wav":
  7458. case "audio/mp3":
  7459. case "audio/mpeg":
  7460. case "audio/mpeg3":
  7461. case "audio/x-mpeg-3":
  7462. case "audio/ogg":
  7463. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7464. break;
  7465. default:
  7466. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7467. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7468. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7469. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7470. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7471. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7472. this._sceneFileToLoad = this._filesToLoad[i];
  7473. }
  7474. break;
  7475. }
  7476. }
  7477. this.reload();
  7478. }
  7479. };
  7480. FilesInput.prototype.reload = function () {
  7481. var _this = this;
  7482. var that = this;
  7483. // If a ".babylon" file has been provided
  7484. if (this._sceneFileToLoad) {
  7485. if (this._currentScene) {
  7486. if (BABYLON.Tools.errorsCount > 0) {
  7487. BABYLON.Tools.ClearLogCache();
  7488. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7489. }
  7490. this._engine.stopRenderLoop();
  7491. this._currentScene.dispose();
  7492. }
  7493. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7494. that._currentScene = newScene;
  7495. // Wait for textures and shaders to be ready
  7496. that._currentScene.executeWhenReady(function () {
  7497. // Attach camera to canvas inputs
  7498. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7499. that._currentScene.createDefaultCameraOrLight();
  7500. }
  7501. that._currentScene.activeCamera.attachControl(that._canvas);
  7502. if (that._sceneLoadedCallback) {
  7503. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7504. }
  7505. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7506. });
  7507. }, function (progress) {
  7508. if (_this._progressCallback) {
  7509. _this._progressCallback(progress);
  7510. }
  7511. });
  7512. }
  7513. else {
  7514. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7515. }
  7516. };
  7517. FilesInput.FilesTextures = new Array();
  7518. FilesInput.FilesToLoad = new Array();
  7519. return FilesInput;
  7520. })();
  7521. BABYLON.FilesInput = FilesInput;
  7522. })(BABYLON || (BABYLON = {}));
  7523. var BABYLON;
  7524. (function (BABYLON) {
  7525. var IntersectionInfo = (function () {
  7526. function IntersectionInfo(bu, bv, distance) {
  7527. this.bu = bu;
  7528. this.bv = bv;
  7529. this.distance = distance;
  7530. this.faceId = 0;
  7531. this.subMeshId = 0;
  7532. }
  7533. return IntersectionInfo;
  7534. })();
  7535. BABYLON.IntersectionInfo = IntersectionInfo;
  7536. var PickingInfo = (function () {
  7537. function PickingInfo() {
  7538. this.hit = false;
  7539. this.distance = 0;
  7540. this.pickedPoint = null;
  7541. this.pickedMesh = null;
  7542. this.bu = 0;
  7543. this.bv = 0;
  7544. this.faceId = -1;
  7545. this.subMeshId = 0;
  7546. this.pickedSprite = null;
  7547. }
  7548. // Methods
  7549. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7550. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7551. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7552. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7553. return null;
  7554. }
  7555. var indices = this.pickedMesh.getIndices();
  7556. var result;
  7557. if (useVerticesNormals) {
  7558. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7559. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7560. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7561. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7562. normal0 = normal0.scale(this.bu);
  7563. normal1 = normal1.scale(this.bv);
  7564. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7565. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7566. }
  7567. else {
  7568. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7569. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7570. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7571. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7572. var p1p2 = vertex1.subtract(vertex2);
  7573. var p3p2 = vertex3.subtract(vertex2);
  7574. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7575. }
  7576. if (useWorldCoordinates) {
  7577. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7578. }
  7579. return BABYLON.Vector3.Normalize(result);
  7580. };
  7581. PickingInfo.prototype.getTextureCoordinates = function () {
  7582. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7583. return null;
  7584. }
  7585. var indices = this.pickedMesh.getIndices();
  7586. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7587. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7588. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7589. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7590. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7591. uv1 = uv1.scale(this.bu);
  7592. uv2 = uv2.scale(this.bv);
  7593. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7594. };
  7595. return PickingInfo;
  7596. })();
  7597. BABYLON.PickingInfo = PickingInfo;
  7598. })(BABYLON || (BABYLON = {}));
  7599. var BABYLON;
  7600. (function (BABYLON) {
  7601. var BoundingSphere = (function () {
  7602. function BoundingSphere(minimum, maximum) {
  7603. this.minimum = minimum;
  7604. this.maximum = maximum;
  7605. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7606. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7607. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7608. this.radius = distance * 0.5;
  7609. this.centerWorld = BABYLON.Vector3.Zero();
  7610. this._update(BABYLON.Matrix.Identity());
  7611. }
  7612. // Methods
  7613. BoundingSphere.prototype._update = function (world) {
  7614. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7615. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7616. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7617. };
  7618. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7619. for (var i = 0; i < 6; i++) {
  7620. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7621. return false;
  7622. }
  7623. return true;
  7624. };
  7625. BoundingSphere.prototype.intersectsPoint = function (point) {
  7626. var x = this.centerWorld.x - point.x;
  7627. var y = this.centerWorld.y - point.y;
  7628. var z = this.centerWorld.z - point.z;
  7629. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7630. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7631. return false;
  7632. return true;
  7633. };
  7634. // Statics
  7635. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7636. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7637. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7638. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7639. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7640. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7641. return false;
  7642. return true;
  7643. };
  7644. return BoundingSphere;
  7645. })();
  7646. BABYLON.BoundingSphere = BoundingSphere;
  7647. })(BABYLON || (BABYLON = {}));
  7648. var BABYLON;
  7649. (function (BABYLON) {
  7650. var BoundingBox = (function () {
  7651. function BoundingBox(minimum, maximum) {
  7652. this.minimum = minimum;
  7653. this.maximum = maximum;
  7654. this.vectors = new Array();
  7655. this.vectorsWorld = new Array();
  7656. // Bounding vectors
  7657. this.vectors.push(this.minimum.clone());
  7658. this.vectors.push(this.maximum.clone());
  7659. this.vectors.push(this.minimum.clone());
  7660. this.vectors[2].x = this.maximum.x;
  7661. this.vectors.push(this.minimum.clone());
  7662. this.vectors[3].y = this.maximum.y;
  7663. this.vectors.push(this.minimum.clone());
  7664. this.vectors[4].z = this.maximum.z;
  7665. this.vectors.push(this.maximum.clone());
  7666. this.vectors[5].z = this.minimum.z;
  7667. this.vectors.push(this.maximum.clone());
  7668. this.vectors[6].x = this.minimum.x;
  7669. this.vectors.push(this.maximum.clone());
  7670. this.vectors[7].y = this.minimum.y;
  7671. // OBB
  7672. this.center = this.maximum.add(this.minimum).scale(0.5);
  7673. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7674. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7675. // World
  7676. for (var index = 0; index < this.vectors.length; index++) {
  7677. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7678. }
  7679. this.minimumWorld = BABYLON.Vector3.Zero();
  7680. this.maximumWorld = BABYLON.Vector3.Zero();
  7681. this._update(BABYLON.Matrix.Identity());
  7682. }
  7683. // Methods
  7684. BoundingBox.prototype.getWorldMatrix = function () {
  7685. return this._worldMatrix;
  7686. };
  7687. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7688. this._worldMatrix.copyFrom(matrix);
  7689. return this;
  7690. };
  7691. BoundingBox.prototype._update = function (world) {
  7692. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7693. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7694. for (var index = 0; index < this.vectors.length; index++) {
  7695. var v = this.vectorsWorld[index];
  7696. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7697. if (v.x < this.minimumWorld.x)
  7698. this.minimumWorld.x = v.x;
  7699. if (v.y < this.minimumWorld.y)
  7700. this.minimumWorld.y = v.y;
  7701. if (v.z < this.minimumWorld.z)
  7702. this.minimumWorld.z = v.z;
  7703. if (v.x > this.maximumWorld.x)
  7704. this.maximumWorld.x = v.x;
  7705. if (v.y > this.maximumWorld.y)
  7706. this.maximumWorld.y = v.y;
  7707. if (v.z > this.maximumWorld.z)
  7708. this.maximumWorld.z = v.z;
  7709. }
  7710. // OBB
  7711. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7712. this.center.scaleInPlace(0.5);
  7713. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7714. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7715. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7716. this._worldMatrix = world;
  7717. };
  7718. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7719. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7720. };
  7721. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7722. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7723. };
  7724. BoundingBox.prototype.intersectsPoint = function (point) {
  7725. var delta = -BABYLON.Epsilon;
  7726. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7727. return false;
  7728. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7729. return false;
  7730. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7731. return false;
  7732. return true;
  7733. };
  7734. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7735. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7736. };
  7737. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7738. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7739. return false;
  7740. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7741. return false;
  7742. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7743. return false;
  7744. return true;
  7745. };
  7746. // Statics
  7747. BoundingBox.Intersects = function (box0, box1) {
  7748. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7749. return false;
  7750. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7751. return false;
  7752. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7753. return false;
  7754. return true;
  7755. };
  7756. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7757. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7758. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7759. return (num <= (sphereRadius * sphereRadius));
  7760. };
  7761. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7762. for (var p = 0; p < 6; p++) {
  7763. for (var i = 0; i < 8; i++) {
  7764. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7765. return false;
  7766. }
  7767. }
  7768. }
  7769. return true;
  7770. };
  7771. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7772. for (var p = 0; p < 6; p++) {
  7773. var inCount = 8;
  7774. for (var i = 0; i < 8; i++) {
  7775. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7776. --inCount;
  7777. }
  7778. else {
  7779. break;
  7780. }
  7781. }
  7782. if (inCount === 0)
  7783. return false;
  7784. }
  7785. return true;
  7786. };
  7787. return BoundingBox;
  7788. })();
  7789. BABYLON.BoundingBox = BoundingBox;
  7790. })(BABYLON || (BABYLON = {}));
  7791. var BABYLON;
  7792. (function (BABYLON) {
  7793. var computeBoxExtents = function (axis, box) {
  7794. var p = BABYLON.Vector3.Dot(box.center, axis);
  7795. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7796. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7797. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7798. var r = r0 + r1 + r2;
  7799. return {
  7800. min: p - r,
  7801. max: p + r
  7802. };
  7803. };
  7804. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7805. var axisOverlap = function (axis, box0, box1) {
  7806. var result0 = computeBoxExtents(axis, box0);
  7807. var result1 = computeBoxExtents(axis, box1);
  7808. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7809. };
  7810. var BoundingInfo = (function () {
  7811. function BoundingInfo(minimum, maximum) {
  7812. this.minimum = minimum;
  7813. this.maximum = maximum;
  7814. this._isLocked = false;
  7815. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7816. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7817. }
  7818. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7819. get: function () {
  7820. return this._isLocked;
  7821. },
  7822. set: function (value) {
  7823. this._isLocked = value;
  7824. },
  7825. enumerable: true,
  7826. configurable: true
  7827. });
  7828. // Methods
  7829. BoundingInfo.prototype.update = function (world) {
  7830. if (this._isLocked) {
  7831. return;
  7832. }
  7833. this.boundingBox._update(world);
  7834. this.boundingSphere._update(world);
  7835. };
  7836. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7837. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7838. return false;
  7839. return this.boundingBox.isInFrustum(frustumPlanes);
  7840. };
  7841. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7842. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7843. };
  7844. BoundingInfo.prototype._checkCollision = function (collider) {
  7845. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7846. };
  7847. BoundingInfo.prototype.intersectsPoint = function (point) {
  7848. if (!this.boundingSphere.centerWorld) {
  7849. return false;
  7850. }
  7851. if (!this.boundingSphere.intersectsPoint(point)) {
  7852. return false;
  7853. }
  7854. if (!this.boundingBox.intersectsPoint(point)) {
  7855. return false;
  7856. }
  7857. return true;
  7858. };
  7859. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7860. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7861. return false;
  7862. }
  7863. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7864. return false;
  7865. }
  7866. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7867. return false;
  7868. }
  7869. if (!precise) {
  7870. return true;
  7871. }
  7872. var box0 = this.boundingBox;
  7873. var box1 = boundingInfo.boundingBox;
  7874. if (!axisOverlap(box0.directions[0], box0, box1))
  7875. return false;
  7876. if (!axisOverlap(box0.directions[1], box0, box1))
  7877. return false;
  7878. if (!axisOverlap(box0.directions[2], box0, box1))
  7879. return false;
  7880. if (!axisOverlap(box1.directions[0], box0, box1))
  7881. return false;
  7882. if (!axisOverlap(box1.directions[1], box0, box1))
  7883. return false;
  7884. if (!axisOverlap(box1.directions[2], box0, box1))
  7885. return false;
  7886. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7887. return false;
  7888. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7889. return false;
  7890. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7891. return false;
  7892. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7893. return false;
  7894. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7895. return false;
  7896. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7897. return false;
  7898. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7899. return false;
  7900. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7901. return false;
  7902. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7903. return false;
  7904. return true;
  7905. };
  7906. return BoundingInfo;
  7907. })();
  7908. BABYLON.BoundingInfo = BoundingInfo;
  7909. })(BABYLON || (BABYLON = {}));
  7910. var BABYLON;
  7911. (function (BABYLON) {
  7912. var Ray = (function () {
  7913. function Ray(origin, direction, length) {
  7914. if (length === void 0) { length = Number.MAX_VALUE; }
  7915. this.origin = origin;
  7916. this.direction = direction;
  7917. this.length = length;
  7918. }
  7919. // Methods
  7920. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  7921. var d = 0.0;
  7922. var maxValue = Number.MAX_VALUE;
  7923. var inv;
  7924. var min;
  7925. var max;
  7926. var temp;
  7927. if (Math.abs(this.direction.x) < 0.0000001) {
  7928. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  7929. return false;
  7930. }
  7931. }
  7932. else {
  7933. inv = 1.0 / this.direction.x;
  7934. min = (minimum.x - this.origin.x) * inv;
  7935. max = (maximum.x - this.origin.x) * inv;
  7936. if (max === -Infinity) {
  7937. max = Infinity;
  7938. }
  7939. if (min > max) {
  7940. temp = min;
  7941. min = max;
  7942. max = temp;
  7943. }
  7944. d = Math.max(min, d);
  7945. maxValue = Math.min(max, maxValue);
  7946. if (d > maxValue) {
  7947. return false;
  7948. }
  7949. }
  7950. if (Math.abs(this.direction.y) < 0.0000001) {
  7951. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  7952. return false;
  7953. }
  7954. }
  7955. else {
  7956. inv = 1.0 / this.direction.y;
  7957. min = (minimum.y - this.origin.y) * inv;
  7958. max = (maximum.y - this.origin.y) * inv;
  7959. if (max === -Infinity) {
  7960. max = Infinity;
  7961. }
  7962. if (min > max) {
  7963. temp = min;
  7964. min = max;
  7965. max = temp;
  7966. }
  7967. d = Math.max(min, d);
  7968. maxValue = Math.min(max, maxValue);
  7969. if (d > maxValue) {
  7970. return false;
  7971. }
  7972. }
  7973. if (Math.abs(this.direction.z) < 0.0000001) {
  7974. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  7975. return false;
  7976. }
  7977. }
  7978. else {
  7979. inv = 1.0 / this.direction.z;
  7980. min = (minimum.z - this.origin.z) * inv;
  7981. max = (maximum.z - this.origin.z) * inv;
  7982. if (max === -Infinity) {
  7983. max = Infinity;
  7984. }
  7985. if (min > max) {
  7986. temp = min;
  7987. min = max;
  7988. max = temp;
  7989. }
  7990. d = Math.max(min, d);
  7991. maxValue = Math.min(max, maxValue);
  7992. if (d > maxValue) {
  7993. return false;
  7994. }
  7995. }
  7996. return true;
  7997. };
  7998. Ray.prototype.intersectsBox = function (box) {
  7999. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8000. };
  8001. Ray.prototype.intersectsSphere = function (sphere) {
  8002. var x = sphere.center.x - this.origin.x;
  8003. var y = sphere.center.y - this.origin.y;
  8004. var z = sphere.center.z - this.origin.z;
  8005. var pyth = (x * x) + (y * y) + (z * z);
  8006. var rr = sphere.radius * sphere.radius;
  8007. if (pyth <= rr) {
  8008. return true;
  8009. }
  8010. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8011. if (dot < 0.0) {
  8012. return false;
  8013. }
  8014. var temp = pyth - (dot * dot);
  8015. return temp <= rr;
  8016. };
  8017. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8018. if (!this._edge1) {
  8019. this._edge1 = BABYLON.Vector3.Zero();
  8020. this._edge2 = BABYLON.Vector3.Zero();
  8021. this._pvec = BABYLON.Vector3.Zero();
  8022. this._tvec = BABYLON.Vector3.Zero();
  8023. this._qvec = BABYLON.Vector3.Zero();
  8024. }
  8025. vertex1.subtractToRef(vertex0, this._edge1);
  8026. vertex2.subtractToRef(vertex0, this._edge2);
  8027. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8028. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8029. if (det === 0) {
  8030. return null;
  8031. }
  8032. var invdet = 1 / det;
  8033. this.origin.subtractToRef(vertex0, this._tvec);
  8034. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8035. if (bu < 0 || bu > 1.0) {
  8036. return null;
  8037. }
  8038. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8039. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8040. if (bv < 0 || bu + bv > 1.0) {
  8041. return null;
  8042. }
  8043. //check if the distance is longer than the predefined length.
  8044. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8045. if (distance > this.length) {
  8046. return null;
  8047. }
  8048. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8049. };
  8050. // Statics
  8051. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8052. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8053. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8054. var direction = end.subtract(start);
  8055. direction.normalize();
  8056. return new Ray(start, direction);
  8057. };
  8058. /**
  8059. * 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
  8060. * transformed to the given world matrix.
  8061. * @param origin The origin point
  8062. * @param end The end point
  8063. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8064. */
  8065. Ray.CreateNewFromTo = function (origin, end, world) {
  8066. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8067. var direction = end.subtract(origin);
  8068. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8069. direction.normalize();
  8070. return Ray.Transform(new Ray(origin, direction, length), world);
  8071. };
  8072. Ray.Transform = function (ray, matrix) {
  8073. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8074. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8075. return new Ray(newOrigin, newDirection, ray.length);
  8076. };
  8077. return Ray;
  8078. })();
  8079. BABYLON.Ray = Ray;
  8080. })(BABYLON || (BABYLON = {}));
  8081. var BABYLON;
  8082. (function (BABYLON) {
  8083. var AbstractMesh = (function (_super) {
  8084. __extends(AbstractMesh, _super);
  8085. // Constructor
  8086. function AbstractMesh(name, scene) {
  8087. var _this = this;
  8088. _super.call(this, name, scene);
  8089. // Properties
  8090. this.definedFacingForward = true; // orientation for POV movement & rotation
  8091. this.position = new BABYLON.Vector3(0, 0, 0);
  8092. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8093. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8094. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8095. this.visibility = 1.0;
  8096. this.alphaIndex = Number.MAX_VALUE;
  8097. this.infiniteDistance = false;
  8098. this.isVisible = true;
  8099. this.isPickable = true;
  8100. this.showBoundingBox = false;
  8101. this.showSubMeshesBoundingBox = false;
  8102. this.onDispose = null;
  8103. this.isBlocker = false;
  8104. this.renderingGroupId = 0;
  8105. this.receiveShadows = false;
  8106. this.renderOutline = false;
  8107. this.outlineColor = BABYLON.Color3.Red();
  8108. this.outlineWidth = 0.02;
  8109. this.renderOverlay = false;
  8110. this.overlayColor = BABYLON.Color3.Red();
  8111. this.overlayAlpha = 0.5;
  8112. this.hasVertexAlpha = false;
  8113. this.useVertexColors = true;
  8114. this.applyFog = true;
  8115. this.computeBonesUsingShaders = true;
  8116. this.scalingDeterminant = 1;
  8117. this.numBoneInfluencers = 4;
  8118. this.useOctreeForRenderingSelection = true;
  8119. this.useOctreeForPicking = true;
  8120. this.useOctreeForCollisions = true;
  8121. this.layerMask = 0x0FFFFFFF;
  8122. this.alwaysSelectAsActiveMesh = false;
  8123. // Collisions
  8124. this._checkCollisions = false;
  8125. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8126. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8127. this._collider = new BABYLON.Collider();
  8128. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8129. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8130. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8131. // Edges
  8132. this.edgesWidth = 1;
  8133. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8134. // Cache
  8135. this._localWorld = BABYLON.Matrix.Zero();
  8136. this._worldMatrix = BABYLON.Matrix.Zero();
  8137. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8138. this._absolutePosition = BABYLON.Vector3.Zero();
  8139. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8140. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8141. this._isDirty = false;
  8142. this._pivotMatrix = BABYLON.Matrix.Identity();
  8143. this._isDisposed = false;
  8144. this._renderId = 0;
  8145. this._intersectionsInProgress = new Array();
  8146. this._onAfterWorldMatrixUpdate = new Array();
  8147. this._isWorldMatrixFrozen = false;
  8148. this._unIndexed = false;
  8149. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8150. if (collidedMesh === void 0) { collidedMesh = null; }
  8151. //TODO move this to the collision coordinator!
  8152. if (_this.getScene().workerCollisions)
  8153. newPosition.multiplyInPlace(_this._collider.radius);
  8154. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8155. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8156. _this.position.addInPlace(_this._diffPositionForCollisions);
  8157. }
  8158. if (_this.onCollide && collidedMesh) {
  8159. _this.onCollide(collidedMesh);
  8160. }
  8161. if (_this.onCollisionPositionChange) {
  8162. _this.onCollisionPositionChange(_this.position);
  8163. }
  8164. };
  8165. scene.addMesh(this);
  8166. }
  8167. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8168. get: function () {
  8169. return AbstractMesh._BILLBOARDMODE_NONE;
  8170. },
  8171. enumerable: true,
  8172. configurable: true
  8173. });
  8174. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8175. get: function () {
  8176. return AbstractMesh._BILLBOARDMODE_X;
  8177. },
  8178. enumerable: true,
  8179. configurable: true
  8180. });
  8181. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8182. get: function () {
  8183. return AbstractMesh._BILLBOARDMODE_Y;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8189. get: function () {
  8190. return AbstractMesh._BILLBOARDMODE_Z;
  8191. },
  8192. enumerable: true,
  8193. configurable: true
  8194. });
  8195. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8196. get: function () {
  8197. return AbstractMesh._BILLBOARDMODE_ALL;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8203. get: function () {
  8204. return this._skeleton;
  8205. },
  8206. set: function (value) {
  8207. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8208. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8209. }
  8210. if (value && value.needInitialSkinMatrix) {
  8211. value._registerMeshWithPoseMatrix(this);
  8212. }
  8213. this._skeleton = value;
  8214. if (!this._skeleton) {
  8215. this._bonesTransformMatrices = null;
  8216. }
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. /**
  8222. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8223. */
  8224. AbstractMesh.prototype.toString = function (fullDetails) {
  8225. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8226. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8227. if (this._skeleton) {
  8228. ret += ", skeleton: " + this._skeleton.name;
  8229. }
  8230. if (fullDetails) {
  8231. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8232. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8233. }
  8234. return ret;
  8235. };
  8236. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8237. /**
  8238. * Getting the rotation object.
  8239. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8240. */
  8241. get: function () {
  8242. return this._rotation;
  8243. },
  8244. set: function (newRotation) {
  8245. this._rotation = newRotation;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8251. get: function () {
  8252. return this._scaling;
  8253. },
  8254. set: function (newScaling) {
  8255. this._scaling = newScaling;
  8256. if (this.physicsImpostor) {
  8257. this.physicsImpostor.forceUpdate();
  8258. }
  8259. },
  8260. enumerable: true,
  8261. configurable: true
  8262. });
  8263. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8264. get: function () {
  8265. return this._rotationQuaternion;
  8266. },
  8267. set: function (quaternion) {
  8268. this._rotationQuaternion = quaternion;
  8269. //reset the rotation vector.
  8270. if (quaternion && this.rotation.length()) {
  8271. this.rotation.copyFromFloats(0, 0, 0);
  8272. }
  8273. },
  8274. enumerable: true,
  8275. configurable: true
  8276. });
  8277. // Methods
  8278. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8279. this._poseMatrix.copyFrom(matrix);
  8280. };
  8281. AbstractMesh.prototype.getPoseMatrix = function () {
  8282. return this._poseMatrix;
  8283. };
  8284. AbstractMesh.prototype.disableEdgesRendering = function () {
  8285. if (this._edgesRenderer !== undefined) {
  8286. this._edgesRenderer.dispose();
  8287. this._edgesRenderer = undefined;
  8288. }
  8289. };
  8290. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8291. if (epsilon === void 0) { epsilon = 0.95; }
  8292. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8293. this.disableEdgesRendering();
  8294. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8295. };
  8296. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8297. get: function () {
  8298. return false;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. AbstractMesh.prototype.getLOD = function (camera) {
  8304. return this;
  8305. };
  8306. AbstractMesh.prototype.getTotalVertices = function () {
  8307. return 0;
  8308. };
  8309. AbstractMesh.prototype.getIndices = function () {
  8310. return null;
  8311. };
  8312. AbstractMesh.prototype.getVerticesData = function (kind) {
  8313. return null;
  8314. };
  8315. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8316. return false;
  8317. };
  8318. AbstractMesh.prototype.getBoundingInfo = function () {
  8319. if (this._masterMesh) {
  8320. return this._masterMesh.getBoundingInfo();
  8321. }
  8322. if (!this._boundingInfo) {
  8323. this._updateBoundingInfo();
  8324. }
  8325. return this._boundingInfo;
  8326. };
  8327. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8328. get: function () {
  8329. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8330. },
  8331. enumerable: true,
  8332. configurable: true
  8333. });
  8334. AbstractMesh.prototype._preActivate = function () {
  8335. };
  8336. AbstractMesh.prototype._activate = function (renderId) {
  8337. this._renderId = renderId;
  8338. };
  8339. AbstractMesh.prototype.getWorldMatrix = function () {
  8340. if (this._masterMesh) {
  8341. return this._masterMesh.getWorldMatrix();
  8342. }
  8343. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8344. this.computeWorldMatrix();
  8345. }
  8346. return this._worldMatrix;
  8347. };
  8348. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8349. get: function () {
  8350. return this._worldMatrix;
  8351. },
  8352. enumerable: true,
  8353. configurable: true
  8354. });
  8355. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8356. get: function () {
  8357. return this._absolutePosition;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8363. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8364. this.computeWorldMatrix(true);
  8365. this._isWorldMatrixFrozen = true;
  8366. };
  8367. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8368. this._isWorldMatrixFrozen = false;
  8369. this.computeWorldMatrix(true);
  8370. };
  8371. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8372. get: function () {
  8373. return this._isWorldMatrixFrozen;
  8374. },
  8375. enumerable: true,
  8376. configurable: true
  8377. });
  8378. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8379. axis.normalize();
  8380. if (!this.rotationQuaternion) {
  8381. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8382. this.rotation = BABYLON.Vector3.Zero();
  8383. }
  8384. var rotationQuaternion;
  8385. if (!space || space === BABYLON.Space.LOCAL) {
  8386. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8387. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8388. }
  8389. else {
  8390. if (this.parent) {
  8391. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8392. invertParentWorldMatrix.invert();
  8393. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8394. }
  8395. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8396. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8397. }
  8398. };
  8399. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8400. var displacementVector = axis.scale(distance);
  8401. if (!space || space === BABYLON.Space.LOCAL) {
  8402. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8403. this.setPositionWithLocalVector(tempV3);
  8404. }
  8405. else {
  8406. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8407. }
  8408. };
  8409. AbstractMesh.prototype.getAbsolutePosition = function () {
  8410. this.computeWorldMatrix();
  8411. return this._absolutePosition;
  8412. };
  8413. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8414. if (!absolutePosition) {
  8415. return;
  8416. }
  8417. var absolutePositionX;
  8418. var absolutePositionY;
  8419. var absolutePositionZ;
  8420. if (absolutePosition.x === undefined) {
  8421. if (arguments.length < 3) {
  8422. return;
  8423. }
  8424. absolutePositionX = arguments[0];
  8425. absolutePositionY = arguments[1];
  8426. absolutePositionZ = arguments[2];
  8427. }
  8428. else {
  8429. absolutePositionX = absolutePosition.x;
  8430. absolutePositionY = absolutePosition.y;
  8431. absolutePositionZ = absolutePosition.z;
  8432. }
  8433. if (this.parent) {
  8434. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8435. invertParentWorldMatrix.invert();
  8436. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8437. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8438. }
  8439. else {
  8440. this.position.x = absolutePositionX;
  8441. this.position.y = absolutePositionY;
  8442. this.position.z = absolutePositionZ;
  8443. }
  8444. };
  8445. // ================================== Point of View Movement =================================
  8446. /**
  8447. * Perform relative position change from the point of view of behind the front of the mesh.
  8448. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8449. * Supports definition of mesh facing forward or backward.
  8450. * @param {number} amountRight
  8451. * @param {number} amountUp
  8452. * @param {number} amountForward
  8453. */
  8454. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8455. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8456. };
  8457. /**
  8458. * Calculate relative position change from the point of view of behind the front of the mesh.
  8459. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8460. * Supports definition of mesh facing forward or backward.
  8461. * @param {number} amountRight
  8462. * @param {number} amountUp
  8463. * @param {number} amountForward
  8464. */
  8465. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8466. var rotMatrix = new BABYLON.Matrix();
  8467. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8468. rotQuaternion.toRotationMatrix(rotMatrix);
  8469. var translationDelta = BABYLON.Vector3.Zero();
  8470. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8471. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8472. return translationDelta;
  8473. };
  8474. // ================================== Point of View Rotation =================================
  8475. /**
  8476. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8477. * Supports definition of mesh facing forward or backward.
  8478. * @param {number} flipBack
  8479. * @param {number} twirlClockwise
  8480. * @param {number} tiltRight
  8481. */
  8482. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8483. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8484. };
  8485. /**
  8486. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8487. * Supports definition of mesh facing forward or backward.
  8488. * @param {number} flipBack
  8489. * @param {number} twirlClockwise
  8490. * @param {number} tiltRight
  8491. */
  8492. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8493. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8494. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8495. };
  8496. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8497. this._pivotMatrix = matrix;
  8498. this._cache.pivotMatrixUpdated = true;
  8499. };
  8500. AbstractMesh.prototype.getPivotMatrix = function () {
  8501. return this._pivotMatrix;
  8502. };
  8503. AbstractMesh.prototype._isSynchronized = function () {
  8504. if (this._isDirty) {
  8505. return false;
  8506. }
  8507. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8508. return false;
  8509. if (this._cache.pivotMatrixUpdated) {
  8510. return false;
  8511. }
  8512. if (this.infiniteDistance) {
  8513. return false;
  8514. }
  8515. if (!this._cache.position.equals(this.position))
  8516. return false;
  8517. if (this.rotationQuaternion) {
  8518. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8519. return false;
  8520. }
  8521. else {
  8522. if (!this._cache.rotation.equals(this.rotation))
  8523. return false;
  8524. }
  8525. if (!this._cache.scaling.equals(this.scaling))
  8526. return false;
  8527. return true;
  8528. };
  8529. AbstractMesh.prototype._initCache = function () {
  8530. _super.prototype._initCache.call(this);
  8531. this._cache.localMatrixUpdated = false;
  8532. this._cache.position = BABYLON.Vector3.Zero();
  8533. this._cache.scaling = BABYLON.Vector3.Zero();
  8534. this._cache.rotation = BABYLON.Vector3.Zero();
  8535. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8536. this._cache.billboardMode = -1;
  8537. };
  8538. AbstractMesh.prototype.markAsDirty = function (property) {
  8539. if (property === "rotation") {
  8540. this.rotationQuaternion = null;
  8541. }
  8542. this._currentRenderId = Number.MAX_VALUE;
  8543. this._isDirty = true;
  8544. };
  8545. AbstractMesh.prototype._updateBoundingInfo = function () {
  8546. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8547. this._boundingInfo.update(this.worldMatrixFromCache);
  8548. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8549. };
  8550. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8551. if (!this.subMeshes) {
  8552. return;
  8553. }
  8554. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8555. var subMesh = this.subMeshes[subIndex];
  8556. if (!subMesh.IsGlobal) {
  8557. subMesh.updateBoundingInfo(matrix);
  8558. }
  8559. }
  8560. };
  8561. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8562. if (this._isWorldMatrixFrozen) {
  8563. return this._worldMatrix;
  8564. }
  8565. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8566. this._currentRenderId = this.getScene().getRenderId();
  8567. return this._worldMatrix;
  8568. }
  8569. this._cache.position.copyFrom(this.position);
  8570. this._cache.scaling.copyFrom(this.scaling);
  8571. this._cache.pivotMatrixUpdated = false;
  8572. this._cache.billboardMode = this.billboardMode;
  8573. this._currentRenderId = this.getScene().getRenderId();
  8574. this._isDirty = false;
  8575. // Scaling
  8576. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8577. // Rotation
  8578. //rotate, if quaternion is set and rotation was used
  8579. if (this.rotationQuaternion) {
  8580. var len = this.rotation.length();
  8581. if (len) {
  8582. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8583. this.rotation.copyFromFloats(0, 0, 0);
  8584. }
  8585. }
  8586. if (this.rotationQuaternion) {
  8587. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8588. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8589. }
  8590. else {
  8591. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8592. this._cache.rotation.copyFrom(this.rotation);
  8593. }
  8594. // Translation
  8595. if (this.infiniteDistance && !this.parent) {
  8596. var camera = this.getScene().activeCamera;
  8597. if (camera) {
  8598. var cameraWorldMatrix = camera.getWorldMatrix();
  8599. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8600. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8601. }
  8602. }
  8603. else {
  8604. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8605. }
  8606. // Composing transformations
  8607. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8608. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8609. // Billboarding
  8610. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8611. var localPosition = this.position.clone();
  8612. var zero = this.getScene().activeCamera.globalPosition.clone();
  8613. if (this.parent && this.parent.position) {
  8614. localPosition.addInPlace(this.parent.position);
  8615. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8616. }
  8617. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8618. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8619. zero.x = localPosition.x + BABYLON.Epsilon;
  8620. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8621. zero.y = localPosition.y + BABYLON.Epsilon;
  8622. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8623. zero.z = localPosition.z + BABYLON.Epsilon;
  8624. }
  8625. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8626. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8627. BABYLON.Tmp.Matrix[3].invert();
  8628. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8629. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8630. }
  8631. // Local world
  8632. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8633. // Parent
  8634. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8635. this._markSyncedWithParent();
  8636. if (this._meshToBoneReferal) {
  8637. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8638. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8639. }
  8640. else {
  8641. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8642. }
  8643. }
  8644. else {
  8645. this._worldMatrix.copyFrom(this._localWorld);
  8646. }
  8647. // Bounding info
  8648. this._updateBoundingInfo();
  8649. // Absolute position
  8650. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8651. // Callbacks
  8652. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8653. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8654. }
  8655. if (!this._poseMatrix) {
  8656. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8657. }
  8658. return this._worldMatrix;
  8659. };
  8660. /**
  8661. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8662. * @param func: callback function to add
  8663. */
  8664. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8665. this._onAfterWorldMatrixUpdate.push(func);
  8666. };
  8667. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8668. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8669. if (index > -1) {
  8670. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8671. }
  8672. };
  8673. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8674. this.computeWorldMatrix();
  8675. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8676. };
  8677. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8678. this.computeWorldMatrix();
  8679. var invLocalWorldMatrix = this._localWorld.clone();
  8680. invLocalWorldMatrix.invert();
  8681. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8682. };
  8683. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8684. this.computeWorldMatrix(true);
  8685. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8686. };
  8687. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8688. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8689. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8690. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8691. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8692. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8693. /// <returns>Mesh oriented towards targetMesh</returns>
  8694. yawCor = yawCor || 0; // default to zero if undefined
  8695. pitchCor = pitchCor || 0;
  8696. rollCor = rollCor || 0;
  8697. var dv = targetPoint.subtract(this.position);
  8698. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8699. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8700. var pitch = Math.atan2(dv.y, len);
  8701. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8702. };
  8703. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8704. this._meshToBoneReferal = affectedMesh;
  8705. this.parent = bone;
  8706. if (bone.getWorldMatrix().determinant() < 0) {
  8707. this.scalingDeterminant *= -1;
  8708. }
  8709. };
  8710. AbstractMesh.prototype.detachFromBone = function () {
  8711. if (this.parent.getWorldMatrix().determinant() < 0) {
  8712. this.scalingDeterminant *= -1;
  8713. }
  8714. this._meshToBoneReferal = null;
  8715. this.parent = null;
  8716. };
  8717. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8718. return this._boundingInfo.isInFrustum(frustumPlanes);
  8719. };
  8720. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8721. if (!camera) {
  8722. camera = this.getScene().activeCamera;
  8723. }
  8724. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8725. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8726. return false;
  8727. }
  8728. return true;
  8729. };
  8730. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8731. if (!this._boundingInfo || !mesh._boundingInfo) {
  8732. return false;
  8733. }
  8734. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8735. };
  8736. AbstractMesh.prototype.intersectsPoint = function (point) {
  8737. if (!this._boundingInfo) {
  8738. return false;
  8739. }
  8740. return this._boundingInfo.intersectsPoint(point);
  8741. };
  8742. // Physics
  8743. /**
  8744. * @Deprecated. Use new PhysicsImpostor instead.
  8745. * */
  8746. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8747. //legacy support
  8748. if (impostor.impostor) {
  8749. options = impostor;
  8750. impostor = impostor.impostor;
  8751. }
  8752. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8753. return this.physicsImpostor.physicsBody;
  8754. };
  8755. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8756. return this.physicsImpostor;
  8757. };
  8758. /**
  8759. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8760. */
  8761. AbstractMesh.prototype.getPhysicsMass = function () {
  8762. return this.physicsImpostor.getParam("mass");
  8763. };
  8764. /**
  8765. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8766. */
  8767. AbstractMesh.prototype.getPhysicsFriction = function () {
  8768. return this.physicsImpostor.getParam("friction");
  8769. };
  8770. /**
  8771. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8772. */
  8773. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8774. return this.physicsImpostor.getParam("resitution");
  8775. };
  8776. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8777. if (!camera) {
  8778. camera = this.getScene().activeCamera;
  8779. }
  8780. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8781. };
  8782. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8783. if (!camera) {
  8784. camera = this.getScene().activeCamera;
  8785. }
  8786. return this.absolutePosition.subtract(camera.position).length();
  8787. };
  8788. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8789. if (!this.physicsImpostor) {
  8790. return;
  8791. }
  8792. this.physicsImpostor.applyImpulse(force, contactPoint);
  8793. };
  8794. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8795. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8796. return;
  8797. }
  8798. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8799. mainPivot: pivot1,
  8800. connectedPivot: pivot2,
  8801. nativeParams: options
  8802. });
  8803. };
  8804. /**
  8805. * @Deprecated
  8806. */
  8807. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8808. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8809. this.updatePhysicsBody();
  8810. };
  8811. /**
  8812. * @Deprecated
  8813. * Calling this function is not needed anymore.
  8814. * The physics engine takes care of transofmration automatically.
  8815. */
  8816. AbstractMesh.prototype.updatePhysicsBody = function () {
  8817. //Unneeded
  8818. };
  8819. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8820. // Collisions
  8821. get: function () {
  8822. return this._checkCollisions;
  8823. },
  8824. set: function (collisionEnabled) {
  8825. this._checkCollisions = collisionEnabled;
  8826. if (this.getScene().workerCollisions) {
  8827. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8828. }
  8829. },
  8830. enumerable: true,
  8831. configurable: true
  8832. });
  8833. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8834. var globalPosition = this.getAbsolutePosition();
  8835. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8836. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8837. this._collider.radius = this.ellipsoid;
  8838. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8839. };
  8840. // Submeshes octree
  8841. /**
  8842. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8843. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8844. */
  8845. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8846. if (maxCapacity === void 0) { maxCapacity = 64; }
  8847. if (maxDepth === void 0) { maxDepth = 2; }
  8848. if (!this._submeshesOctree) {
  8849. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8850. }
  8851. this.computeWorldMatrix(true);
  8852. // Update octree
  8853. var bbox = this.getBoundingInfo().boundingBox;
  8854. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8855. return this._submeshesOctree;
  8856. };
  8857. // Collisions
  8858. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8859. this._generatePointsArray();
  8860. // Transformation
  8861. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8862. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8863. subMesh._lastColliderWorldVertices = [];
  8864. subMesh._trianglePlanes = [];
  8865. var start = subMesh.verticesStart;
  8866. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8867. for (var i = start; i < end; i++) {
  8868. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8869. }
  8870. }
  8871. // Collide
  8872. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8873. if (collider.collisionFound) {
  8874. collider.collidedMesh = this;
  8875. }
  8876. };
  8877. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8878. var subMeshes;
  8879. var len;
  8880. // Octrees
  8881. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8882. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8883. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8884. len = intersections.length;
  8885. subMeshes = intersections.data;
  8886. }
  8887. else {
  8888. subMeshes = this.subMeshes;
  8889. len = subMeshes.length;
  8890. }
  8891. for (var index = 0; index < len; index++) {
  8892. var subMesh = subMeshes[index];
  8893. // Bounding test
  8894. if (len > 1 && !subMesh._checkCollision(collider))
  8895. continue;
  8896. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8897. }
  8898. };
  8899. AbstractMesh.prototype._checkCollision = function (collider) {
  8900. // Bounding box test
  8901. if (!this._boundingInfo._checkCollision(collider))
  8902. return;
  8903. // Transformation matrix
  8904. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8905. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8906. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8907. };
  8908. // Picking
  8909. AbstractMesh.prototype._generatePointsArray = function () {
  8910. return false;
  8911. };
  8912. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8913. var pickingInfo = new BABYLON.PickingInfo();
  8914. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8915. return pickingInfo;
  8916. }
  8917. if (!this._generatePointsArray()) {
  8918. return pickingInfo;
  8919. }
  8920. var intersectInfo = null;
  8921. // Octrees
  8922. var subMeshes;
  8923. var len;
  8924. if (this._submeshesOctree && this.useOctreeForPicking) {
  8925. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8926. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8927. len = intersections.length;
  8928. subMeshes = intersections.data;
  8929. }
  8930. else {
  8931. subMeshes = this.subMeshes;
  8932. len = subMeshes.length;
  8933. }
  8934. for (var index = 0; index < len; index++) {
  8935. var subMesh = subMeshes[index];
  8936. // Bounding test
  8937. if (len > 1 && !subMesh.canIntersects(ray))
  8938. continue;
  8939. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8940. if (currentIntersectInfo) {
  8941. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8942. intersectInfo = currentIntersectInfo;
  8943. intersectInfo.subMeshId = index;
  8944. if (fastCheck) {
  8945. break;
  8946. }
  8947. }
  8948. }
  8949. }
  8950. if (intersectInfo) {
  8951. // Get picked point
  8952. var world = this.getWorldMatrix();
  8953. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8954. var direction = ray.direction.clone();
  8955. direction = direction.scale(intersectInfo.distance);
  8956. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8957. var pickedPoint = worldOrigin.add(worldDirection);
  8958. // Return result
  8959. pickingInfo.hit = true;
  8960. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8961. pickingInfo.pickedPoint = pickedPoint;
  8962. pickingInfo.pickedMesh = this;
  8963. pickingInfo.bu = intersectInfo.bu;
  8964. pickingInfo.bv = intersectInfo.bv;
  8965. pickingInfo.faceId = intersectInfo.faceId;
  8966. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8967. return pickingInfo;
  8968. }
  8969. return pickingInfo;
  8970. };
  8971. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8972. return null;
  8973. };
  8974. AbstractMesh.prototype.releaseSubMeshes = function () {
  8975. if (this.subMeshes) {
  8976. while (this.subMeshes.length) {
  8977. this.subMeshes[0].dispose();
  8978. }
  8979. }
  8980. else {
  8981. this.subMeshes = new Array();
  8982. }
  8983. };
  8984. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8985. var index;
  8986. // Action manager
  8987. if (this.actionManager) {
  8988. this.actionManager.dispose();
  8989. this.actionManager = null;
  8990. }
  8991. // Skeleton
  8992. this.skeleton = null;
  8993. // Animations
  8994. this.getScene().stopAnimation(this);
  8995. // Physics
  8996. if (this.physicsImpostor) {
  8997. this.physicsImpostor.dispose(!doNotRecurse);
  8998. }
  8999. // Intersections in progress
  9000. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9001. var other = this._intersectionsInProgress[index];
  9002. var pos = other._intersectionsInProgress.indexOf(this);
  9003. other._intersectionsInProgress.splice(pos, 1);
  9004. }
  9005. this._intersectionsInProgress = [];
  9006. // Edges
  9007. if (this._edgesRenderer) {
  9008. this._edgesRenderer.dispose();
  9009. this._edgesRenderer = null;
  9010. }
  9011. // SubMeshes
  9012. this.releaseSubMeshes();
  9013. // Remove from scene
  9014. this.getScene().removeMesh(this);
  9015. if (!doNotRecurse) {
  9016. // Particles
  9017. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9018. if (this.getScene().particleSystems[index].emitter === this) {
  9019. this.getScene().particleSystems[index].dispose();
  9020. index--;
  9021. }
  9022. }
  9023. // Children
  9024. var objects = this.getDescendants(true);
  9025. for (index = 0; index < objects.length; index++) {
  9026. objects[index].dispose();
  9027. }
  9028. }
  9029. else {
  9030. var childMeshes = this.getChildMeshes(true);
  9031. for (index = 0; childMeshes.length; index++) {
  9032. var child = childMeshes[index];
  9033. child.parent = null;
  9034. child.computeWorldMatrix(true);
  9035. }
  9036. }
  9037. _super.prototype.dispose.call(this);
  9038. this._onAfterWorldMatrixUpdate = [];
  9039. this._isDisposed = true;
  9040. // Callback
  9041. if (this.onDispose) {
  9042. this.onDispose();
  9043. }
  9044. };
  9045. // Statics
  9046. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9047. AbstractMesh._BILLBOARDMODE_X = 1;
  9048. AbstractMesh._BILLBOARDMODE_Y = 2;
  9049. AbstractMesh._BILLBOARDMODE_Z = 4;
  9050. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9051. return AbstractMesh;
  9052. })(BABYLON.Node);
  9053. BABYLON.AbstractMesh = AbstractMesh;
  9054. })(BABYLON || (BABYLON = {}));
  9055. var BABYLON;
  9056. (function (BABYLON) {
  9057. var Light = (function (_super) {
  9058. __extends(Light, _super);
  9059. function Light(name, scene) {
  9060. _super.call(this, name, scene);
  9061. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9062. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9063. this.intensity = 1.0;
  9064. this.range = Number.MAX_VALUE;
  9065. this.includeOnlyWithLayerMask = 0;
  9066. this.includedOnlyMeshes = new Array();
  9067. this.excludedMeshes = new Array();
  9068. this.excludeWithLayerMask = 0;
  9069. // PBR Properties.
  9070. this.radius = 0.00001;
  9071. this._excludedMeshesIds = new Array();
  9072. this._includedOnlyMeshesIds = new Array();
  9073. scene.addLight(this);
  9074. }
  9075. /**
  9076. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9077. */
  9078. Light.prototype.toString = function (fullDetails) {
  9079. var ret = "Name: " + this.name;
  9080. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9081. if (this.animations) {
  9082. for (var i = 0; i < this.animations.length; i++) {
  9083. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9084. }
  9085. }
  9086. if (fullDetails) {
  9087. }
  9088. return ret;
  9089. };
  9090. Light.prototype.getShadowGenerator = function () {
  9091. return this._shadowGenerator;
  9092. };
  9093. Light.prototype.getAbsolutePosition = function () {
  9094. return BABYLON.Vector3.Zero();
  9095. };
  9096. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9097. };
  9098. Light.prototype._getWorldMatrix = function () {
  9099. return BABYLON.Matrix.Identity();
  9100. };
  9101. Light.prototype.canAffectMesh = function (mesh) {
  9102. if (!mesh) {
  9103. return true;
  9104. }
  9105. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9106. return false;
  9107. }
  9108. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9109. return false;
  9110. }
  9111. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9112. return false;
  9113. }
  9114. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9115. return false;
  9116. }
  9117. return true;
  9118. };
  9119. Light.prototype.getWorldMatrix = function () {
  9120. this._currentRenderId = this.getScene().getRenderId();
  9121. var worldMatrix = this._getWorldMatrix();
  9122. if (this.parent && this.parent.getWorldMatrix) {
  9123. if (!this._parentedWorldMatrix) {
  9124. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9125. }
  9126. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9127. this._markSyncedWithParent();
  9128. return this._parentedWorldMatrix;
  9129. }
  9130. return worldMatrix;
  9131. };
  9132. Light.prototype.dispose = function () {
  9133. if (this._shadowGenerator) {
  9134. this._shadowGenerator.dispose();
  9135. this._shadowGenerator = null;
  9136. }
  9137. // Animations
  9138. this.getScene().stopAnimation(this);
  9139. // Remove from scene
  9140. this.getScene().removeLight(this);
  9141. _super.prototype.dispose.call(this);
  9142. };
  9143. Light.prototype.getTypeID = function () {
  9144. return 0;
  9145. };
  9146. Light.prototype.clone = function (name) {
  9147. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9148. };
  9149. Light.prototype.serialize = function () {
  9150. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9151. // Type
  9152. serializationObject.type = this.getTypeID();
  9153. // Parent
  9154. if (this.parent) {
  9155. serializationObject.parentId = this.parent.id;
  9156. }
  9157. // Animations
  9158. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9159. serializationObject.ranges = this.serializeAnimationRanges();
  9160. return serializationObject;
  9161. };
  9162. Light.GetConstructorFromName = function (type, name, scene) {
  9163. switch (type) {
  9164. case 0:
  9165. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9166. case 1:
  9167. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9168. case 2:
  9169. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9170. case 3:
  9171. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9172. }
  9173. };
  9174. Light.Parse = function (parsedLight, scene) {
  9175. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9176. // Inclusion / exclusions
  9177. if (parsedLight.excludedMeshesIds) {
  9178. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9179. }
  9180. if (parsedLight.includedOnlyMeshesIds) {
  9181. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9182. }
  9183. // Parent
  9184. if (parsedLight.parentId) {
  9185. light._waitingParentId = parsedLight.parentId;
  9186. }
  9187. // Animations
  9188. if (parsedLight.animations) {
  9189. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9190. var parsedAnimation = parsedLight.animations[animationIndex];
  9191. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9192. }
  9193. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9194. }
  9195. if (parsedLight.autoAnimate) {
  9196. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9197. }
  9198. return light;
  9199. };
  9200. __decorate([
  9201. BABYLON.serializeAsColor3()
  9202. ], Light.prototype, "diffuse", void 0);
  9203. __decorate([
  9204. BABYLON.serializeAsColor3()
  9205. ], Light.prototype, "specular", void 0);
  9206. __decorate([
  9207. BABYLON.serialize()
  9208. ], Light.prototype, "intensity", void 0);
  9209. __decorate([
  9210. BABYLON.serialize()
  9211. ], Light.prototype, "range", void 0);
  9212. __decorate([
  9213. BABYLON.serialize()
  9214. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9215. __decorate([
  9216. BABYLON.serialize()
  9217. ], Light.prototype, "radius", void 0);
  9218. return Light;
  9219. })(BABYLON.Node);
  9220. BABYLON.Light = Light;
  9221. })(BABYLON || (BABYLON = {}));
  9222. var BABYLON;
  9223. (function (BABYLON) {
  9224. var PointLight = (function (_super) {
  9225. __extends(PointLight, _super);
  9226. function PointLight(name, position, scene) {
  9227. _super.call(this, name, scene);
  9228. this.position = position;
  9229. }
  9230. PointLight.prototype.getAbsolutePosition = function () {
  9231. return this.transformedPosition ? this.transformedPosition : this.position;
  9232. };
  9233. PointLight.prototype.computeTransformedPosition = function () {
  9234. if (this.parent && this.parent.getWorldMatrix) {
  9235. if (!this.transformedPosition) {
  9236. this.transformedPosition = BABYLON.Vector3.Zero();
  9237. }
  9238. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9239. return true;
  9240. }
  9241. return false;
  9242. };
  9243. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9244. if (this.parent && this.parent.getWorldMatrix) {
  9245. this.computeTransformedPosition();
  9246. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9247. return;
  9248. }
  9249. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9250. };
  9251. PointLight.prototype.needCube = function () {
  9252. return true;
  9253. };
  9254. PointLight.prototype.supportsVSM = function () {
  9255. return false;
  9256. };
  9257. PointLight.prototype.needRefreshPerFrame = function () {
  9258. return false;
  9259. };
  9260. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9261. switch (faceIndex) {
  9262. case 0:
  9263. return new BABYLON.Vector3(1, 0, 0);
  9264. case 1:
  9265. return new BABYLON.Vector3(-1, 0, 0);
  9266. case 2:
  9267. return new BABYLON.Vector3(0, -1, 0);
  9268. case 3:
  9269. return new BABYLON.Vector3(0, 1, 0);
  9270. case 4:
  9271. return new BABYLON.Vector3(0, 0, 1);
  9272. case 5:
  9273. return new BABYLON.Vector3(0, 0, -1);
  9274. }
  9275. return BABYLON.Vector3.Zero();
  9276. };
  9277. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9278. var activeCamera = this.getScene().activeCamera;
  9279. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9280. };
  9281. PointLight.prototype._getWorldMatrix = function () {
  9282. if (!this._worldMatrix) {
  9283. this._worldMatrix = BABYLON.Matrix.Identity();
  9284. }
  9285. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9286. return this._worldMatrix;
  9287. };
  9288. PointLight.prototype.getTypeID = function () {
  9289. return 0;
  9290. };
  9291. __decorate([
  9292. BABYLON.serializeAsVector3()
  9293. ], PointLight.prototype, "position", void 0);
  9294. return PointLight;
  9295. })(BABYLON.Light);
  9296. BABYLON.PointLight = PointLight;
  9297. })(BABYLON || (BABYLON = {}));
  9298. var BABYLON;
  9299. (function (BABYLON) {
  9300. var SpotLight = (function (_super) {
  9301. __extends(SpotLight, _super);
  9302. function SpotLight(name, position, direction, angle, exponent, scene) {
  9303. _super.call(this, name, scene);
  9304. this.position = position;
  9305. this.direction = direction;
  9306. this.angle = angle;
  9307. this.exponent = exponent;
  9308. }
  9309. SpotLight.prototype.getAbsolutePosition = function () {
  9310. return this.transformedPosition ? this.transformedPosition : this.position;
  9311. };
  9312. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9313. var activeCamera = this.getScene().activeCamera;
  9314. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9315. };
  9316. SpotLight.prototype.needCube = function () {
  9317. return false;
  9318. };
  9319. SpotLight.prototype.supportsVSM = function () {
  9320. return true;
  9321. };
  9322. SpotLight.prototype.needRefreshPerFrame = function () {
  9323. return false;
  9324. };
  9325. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9326. return this.direction;
  9327. };
  9328. SpotLight.prototype.setDirectionToTarget = function (target) {
  9329. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9330. return this.direction;
  9331. };
  9332. SpotLight.prototype.computeTransformedPosition = function () {
  9333. if (this.parent && this.parent.getWorldMatrix) {
  9334. if (!this.transformedPosition) {
  9335. this.transformedPosition = BABYLON.Vector3.Zero();
  9336. }
  9337. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9338. return true;
  9339. }
  9340. return false;
  9341. };
  9342. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9343. var normalizeDirection;
  9344. if (this.parent && this.parent.getWorldMatrix) {
  9345. if (!this._transformedDirection) {
  9346. this._transformedDirection = BABYLON.Vector3.Zero();
  9347. }
  9348. this.computeTransformedPosition();
  9349. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9350. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9351. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9352. }
  9353. else {
  9354. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9355. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9356. }
  9357. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9358. };
  9359. SpotLight.prototype._getWorldMatrix = function () {
  9360. if (!this._worldMatrix) {
  9361. this._worldMatrix = BABYLON.Matrix.Identity();
  9362. }
  9363. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9364. return this._worldMatrix;
  9365. };
  9366. SpotLight.prototype.getTypeID = function () {
  9367. return 2;
  9368. };
  9369. __decorate([
  9370. BABYLON.serializeAsVector3()
  9371. ], SpotLight.prototype, "position", void 0);
  9372. __decorate([
  9373. BABYLON.serializeAsVector3()
  9374. ], SpotLight.prototype, "direction", void 0);
  9375. __decorate([
  9376. BABYLON.serialize()
  9377. ], SpotLight.prototype, "angle", void 0);
  9378. __decorate([
  9379. BABYLON.serialize()
  9380. ], SpotLight.prototype, "exponent", void 0);
  9381. return SpotLight;
  9382. })(BABYLON.Light);
  9383. BABYLON.SpotLight = SpotLight;
  9384. })(BABYLON || (BABYLON = {}));
  9385. var BABYLON;
  9386. (function (BABYLON) {
  9387. var HemisphericLight = (function (_super) {
  9388. __extends(HemisphericLight, _super);
  9389. function HemisphericLight(name, direction, scene) {
  9390. _super.call(this, name, scene);
  9391. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9392. this.direction = direction;
  9393. }
  9394. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9395. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9396. return this.direction;
  9397. };
  9398. HemisphericLight.prototype.getShadowGenerator = function () {
  9399. return null;
  9400. };
  9401. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9402. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9403. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9404. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9405. };
  9406. HemisphericLight.prototype._getWorldMatrix = function () {
  9407. if (!this._worldMatrix) {
  9408. this._worldMatrix = BABYLON.Matrix.Identity();
  9409. }
  9410. return this._worldMatrix;
  9411. };
  9412. HemisphericLight.prototype.getTypeID = function () {
  9413. return 3;
  9414. };
  9415. __decorate([
  9416. BABYLON.serializeAsColor3()
  9417. ], HemisphericLight.prototype, "groundColor", void 0);
  9418. __decorate([
  9419. BABYLON.serializeAsVector3()
  9420. ], HemisphericLight.prototype, "direction", void 0);
  9421. return HemisphericLight;
  9422. })(BABYLON.Light);
  9423. BABYLON.HemisphericLight = HemisphericLight;
  9424. })(BABYLON || (BABYLON = {}));
  9425. var BABYLON;
  9426. (function (BABYLON) {
  9427. var DirectionalLight = (function (_super) {
  9428. __extends(DirectionalLight, _super);
  9429. function DirectionalLight(name, direction, scene) {
  9430. _super.call(this, name, scene);
  9431. this.shadowOrthoScale = 0.5;
  9432. this.autoUpdateExtends = true;
  9433. // Cache
  9434. this._orthoLeft = Number.MAX_VALUE;
  9435. this._orthoRight = Number.MIN_VALUE;
  9436. this._orthoTop = Number.MIN_VALUE;
  9437. this._orthoBottom = Number.MAX_VALUE;
  9438. this.position = direction.scale(-1);
  9439. this.direction = direction;
  9440. }
  9441. DirectionalLight.prototype.getAbsolutePosition = function () {
  9442. return this.transformedPosition ? this.transformedPosition : this.position;
  9443. };
  9444. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9445. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9446. return this.direction;
  9447. };
  9448. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9449. var activeCamera = this.getScene().activeCamera;
  9450. // Check extends
  9451. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9452. var tempVector3 = BABYLON.Vector3.Zero();
  9453. this._orthoLeft = Number.MAX_VALUE;
  9454. this._orthoRight = Number.MIN_VALUE;
  9455. this._orthoTop = Number.MIN_VALUE;
  9456. this._orthoBottom = Number.MAX_VALUE;
  9457. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9458. var mesh = renderList[meshIndex];
  9459. if (!mesh) {
  9460. continue;
  9461. }
  9462. var boundingInfo = mesh.getBoundingInfo();
  9463. if (!boundingInfo) {
  9464. continue;
  9465. }
  9466. var boundingBox = boundingInfo.boundingBox;
  9467. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9468. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9469. if (tempVector3.x < this._orthoLeft)
  9470. this._orthoLeft = tempVector3.x;
  9471. if (tempVector3.y < this._orthoBottom)
  9472. this._orthoBottom = tempVector3.y;
  9473. if (tempVector3.x > this._orthoRight)
  9474. this._orthoRight = tempVector3.x;
  9475. if (tempVector3.y > this._orthoTop)
  9476. this._orthoTop = tempVector3.y;
  9477. }
  9478. }
  9479. }
  9480. var xOffset = this._orthoRight - this._orthoLeft;
  9481. var yOffset = this._orthoTop - this._orthoBottom;
  9482. 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);
  9483. };
  9484. DirectionalLight.prototype.supportsVSM = function () {
  9485. return true;
  9486. };
  9487. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9488. return true;
  9489. };
  9490. DirectionalLight.prototype.needCube = function () {
  9491. return false;
  9492. };
  9493. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9494. return this.direction;
  9495. };
  9496. DirectionalLight.prototype.computeTransformedPosition = function () {
  9497. if (this.parent && this.parent.getWorldMatrix) {
  9498. if (!this.transformedPosition) {
  9499. this.transformedPosition = BABYLON.Vector3.Zero();
  9500. }
  9501. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9502. return true;
  9503. }
  9504. return false;
  9505. };
  9506. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9507. if (this.parent && this.parent.getWorldMatrix) {
  9508. if (!this._transformedDirection) {
  9509. this._transformedDirection = BABYLON.Vector3.Zero();
  9510. }
  9511. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9512. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9513. return;
  9514. }
  9515. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9516. };
  9517. DirectionalLight.prototype._getWorldMatrix = function () {
  9518. if (!this._worldMatrix) {
  9519. this._worldMatrix = BABYLON.Matrix.Identity();
  9520. }
  9521. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9522. return this._worldMatrix;
  9523. };
  9524. DirectionalLight.prototype.getTypeID = function () {
  9525. return 1;
  9526. };
  9527. __decorate([
  9528. BABYLON.serializeAsVector3()
  9529. ], DirectionalLight.prototype, "position", void 0);
  9530. __decorate([
  9531. BABYLON.serializeAsVector3()
  9532. ], DirectionalLight.prototype, "direction", void 0);
  9533. __decorate([
  9534. BABYLON.serialize()
  9535. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9536. __decorate([
  9537. BABYLON.serialize()
  9538. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9539. return DirectionalLight;
  9540. })(BABYLON.Light);
  9541. BABYLON.DirectionalLight = DirectionalLight;
  9542. })(BABYLON || (BABYLON = {}));
  9543. var BABYLON;
  9544. (function (BABYLON) {
  9545. var ShadowGenerator = (function () {
  9546. function ShadowGenerator(mapSize, light) {
  9547. var _this = this;
  9548. // Members
  9549. this._filter = ShadowGenerator.FILTER_NONE;
  9550. this.blurScale = 2;
  9551. this._blurBoxOffset = 0;
  9552. this._bias = 0.00005;
  9553. this._lightDirection = BABYLON.Vector3.Zero();
  9554. this.forceBackFacesOnly = false;
  9555. this._darkness = 0;
  9556. this._transparencyShadow = false;
  9557. this._viewMatrix = BABYLON.Matrix.Zero();
  9558. this._projectionMatrix = BABYLON.Matrix.Zero();
  9559. this._transformMatrix = BABYLON.Matrix.Zero();
  9560. this._worldViewProjection = BABYLON.Matrix.Zero();
  9561. this._currentFaceIndex = 0;
  9562. this._currentFaceIndexCache = 0;
  9563. this._light = light;
  9564. this._scene = light.getScene();
  9565. this._mapSize = mapSize;
  9566. light._shadowGenerator = this;
  9567. // Render target
  9568. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9569. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9570. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9571. this._shadowMap.anisotropicFilteringLevel = 1;
  9572. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9573. this._shadowMap.renderParticles = false;
  9574. this._shadowMap.onBeforeRender = function (faceIndex) {
  9575. _this._currentFaceIndex = faceIndex;
  9576. };
  9577. this._shadowMap.onAfterUnbind = function () {
  9578. if (!_this.useBlurVarianceShadowMap) {
  9579. return;
  9580. }
  9581. if (!_this._shadowMap2) {
  9582. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9583. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9584. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9585. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9586. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9587. _this._downSamplePostprocess.onApply = function (effect) {
  9588. effect.setTexture("textureSampler", _this._shadowMap);
  9589. };
  9590. _this.blurBoxOffset = 1;
  9591. }
  9592. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9593. };
  9594. // Custom render function
  9595. var renderSubMesh = function (subMesh) {
  9596. var mesh = subMesh.getRenderingMesh();
  9597. var scene = _this._scene;
  9598. var engine = scene.getEngine();
  9599. // Culling
  9600. engine.setState(subMesh.getMaterial().backFaceCulling);
  9601. // Managing instances
  9602. var batch = mesh._getInstancesRenderList(subMesh._id);
  9603. if (batch.mustReturn) {
  9604. return;
  9605. }
  9606. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9607. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9608. engine.enableEffect(_this._effect);
  9609. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9610. var material = subMesh.getMaterial();
  9611. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9612. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9613. if (_this.getLight().needCube()) {
  9614. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9615. }
  9616. // Alpha test
  9617. if (material && material.needAlphaTesting()) {
  9618. var alphaTexture = material.getAlphaTestTexture();
  9619. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9620. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9621. }
  9622. // Bones
  9623. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9624. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9625. }
  9626. if (_this.forceBackFacesOnly) {
  9627. engine.setState(true, 0, false, true);
  9628. }
  9629. // Draw
  9630. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9631. if (_this.forceBackFacesOnly) {
  9632. engine.setState(true, 0, false, false);
  9633. }
  9634. }
  9635. else {
  9636. // Need to reset refresh rate of the shadowMap
  9637. _this._shadowMap.resetRefreshCounter();
  9638. }
  9639. };
  9640. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9641. var index;
  9642. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9643. renderSubMesh(opaqueSubMeshes.data[index]);
  9644. }
  9645. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9646. renderSubMesh(alphaTestSubMeshes.data[index]);
  9647. }
  9648. if (_this._transparencyShadow) {
  9649. for (index = 0; index < transparentSubMeshes.length; index++) {
  9650. renderSubMesh(transparentSubMeshes.data[index]);
  9651. }
  9652. }
  9653. };
  9654. this._shadowMap.onClear = function (engine) {
  9655. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9656. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9657. }
  9658. else {
  9659. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9660. }
  9661. };
  9662. }
  9663. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9664. // Static
  9665. get: function () {
  9666. return ShadowGenerator._FILTER_NONE;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9672. get: function () {
  9673. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9679. get: function () {
  9680. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9686. get: function () {
  9687. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9693. get: function () {
  9694. return this._bias;
  9695. },
  9696. set: function (bias) {
  9697. this._bias = bias;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9703. get: function () {
  9704. return this._blurBoxOffset;
  9705. },
  9706. set: function (value) {
  9707. var _this = this;
  9708. if (this._blurBoxOffset === value) {
  9709. return;
  9710. }
  9711. this._blurBoxOffset = value;
  9712. if (this._boxBlurPostprocess) {
  9713. this._boxBlurPostprocess.dispose();
  9714. }
  9715. 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);
  9716. this._boxBlurPostprocess.onApply = function (effect) {
  9717. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9718. };
  9719. },
  9720. enumerable: true,
  9721. configurable: true
  9722. });
  9723. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9724. get: function () {
  9725. return this._filter;
  9726. },
  9727. set: function (value) {
  9728. if (this._filter === value) {
  9729. return;
  9730. }
  9731. this._filter = value;
  9732. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9733. this._shadowMap.anisotropicFilteringLevel = 16;
  9734. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9735. }
  9736. else {
  9737. this._shadowMap.anisotropicFilteringLevel = 1;
  9738. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9739. }
  9740. },
  9741. enumerable: true,
  9742. configurable: true
  9743. });
  9744. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9745. get: function () {
  9746. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9747. },
  9748. set: function (value) {
  9749. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9750. },
  9751. enumerable: true,
  9752. configurable: true
  9753. });
  9754. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9755. get: function () {
  9756. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9757. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9758. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9759. },
  9760. set: function (value) {
  9761. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9762. },
  9763. enumerable: true,
  9764. configurable: true
  9765. });
  9766. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9767. get: function () {
  9768. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9769. },
  9770. set: function (value) {
  9771. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9777. var defines = [];
  9778. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9779. defines.push("#define VSM");
  9780. }
  9781. if (this.getLight().needCube()) {
  9782. defines.push("#define CUBEMAP");
  9783. }
  9784. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9785. var mesh = subMesh.getMesh();
  9786. var material = subMesh.getMaterial();
  9787. // Alpha test
  9788. if (material && material.needAlphaTesting()) {
  9789. defines.push("#define ALPHATEST");
  9790. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9791. attribs.push(BABYLON.VertexBuffer.UVKind);
  9792. defines.push("#define UV1");
  9793. }
  9794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9795. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9796. defines.push("#define UV2");
  9797. }
  9798. }
  9799. // Bones
  9800. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9801. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9802. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9803. if (mesh.numBoneInfluencers > 4) {
  9804. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9805. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9806. }
  9807. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9808. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9809. }
  9810. else {
  9811. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9812. }
  9813. // Instances
  9814. if (useInstances) {
  9815. defines.push("#define INSTANCES");
  9816. attribs.push("world0");
  9817. attribs.push("world1");
  9818. attribs.push("world2");
  9819. attribs.push("world3");
  9820. }
  9821. // Get correct effect
  9822. var join = defines.join("\n");
  9823. if (this._cachedDefines !== join) {
  9824. this._cachedDefines = join;
  9825. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9826. }
  9827. return this._effect.isReady();
  9828. };
  9829. ShadowGenerator.prototype.getShadowMap = function () {
  9830. return this._shadowMap;
  9831. };
  9832. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9833. if (this._shadowMap2) {
  9834. return this._shadowMap2;
  9835. }
  9836. return this._shadowMap;
  9837. };
  9838. ShadowGenerator.prototype.getLight = function () {
  9839. return this._light;
  9840. };
  9841. // Methods
  9842. ShadowGenerator.prototype.getTransformMatrix = function () {
  9843. var scene = this._scene;
  9844. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9845. return this._transformMatrix;
  9846. }
  9847. this._currentRenderID = scene.getRenderId();
  9848. this._currentFaceIndexCache = this._currentFaceIndex;
  9849. var lightPosition = this._light.position;
  9850. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9851. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9852. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9853. }
  9854. if (this._light.computeTransformedPosition()) {
  9855. lightPosition = this._light.transformedPosition;
  9856. }
  9857. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9858. this._cachedPosition = lightPosition.clone();
  9859. this._cachedDirection = this._lightDirection.clone();
  9860. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9861. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9862. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9863. }
  9864. return this._transformMatrix;
  9865. };
  9866. ShadowGenerator.prototype.getDarkness = function () {
  9867. return this._darkness;
  9868. };
  9869. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9870. if (darkness >= 1.0)
  9871. this._darkness = 1.0;
  9872. else if (darkness <= 0.0)
  9873. this._darkness = 0.0;
  9874. else
  9875. this._darkness = darkness;
  9876. };
  9877. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9878. this._transparencyShadow = hasShadow;
  9879. };
  9880. ShadowGenerator.prototype._packHalf = function (depth) {
  9881. var scale = depth * 255.0;
  9882. var fract = scale - Math.floor(scale);
  9883. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9884. };
  9885. ShadowGenerator.prototype.dispose = function () {
  9886. this._shadowMap.dispose();
  9887. if (this._shadowMap2) {
  9888. this._shadowMap2.dispose();
  9889. }
  9890. if (this._downSamplePostprocess) {
  9891. this._downSamplePostprocess.dispose();
  9892. }
  9893. if (this._boxBlurPostprocess) {
  9894. this._boxBlurPostprocess.dispose();
  9895. }
  9896. };
  9897. ShadowGenerator.prototype.serialize = function () {
  9898. var serializationObject = {};
  9899. serializationObject.lightId = this._light.id;
  9900. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9901. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9902. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9903. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9904. serializationObject.renderList = [];
  9905. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9906. var mesh = this.getShadowMap().renderList[meshIndex];
  9907. serializationObject.renderList.push(mesh.id);
  9908. }
  9909. return serializationObject;
  9910. };
  9911. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9912. //casting to point light, as light is missing the position attr and typescript complains.
  9913. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9914. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9915. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9916. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9917. shadowGenerator.getShadowMap().renderList.push(mesh);
  9918. }
  9919. if (parsedShadowGenerator.usePoissonSampling) {
  9920. shadowGenerator.usePoissonSampling = true;
  9921. }
  9922. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9923. shadowGenerator.useVarianceShadowMap = true;
  9924. }
  9925. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9926. shadowGenerator.useBlurVarianceShadowMap = true;
  9927. if (parsedShadowGenerator.blurScale) {
  9928. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9929. }
  9930. if (parsedShadowGenerator.blurBoxOffset) {
  9931. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9932. }
  9933. }
  9934. if (parsedShadowGenerator.bias !== undefined) {
  9935. shadowGenerator.bias = parsedShadowGenerator.bias;
  9936. }
  9937. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9938. return shadowGenerator;
  9939. };
  9940. ShadowGenerator._FILTER_NONE = 0;
  9941. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9942. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9943. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9944. return ShadowGenerator;
  9945. })();
  9946. BABYLON.ShadowGenerator = ShadowGenerator;
  9947. })(BABYLON || (BABYLON = {}));
  9948. var BABYLON;
  9949. (function (BABYLON) {
  9950. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9951. if (boxMin.x > sphereCenter.x + sphereRadius)
  9952. return false;
  9953. if (sphereCenter.x - sphereRadius > boxMax.x)
  9954. return false;
  9955. if (boxMin.y > sphereCenter.y + sphereRadius)
  9956. return false;
  9957. if (sphereCenter.y - sphereRadius > boxMax.y)
  9958. return false;
  9959. if (boxMin.z > sphereCenter.z + sphereRadius)
  9960. return false;
  9961. if (sphereCenter.z - sphereRadius > boxMax.z)
  9962. return false;
  9963. return true;
  9964. };
  9965. var getLowestRoot = function (a, b, c, maxR) {
  9966. var determinant = b * b - 4.0 * a * c;
  9967. var result = { root: 0, found: false };
  9968. if (determinant < 0)
  9969. return result;
  9970. var sqrtD = Math.sqrt(determinant);
  9971. var r1 = (-b - sqrtD) / (2.0 * a);
  9972. var r2 = (-b + sqrtD) / (2.0 * a);
  9973. if (r1 > r2) {
  9974. var temp = r2;
  9975. r2 = r1;
  9976. r1 = temp;
  9977. }
  9978. if (r1 > 0 && r1 < maxR) {
  9979. result.root = r1;
  9980. result.found = true;
  9981. return result;
  9982. }
  9983. if (r2 > 0 && r2 < maxR) {
  9984. result.root = r2;
  9985. result.found = true;
  9986. return result;
  9987. }
  9988. return result;
  9989. };
  9990. var Collider = (function () {
  9991. function Collider() {
  9992. this.radius = new BABYLON.Vector3(1, 1, 1);
  9993. this.retry = 0;
  9994. this.basePointWorld = BABYLON.Vector3.Zero();
  9995. this.velocityWorld = BABYLON.Vector3.Zero();
  9996. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9997. this._collisionPoint = BABYLON.Vector3.Zero();
  9998. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9999. this._tempVector = BABYLON.Vector3.Zero();
  10000. this._tempVector2 = BABYLON.Vector3.Zero();
  10001. this._tempVector3 = BABYLON.Vector3.Zero();
  10002. this._tempVector4 = BABYLON.Vector3.Zero();
  10003. this._edge = BABYLON.Vector3.Zero();
  10004. this._baseToVertex = BABYLON.Vector3.Zero();
  10005. this._destinationPoint = BABYLON.Vector3.Zero();
  10006. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10007. this._displacementVector = BABYLON.Vector3.Zero();
  10008. }
  10009. // Methods
  10010. Collider.prototype._initialize = function (source, dir, e) {
  10011. this.velocity = dir;
  10012. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10013. this.basePoint = source;
  10014. source.multiplyToRef(this.radius, this.basePointWorld);
  10015. dir.multiplyToRef(this.radius, this.velocityWorld);
  10016. this.velocityWorldLength = this.velocityWorld.length();
  10017. this.epsilon = e;
  10018. this.collisionFound = false;
  10019. };
  10020. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10021. pa.subtractToRef(point, this._tempVector);
  10022. pb.subtractToRef(point, this._tempVector2);
  10023. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10024. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10025. if (d < 0)
  10026. return false;
  10027. pc.subtractToRef(point, this._tempVector3);
  10028. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10029. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10030. if (d < 0)
  10031. return false;
  10032. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10033. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10034. return d >= 0;
  10035. };
  10036. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10037. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10038. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10039. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10040. return false;
  10041. }
  10042. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10043. return false;
  10044. return true;
  10045. };
  10046. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10047. var t0;
  10048. var embeddedInPlane = false;
  10049. //defensive programming, actually not needed.
  10050. if (!trianglePlaneArray) {
  10051. trianglePlaneArray = [];
  10052. }
  10053. if (!trianglePlaneArray[faceIndex]) {
  10054. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10055. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10056. }
  10057. var trianglePlane = trianglePlaneArray[faceIndex];
  10058. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10059. return;
  10060. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10061. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10062. if (normalDotVelocity == 0) {
  10063. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10064. return;
  10065. embeddedInPlane = true;
  10066. t0 = 0;
  10067. }
  10068. else {
  10069. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10070. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10071. if (t0 > t1) {
  10072. var temp = t1;
  10073. t1 = t0;
  10074. t0 = temp;
  10075. }
  10076. if (t0 > 1.0 || t1 < 0.0)
  10077. return;
  10078. if (t0 < 0)
  10079. t0 = 0;
  10080. if (t0 > 1.0)
  10081. t0 = 1.0;
  10082. }
  10083. this._collisionPoint.copyFromFloats(0, 0, 0);
  10084. var found = false;
  10085. var t = 1.0;
  10086. if (!embeddedInPlane) {
  10087. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10088. this.velocity.scaleToRef(t0, this._tempVector);
  10089. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10090. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10091. found = true;
  10092. t = t0;
  10093. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10094. }
  10095. }
  10096. if (!found) {
  10097. var velocitySquaredLength = this.velocity.lengthSquared();
  10098. var a = velocitySquaredLength;
  10099. this.basePoint.subtractToRef(p1, this._tempVector);
  10100. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10101. var c = this._tempVector.lengthSquared() - 1.0;
  10102. var lowestRoot = getLowestRoot(a, b, c, t);
  10103. if (lowestRoot.found) {
  10104. t = lowestRoot.root;
  10105. found = true;
  10106. this._collisionPoint.copyFrom(p1);
  10107. }
  10108. this.basePoint.subtractToRef(p2, this._tempVector);
  10109. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10110. c = this._tempVector.lengthSquared() - 1.0;
  10111. lowestRoot = getLowestRoot(a, b, c, t);
  10112. if (lowestRoot.found) {
  10113. t = lowestRoot.root;
  10114. found = true;
  10115. this._collisionPoint.copyFrom(p2);
  10116. }
  10117. this.basePoint.subtractToRef(p3, this._tempVector);
  10118. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10119. c = this._tempVector.lengthSquared() - 1.0;
  10120. lowestRoot = getLowestRoot(a, b, c, t);
  10121. if (lowestRoot.found) {
  10122. t = lowestRoot.root;
  10123. found = true;
  10124. this._collisionPoint.copyFrom(p3);
  10125. }
  10126. p2.subtractToRef(p1, this._edge);
  10127. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10128. var edgeSquaredLength = this._edge.lengthSquared();
  10129. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10130. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10131. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10132. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10133. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10134. lowestRoot = getLowestRoot(a, b, c, t);
  10135. if (lowestRoot.found) {
  10136. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10137. if (f >= 0.0 && f <= 1.0) {
  10138. t = lowestRoot.root;
  10139. found = true;
  10140. this._edge.scaleInPlace(f);
  10141. p1.addToRef(this._edge, this._collisionPoint);
  10142. }
  10143. }
  10144. p3.subtractToRef(p2, this._edge);
  10145. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10146. edgeSquaredLength = this._edge.lengthSquared();
  10147. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10148. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10149. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10150. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10151. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10152. lowestRoot = getLowestRoot(a, b, c, t);
  10153. if (lowestRoot.found) {
  10154. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10155. if (f >= 0.0 && f <= 1.0) {
  10156. t = lowestRoot.root;
  10157. found = true;
  10158. this._edge.scaleInPlace(f);
  10159. p2.addToRef(this._edge, this._collisionPoint);
  10160. }
  10161. }
  10162. p1.subtractToRef(p3, this._edge);
  10163. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10164. edgeSquaredLength = this._edge.lengthSquared();
  10165. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10166. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10167. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10168. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10169. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10170. lowestRoot = getLowestRoot(a, b, c, t);
  10171. if (lowestRoot.found) {
  10172. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10173. if (f >= 0.0 && f <= 1.0) {
  10174. t = lowestRoot.root;
  10175. found = true;
  10176. this._edge.scaleInPlace(f);
  10177. p3.addToRef(this._edge, this._collisionPoint);
  10178. }
  10179. }
  10180. }
  10181. if (found) {
  10182. var distToCollision = t * this.velocity.length();
  10183. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10184. if (!this.intersectionPoint) {
  10185. this.intersectionPoint = this._collisionPoint.clone();
  10186. }
  10187. else {
  10188. this.intersectionPoint.copyFrom(this._collisionPoint);
  10189. }
  10190. this.nearestDistance = distToCollision;
  10191. this.collisionFound = true;
  10192. }
  10193. }
  10194. };
  10195. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10196. for (var i = indexStart; i < indexEnd; i += 3) {
  10197. var p1 = pts[indices[i] - decal];
  10198. var p2 = pts[indices[i + 1] - decal];
  10199. var p3 = pts[indices[i + 2] - decal];
  10200. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10201. }
  10202. };
  10203. Collider.prototype._getResponse = function (pos, vel) {
  10204. pos.addToRef(vel, this._destinationPoint);
  10205. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10206. this.basePoint.addToRef(vel, pos);
  10207. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10208. this._slidePlaneNormal.normalize();
  10209. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10210. pos.addInPlace(this._displacementVector);
  10211. this.intersectionPoint.addInPlace(this._displacementVector);
  10212. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10213. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10214. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10215. };
  10216. return Collider;
  10217. })();
  10218. BABYLON.Collider = Collider;
  10219. })(BABYLON || (BABYLON = {}));
  10220. var BABYLON;
  10221. (function (BABYLON) {
  10222. //WebWorker code will be inserted to this variable.
  10223. BABYLON.CollisionWorker = "";
  10224. (function (WorkerTaskType) {
  10225. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10226. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10227. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10228. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10229. var WorkerTaskType = BABYLON.WorkerTaskType;
  10230. (function (WorkerReplyType) {
  10231. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10232. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10233. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10234. var WorkerReplyType = BABYLON.WorkerReplyType;
  10235. var CollisionCoordinatorWorker = (function () {
  10236. function CollisionCoordinatorWorker() {
  10237. var _this = this;
  10238. this._scaledPosition = BABYLON.Vector3.Zero();
  10239. this._scaledVelocity = BABYLON.Vector3.Zero();
  10240. this.onMeshUpdated = function (mesh) {
  10241. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10242. };
  10243. this.onGeometryUpdated = function (geometry) {
  10244. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10245. };
  10246. this._afterRender = function () {
  10247. if (!_this._init)
  10248. return;
  10249. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10250. return;
  10251. }
  10252. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10253. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10254. if (_this._runningUpdated > 4) {
  10255. return;
  10256. }
  10257. ++_this._runningUpdated;
  10258. var payload = {
  10259. updatedMeshes: _this._addUpdateMeshesList,
  10260. updatedGeometries: _this._addUpdateGeometriesList,
  10261. removedGeometries: _this._toRemoveGeometryArray,
  10262. removedMeshes: _this._toRemoveMeshesArray
  10263. };
  10264. var message = {
  10265. payload: payload,
  10266. taskType: WorkerTaskType.UPDATE
  10267. };
  10268. var serializable = [];
  10269. for (var id in payload.updatedGeometries) {
  10270. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10271. //prepare transferables
  10272. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10273. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10274. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10275. }
  10276. }
  10277. _this._worker.postMessage(message, serializable);
  10278. _this._addUpdateMeshesList = {};
  10279. _this._addUpdateGeometriesList = {};
  10280. _this._toRemoveGeometryArray = [];
  10281. _this._toRemoveMeshesArray = [];
  10282. };
  10283. this._onMessageFromWorker = function (e) {
  10284. var returnData = e.data;
  10285. if (returnData.error != WorkerReplyType.SUCCESS) {
  10286. //TODO what errors can be returned from the worker?
  10287. BABYLON.Tools.Warn("error returned from worker!");
  10288. return;
  10289. }
  10290. switch (returnData.taskType) {
  10291. case WorkerTaskType.INIT:
  10292. _this._init = true;
  10293. //Update the worked with ALL of the scene's current state
  10294. _this._scene.meshes.forEach(function (mesh) {
  10295. _this.onMeshAdded(mesh);
  10296. });
  10297. _this._scene.getGeometries().forEach(function (geometry) {
  10298. _this.onGeometryAdded(geometry);
  10299. });
  10300. break;
  10301. case WorkerTaskType.UPDATE:
  10302. _this._runningUpdated--;
  10303. break;
  10304. case WorkerTaskType.COLLIDE:
  10305. _this._runningCollisionTask = false;
  10306. var returnPayload = returnData.payload;
  10307. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10308. return;
  10309. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10310. //cleanup
  10311. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10312. break;
  10313. }
  10314. };
  10315. this._collisionsCallbackArray = [];
  10316. this._init = false;
  10317. this._runningUpdated = 0;
  10318. this._runningCollisionTask = false;
  10319. this._addUpdateMeshesList = {};
  10320. this._addUpdateGeometriesList = {};
  10321. this._toRemoveGeometryArray = [];
  10322. this._toRemoveMeshesArray = [];
  10323. }
  10324. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10325. if (!this._init)
  10326. return;
  10327. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10328. return;
  10329. position.divideToRef(collider.radius, this._scaledPosition);
  10330. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10331. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10332. var payload = {
  10333. collider: {
  10334. position: this._scaledPosition.asArray(),
  10335. velocity: this._scaledVelocity.asArray(),
  10336. radius: collider.radius.asArray()
  10337. },
  10338. collisionId: collisionIndex,
  10339. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10340. maximumRetry: maximumRetry
  10341. };
  10342. var message = {
  10343. payload: payload,
  10344. taskType: WorkerTaskType.COLLIDE
  10345. };
  10346. this._worker.postMessage(message);
  10347. };
  10348. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10349. this._scene = scene;
  10350. this._scene.registerAfterRender(this._afterRender);
  10351. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10352. this._worker = new Worker(workerUrl);
  10353. this._worker.onmessage = this._onMessageFromWorker;
  10354. var message = {
  10355. payload: {},
  10356. taskType: WorkerTaskType.INIT
  10357. };
  10358. this._worker.postMessage(message);
  10359. };
  10360. CollisionCoordinatorWorker.prototype.destroy = function () {
  10361. this._scene.unregisterAfterRender(this._afterRender);
  10362. this._worker.terminate();
  10363. };
  10364. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10365. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10366. this.onMeshUpdated(mesh);
  10367. };
  10368. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10369. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10370. };
  10371. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10372. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10373. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10374. this.onGeometryUpdated(geometry);
  10375. };
  10376. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10377. this._toRemoveGeometryArray.push(geometry.id);
  10378. };
  10379. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10380. var submeshes = [];
  10381. if (mesh.subMeshes) {
  10382. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10383. return {
  10384. position: idx,
  10385. verticesStart: sm.verticesStart,
  10386. verticesCount: sm.verticesCount,
  10387. indexStart: sm.indexStart,
  10388. indexCount: sm.indexCount,
  10389. hasMaterial: !!sm.getMaterial(),
  10390. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10391. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10392. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10393. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10394. };
  10395. });
  10396. }
  10397. var geometryId = null;
  10398. if (mesh instanceof BABYLON.Mesh) {
  10399. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10400. }
  10401. else if (mesh instanceof BABYLON.InstancedMesh) {
  10402. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10403. }
  10404. return {
  10405. uniqueId: mesh.uniqueId,
  10406. id: mesh.id,
  10407. name: mesh.name,
  10408. geometryId: geometryId,
  10409. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10410. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10411. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10412. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10413. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10414. subMeshes: submeshes,
  10415. checkCollisions: mesh.checkCollisions
  10416. };
  10417. };
  10418. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10419. return {
  10420. id: geometry.id,
  10421. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10422. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10423. indices: new Int32Array(geometry.getIndices() || []),
  10424. };
  10425. };
  10426. return CollisionCoordinatorWorker;
  10427. })();
  10428. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10429. var CollisionCoordinatorLegacy = (function () {
  10430. function CollisionCoordinatorLegacy() {
  10431. this._scaledPosition = BABYLON.Vector3.Zero();
  10432. this._scaledVelocity = BABYLON.Vector3.Zero();
  10433. this._finalPosition = BABYLON.Vector3.Zero();
  10434. }
  10435. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10436. position.divideToRef(collider.radius, this._scaledPosition);
  10437. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10438. collider.collidedMesh = null;
  10439. collider.retry = 0;
  10440. collider.initialVelocity = this._scaledVelocity;
  10441. collider.initialPosition = this._scaledPosition;
  10442. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10443. this._finalPosition.multiplyInPlace(collider.radius);
  10444. //run the callback
  10445. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10446. };
  10447. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10448. this._scene = scene;
  10449. };
  10450. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10451. //Legacy need no destruction method.
  10452. };
  10453. //No update in legacy mode
  10454. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10455. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10456. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10457. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10458. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10459. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10460. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10461. if (excludedMesh === void 0) { excludedMesh = null; }
  10462. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10463. if (collider.retry >= maximumRetry) {
  10464. finalPosition.copyFrom(position);
  10465. return;
  10466. }
  10467. collider._initialize(position, velocity, closeDistance);
  10468. // Check all meshes
  10469. for (var index = 0; index < this._scene.meshes.length; index++) {
  10470. var mesh = this._scene.meshes[index];
  10471. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10472. mesh._checkCollision(collider);
  10473. }
  10474. }
  10475. if (!collider.collisionFound) {
  10476. position.addToRef(velocity, finalPosition);
  10477. return;
  10478. }
  10479. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10480. collider._getResponse(position, velocity);
  10481. }
  10482. if (velocity.length() <= closeDistance) {
  10483. finalPosition.copyFrom(position);
  10484. return;
  10485. }
  10486. collider.retry++;
  10487. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10488. };
  10489. return CollisionCoordinatorLegacy;
  10490. })();
  10491. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10492. })(BABYLON || (BABYLON = {}));
  10493. var BABYLON;
  10494. (function (BABYLON) {
  10495. var Camera = (function (_super) {
  10496. __extends(Camera, _super);
  10497. function Camera(name, position, scene) {
  10498. _super.call(this, name, scene);
  10499. this.upVector = BABYLON.Vector3.Up();
  10500. this.orthoLeft = null;
  10501. this.orthoRight = null;
  10502. this.orthoBottom = null;
  10503. this.orthoTop = null;
  10504. this.fov = 0.8;
  10505. this.minZ = 1.0;
  10506. this.maxZ = 10000.0;
  10507. this.inertia = 0.9;
  10508. this.mode = Camera.PERSPECTIVE_CAMERA;
  10509. this.isIntermediate = false;
  10510. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10511. this.layerMask = 0x0FFFFFFF;
  10512. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10513. // Camera rig members
  10514. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10515. this._rigCameras = new Array();
  10516. // Cache
  10517. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10518. this._projectionMatrix = new BABYLON.Matrix();
  10519. this._postProcesses = new Array();
  10520. this._postProcessesTakenIndices = [];
  10521. this._activeMeshes = new BABYLON.SmartArray(256);
  10522. this._globalPosition = BABYLON.Vector3.Zero();
  10523. scene.addCamera(this);
  10524. if (!scene.activeCamera) {
  10525. scene.activeCamera = this;
  10526. }
  10527. this.position = position;
  10528. }
  10529. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10530. get: function () {
  10531. return Camera._PERSPECTIVE_CAMERA;
  10532. },
  10533. enumerable: true,
  10534. configurable: true
  10535. });
  10536. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10537. get: function () {
  10538. return Camera._ORTHOGRAPHIC_CAMERA;
  10539. },
  10540. enumerable: true,
  10541. configurable: true
  10542. });
  10543. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10544. get: function () {
  10545. return Camera._FOVMODE_VERTICAL_FIXED;
  10546. },
  10547. enumerable: true,
  10548. configurable: true
  10549. });
  10550. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10551. get: function () {
  10552. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10553. },
  10554. enumerable: true,
  10555. configurable: true
  10556. });
  10557. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10558. get: function () {
  10559. return Camera._RIG_MODE_NONE;
  10560. },
  10561. enumerable: true,
  10562. configurable: true
  10563. });
  10564. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10565. get: function () {
  10566. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10567. },
  10568. enumerable: true,
  10569. configurable: true
  10570. });
  10571. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10572. get: function () {
  10573. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10574. },
  10575. enumerable: true,
  10576. configurable: true
  10577. });
  10578. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10579. get: function () {
  10580. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10581. },
  10582. enumerable: true,
  10583. configurable: true
  10584. });
  10585. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10586. get: function () {
  10587. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10593. get: function () {
  10594. return Camera._RIG_MODE_VR;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. /**
  10600. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10601. */
  10602. Camera.prototype.toString = function (fullDetails) {
  10603. var ret = "Name: " + this.name;
  10604. ret += ", type: " + this.getTypeName();
  10605. if (this.animations) {
  10606. for (var i = 0; i < this.animations.length; i++) {
  10607. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10608. }
  10609. }
  10610. if (fullDetails) {
  10611. }
  10612. return ret;
  10613. };
  10614. Object.defineProperty(Camera.prototype, "globalPosition", {
  10615. get: function () {
  10616. return this._globalPosition;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Camera.prototype.getActiveMeshes = function () {
  10622. return this._activeMeshes;
  10623. };
  10624. Camera.prototype.isActiveMesh = function (mesh) {
  10625. return (this._activeMeshes.indexOf(mesh) !== -1);
  10626. };
  10627. //Cache
  10628. Camera.prototype._initCache = function () {
  10629. _super.prototype._initCache.call(this);
  10630. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10631. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10632. this._cache.mode = undefined;
  10633. this._cache.minZ = undefined;
  10634. this._cache.maxZ = undefined;
  10635. this._cache.fov = undefined;
  10636. this._cache.aspectRatio = undefined;
  10637. this._cache.orthoLeft = undefined;
  10638. this._cache.orthoRight = undefined;
  10639. this._cache.orthoBottom = undefined;
  10640. this._cache.orthoTop = undefined;
  10641. this._cache.renderWidth = undefined;
  10642. this._cache.renderHeight = undefined;
  10643. };
  10644. Camera.prototype._updateCache = function (ignoreParentClass) {
  10645. if (!ignoreParentClass) {
  10646. _super.prototype._updateCache.call(this);
  10647. }
  10648. var engine = this.getEngine();
  10649. this._cache.position.copyFrom(this.position);
  10650. this._cache.upVector.copyFrom(this.upVector);
  10651. this._cache.mode = this.mode;
  10652. this._cache.minZ = this.minZ;
  10653. this._cache.maxZ = this.maxZ;
  10654. this._cache.fov = this.fov;
  10655. this._cache.aspectRatio = engine.getAspectRatio(this);
  10656. this._cache.orthoLeft = this.orthoLeft;
  10657. this._cache.orthoRight = this.orthoRight;
  10658. this._cache.orthoBottom = this.orthoBottom;
  10659. this._cache.orthoTop = this.orthoTop;
  10660. this._cache.renderWidth = engine.getRenderWidth();
  10661. this._cache.renderHeight = engine.getRenderHeight();
  10662. };
  10663. Camera.prototype._updateFromScene = function () {
  10664. this.updateCache();
  10665. this._update();
  10666. };
  10667. // Synchronized
  10668. Camera.prototype._isSynchronized = function () {
  10669. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10670. };
  10671. Camera.prototype._isSynchronizedViewMatrix = function () {
  10672. if (!_super.prototype._isSynchronized.call(this))
  10673. return false;
  10674. return this._cache.position.equals(this.position)
  10675. && this._cache.upVector.equals(this.upVector)
  10676. && this.isSynchronizedWithParent();
  10677. };
  10678. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10679. var check = this._cache.mode === this.mode
  10680. && this._cache.minZ === this.minZ
  10681. && this._cache.maxZ === this.maxZ;
  10682. if (!check) {
  10683. return false;
  10684. }
  10685. var engine = this.getEngine();
  10686. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10687. check = this._cache.fov === this.fov
  10688. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10689. }
  10690. else {
  10691. check = this._cache.orthoLeft === this.orthoLeft
  10692. && this._cache.orthoRight === this.orthoRight
  10693. && this._cache.orthoBottom === this.orthoBottom
  10694. && this._cache.orthoTop === this.orthoTop
  10695. && this._cache.renderWidth === engine.getRenderWidth()
  10696. && this._cache.renderHeight === engine.getRenderHeight();
  10697. }
  10698. return check;
  10699. };
  10700. // Controls
  10701. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10702. };
  10703. Camera.prototype.detachControl = function (element) {
  10704. };
  10705. Camera.prototype._update = function () {
  10706. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10707. this._updateRigCameras();
  10708. }
  10709. this._checkInputs();
  10710. };
  10711. Camera.prototype._checkInputs = function () {
  10712. };
  10713. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10714. if (insertAt === void 0) { insertAt = null; }
  10715. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10716. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10717. return 0;
  10718. }
  10719. if (insertAt == null || insertAt < 0) {
  10720. this._postProcesses.push(postProcess);
  10721. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10722. return this._postProcesses.length - 1;
  10723. }
  10724. var add = 0;
  10725. var i;
  10726. var start;
  10727. if (this._postProcesses[insertAt]) {
  10728. start = this._postProcesses.length - 1;
  10729. for (i = start; i >= insertAt + 1; --i) {
  10730. this._postProcesses[i + 1] = this._postProcesses[i];
  10731. }
  10732. add = 1;
  10733. }
  10734. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10735. if (this._postProcessesTakenIndices[i] < insertAt) {
  10736. continue;
  10737. }
  10738. start = this._postProcessesTakenIndices.length - 1;
  10739. for (var j = start; j >= i; --j) {
  10740. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10741. }
  10742. this._postProcessesTakenIndices[i] = insertAt;
  10743. break;
  10744. }
  10745. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10746. this._postProcessesTakenIndices.push(insertAt);
  10747. }
  10748. var result = insertAt + add;
  10749. this._postProcesses[result] = postProcess;
  10750. return result;
  10751. };
  10752. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10753. if (atIndices === void 0) { atIndices = null; }
  10754. var result = [];
  10755. var i;
  10756. var index;
  10757. if (!atIndices) {
  10758. var length = this._postProcesses.length;
  10759. for (i = 0; i < length; i++) {
  10760. if (this._postProcesses[i] !== postProcess) {
  10761. continue;
  10762. }
  10763. delete this._postProcesses[i];
  10764. index = this._postProcessesTakenIndices.indexOf(i);
  10765. this._postProcessesTakenIndices.splice(index, 1);
  10766. }
  10767. }
  10768. else {
  10769. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10770. for (i = 0; i < atIndices.length; i++) {
  10771. var foundPostProcess = this._postProcesses[atIndices[i]];
  10772. if (foundPostProcess !== postProcess) {
  10773. result.push(i);
  10774. continue;
  10775. }
  10776. delete this._postProcesses[atIndices[i]];
  10777. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10778. this._postProcessesTakenIndices.splice(index, 1);
  10779. }
  10780. }
  10781. return result;
  10782. };
  10783. Camera.prototype.getWorldMatrix = function () {
  10784. if (!this._worldMatrix) {
  10785. this._worldMatrix = BABYLON.Matrix.Identity();
  10786. }
  10787. var viewMatrix = this.getViewMatrix();
  10788. viewMatrix.invertToRef(this._worldMatrix);
  10789. return this._worldMatrix;
  10790. };
  10791. Camera.prototype._getViewMatrix = function () {
  10792. return BABYLON.Matrix.Identity();
  10793. };
  10794. Camera.prototype.getViewMatrix = function (force) {
  10795. this._computedViewMatrix = this._computeViewMatrix(force);
  10796. if (!force && this._isSynchronizedViewMatrix()) {
  10797. return this._computedViewMatrix;
  10798. }
  10799. if (!this.parent || !this.parent.getWorldMatrix) {
  10800. this._globalPosition.copyFrom(this.position);
  10801. }
  10802. else {
  10803. if (!this._worldMatrix) {
  10804. this._worldMatrix = BABYLON.Matrix.Identity();
  10805. }
  10806. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10807. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10808. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10809. this._computedViewMatrix.invert();
  10810. this._markSyncedWithParent();
  10811. }
  10812. this._currentRenderId = this.getScene().getRenderId();
  10813. return this._computedViewMatrix;
  10814. };
  10815. Camera.prototype._computeViewMatrix = function (force) {
  10816. if (!force && this._isSynchronizedViewMatrix()) {
  10817. return this._computedViewMatrix;
  10818. }
  10819. this._computedViewMatrix = this._getViewMatrix();
  10820. this._currentRenderId = this.getScene().getRenderId();
  10821. return this._computedViewMatrix;
  10822. };
  10823. Camera.prototype.getProjectionMatrix = function (force) {
  10824. if (!force && this._isSynchronizedProjectionMatrix()) {
  10825. return this._projectionMatrix;
  10826. }
  10827. var engine = this.getEngine();
  10828. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10829. if (this.minZ <= 0) {
  10830. this.minZ = 0.1;
  10831. }
  10832. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  10833. return this._projectionMatrix;
  10834. }
  10835. var halfWidth = engine.getRenderWidth() / 2.0;
  10836. var halfHeight = engine.getRenderHeight() / 2.0;
  10837. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10838. return this._projectionMatrix;
  10839. };
  10840. Camera.prototype.dispose = function () {
  10841. // Animations
  10842. this.getScene().stopAnimation(this);
  10843. // Remove from scene
  10844. this.getScene().removeCamera(this);
  10845. while (this._rigCameras.length > 0) {
  10846. this._rigCameras.pop().dispose();
  10847. }
  10848. // Postprocesses
  10849. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10850. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10851. }
  10852. _super.prototype.dispose.call(this);
  10853. };
  10854. // ---- Camera rigs section ----
  10855. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10856. while (this._rigCameras.length > 0) {
  10857. this._rigCameras.pop().dispose();
  10858. }
  10859. this.cameraRigMode = mode;
  10860. this._cameraRigParams = {};
  10861. switch (this.cameraRigMode) {
  10862. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10863. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10864. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10865. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10866. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10867. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10868. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10869. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10870. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10871. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10872. break;
  10873. }
  10874. var postProcesses = new Array();
  10875. switch (this.cameraRigMode) {
  10876. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10877. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10878. this._rigCameras[0].isIntermediate = true;
  10879. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10880. postProcesses[1].onApply = function (effect) {
  10881. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10882. };
  10883. break;
  10884. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10885. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10886. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10887. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10888. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10889. var secondCamIndex = 1 - firstCamIndex;
  10890. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10891. this._rigCameras[firstCamIndex].isIntermediate = true;
  10892. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10893. break;
  10894. case Camera.RIG_MODE_VR:
  10895. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10896. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10897. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10898. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10899. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10900. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10901. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10902. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10903. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10904. if (metrics.compensateDistortion) {
  10905. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10906. }
  10907. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10908. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10909. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10910. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10911. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10912. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10913. if (metrics.compensateDistortion) {
  10914. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10915. }
  10916. break;
  10917. }
  10918. this._update();
  10919. };
  10920. Camera.prototype._getVRProjectionMatrix = function () {
  10921. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10922. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10923. return this._projectionMatrix;
  10924. };
  10925. Camera.prototype.setCameraRigParameter = function (name, value) {
  10926. this._cameraRigParams[name] = value;
  10927. //provisionnally:
  10928. if (name === "interaxialDistance") {
  10929. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10930. }
  10931. };
  10932. /**
  10933. * May needs to be overridden by children so sub has required properties to be copied
  10934. */
  10935. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10936. return null;
  10937. };
  10938. /**
  10939. * May needs to be overridden by children
  10940. */
  10941. Camera.prototype._updateRigCameras = function () {
  10942. for (var i = 0; i < this._rigCameras.length; i++) {
  10943. this._rigCameras[i].minZ = this.minZ;
  10944. this._rigCameras[i].maxZ = this.maxZ;
  10945. this._rigCameras[i].fov = this.fov;
  10946. }
  10947. // only update viewport when ANAGLYPH
  10948. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10949. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10950. }
  10951. };
  10952. Camera.prototype.serialize = function () {
  10953. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10954. // Type
  10955. serializationObject.type = this.getTypeName();
  10956. // Parent
  10957. if (this.parent) {
  10958. serializationObject.parentId = this.parent.id;
  10959. }
  10960. if (this.inputs) {
  10961. this.inputs.serialize(serializationObject);
  10962. }
  10963. // Animations
  10964. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10965. serializationObject.ranges = this.serializeAnimationRanges();
  10966. return serializationObject;
  10967. };
  10968. Camera.prototype.getTypeName = function () {
  10969. return "Camera";
  10970. };
  10971. Camera.prototype.clone = function (name) {
  10972. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10973. };
  10974. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10975. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10976. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10977. switch (type) {
  10978. case "ArcRotateCamera":
  10979. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10980. case "DeviceOrientationCamera":
  10981. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10982. case "FollowCamera":
  10983. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10984. case "ArcFollowCamera":
  10985. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10986. case "GamepadCamera":
  10987. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10988. case "TouchCamera":
  10989. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10990. case "VirtualJoysticksCamera":
  10991. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10992. case "WebVRFreeCamera":
  10993. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10994. case "VRDeviceOrientationFreeCamera":
  10995. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10996. case "AnaglyphArcRotateCamera":
  10997. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10998. case "AnaglyphFreeCamera":
  10999. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11000. case "AnaglyphGamepadCamera":
  11001. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11002. case "AnaglyphUniversalCamera":
  11003. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11004. case "StereoscopicArcRotateCamera":
  11005. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11006. case "StereoscopicFreeCamera":
  11007. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11008. case "StereoscopicGamepadCamera":
  11009. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11010. case "StereoscopicUniversalCamera":
  11011. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11012. case "FreeCamera":
  11013. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11014. default:
  11015. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11016. }
  11017. };
  11018. Camera.Parse = function (parsedCamera, scene) {
  11019. var type = parsedCamera.type;
  11020. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11021. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11022. // Parent
  11023. if (parsedCamera.parentId) {
  11024. camera._waitingParentId = parsedCamera.parentId;
  11025. }
  11026. //If camera has an input manager, let it parse inputs settings
  11027. if (camera.inputs) {
  11028. camera.inputs.parse(parsedCamera);
  11029. }
  11030. // Target
  11031. if (parsedCamera.target) {
  11032. if (camera.setTarget) {
  11033. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11034. }
  11035. }
  11036. // Apply 3d rig, when found
  11037. if (parsedCamera.cameraRigMode) {
  11038. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11039. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11040. }
  11041. // Animations
  11042. if (parsedCamera.animations) {
  11043. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11044. var parsedAnimation = parsedCamera.animations[animationIndex];
  11045. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11046. }
  11047. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11048. }
  11049. if (parsedCamera.autoAnimate) {
  11050. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11051. }
  11052. return camera;
  11053. };
  11054. // Statics
  11055. Camera._PERSPECTIVE_CAMERA = 0;
  11056. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11057. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11058. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11059. Camera._RIG_MODE_NONE = 0;
  11060. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11061. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11062. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11063. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11064. Camera._RIG_MODE_VR = 20;
  11065. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11066. __decorate([
  11067. BABYLON.serializeAsVector3()
  11068. ], Camera.prototype, "position", void 0);
  11069. __decorate([
  11070. BABYLON.serialize()
  11071. ], Camera.prototype, "upVector", void 0);
  11072. __decorate([
  11073. BABYLON.serialize()
  11074. ], Camera.prototype, "orthoLeft", void 0);
  11075. __decorate([
  11076. BABYLON.serialize()
  11077. ], Camera.prototype, "orthoRight", void 0);
  11078. __decorate([
  11079. BABYLON.serialize()
  11080. ], Camera.prototype, "orthoBottom", void 0);
  11081. __decorate([
  11082. BABYLON.serialize()
  11083. ], Camera.prototype, "orthoTop", void 0);
  11084. __decorate([
  11085. BABYLON.serialize()
  11086. ], Camera.prototype, "fov", void 0);
  11087. __decorate([
  11088. BABYLON.serialize()
  11089. ], Camera.prototype, "minZ", void 0);
  11090. __decorate([
  11091. BABYLON.serialize()
  11092. ], Camera.prototype, "maxZ", void 0);
  11093. __decorate([
  11094. BABYLON.serialize()
  11095. ], Camera.prototype, "inertia", void 0);
  11096. __decorate([
  11097. BABYLON.serialize()
  11098. ], Camera.prototype, "mode", void 0);
  11099. __decorate([
  11100. BABYLON.serialize()
  11101. ], Camera.prototype, "layerMask", void 0);
  11102. __decorate([
  11103. BABYLON.serialize()
  11104. ], Camera.prototype, "fovMode", void 0);
  11105. __decorate([
  11106. BABYLON.serialize()
  11107. ], Camera.prototype, "cameraRigMode", void 0);
  11108. __decorate([
  11109. BABYLON.serialize()
  11110. ], Camera.prototype, "interaxialDistance", void 0);
  11111. __decorate([
  11112. BABYLON.serialize()
  11113. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11114. return Camera;
  11115. })(BABYLON.Node);
  11116. BABYLON.Camera = Camera;
  11117. })(BABYLON || (BABYLON = {}));
  11118. var BABYLON;
  11119. (function (BABYLON) {
  11120. BABYLON.CameraInputTypes = {};
  11121. var CameraInputsManager = (function () {
  11122. function CameraInputsManager(camera) {
  11123. this.attached = {};
  11124. this.camera = camera;
  11125. this.checkInputs = function () { };
  11126. }
  11127. CameraInputsManager.prototype.add = function (input) {
  11128. var type = input.getSimpleName();
  11129. if (this.attached[type]) {
  11130. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11131. return;
  11132. }
  11133. this.attached[type] = input;
  11134. input.camera = this.camera;
  11135. //for checkInputs, we are dynamically creating a function
  11136. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11137. if (input.checkInputs) {
  11138. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11139. }
  11140. if (this.attachedElement) {
  11141. input.attachControl(this.attachedElement);
  11142. }
  11143. };
  11144. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11145. for (var cam in this.attached) {
  11146. var input = this.attached[cam];
  11147. if (input === inputToRemove) {
  11148. input.detachControl(this.attachedElement);
  11149. delete this.attached[cam];
  11150. }
  11151. }
  11152. };
  11153. CameraInputsManager.prototype.removeByType = function (inputType) {
  11154. for (var cam in this.attached) {
  11155. var input = this.attached[cam];
  11156. if (input.getTypeName() === inputType) {
  11157. input.detachControl(this.attachedElement);
  11158. delete this.attached[cam];
  11159. }
  11160. }
  11161. };
  11162. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11163. var current = this.checkInputs;
  11164. return function () {
  11165. current();
  11166. fn();
  11167. };
  11168. };
  11169. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11170. this.attachedElement = element;
  11171. for (var cam in this.attached) {
  11172. var input = this.attached[cam];
  11173. this.attached[cam].attachControl(element, noPreventDefault);
  11174. }
  11175. };
  11176. CameraInputsManager.prototype.detachElement = function (element) {
  11177. for (var cam in this.attached) {
  11178. var input = this.attached[cam];
  11179. this.attached[cam].detachControl(element);
  11180. }
  11181. };
  11182. CameraInputsManager.prototype.rebuildInputCheck = function (element) {
  11183. this.checkInputs = function () { };
  11184. for (var cam in this.attached) {
  11185. var input = this.attached[cam];
  11186. if (input.checkInputs) {
  11187. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11188. }
  11189. }
  11190. };
  11191. CameraInputsManager.prototype.clear = function () {
  11192. if (this.attachedElement) {
  11193. this.detachElement(this.attachedElement);
  11194. }
  11195. this.attached = {};
  11196. this.attachedElement = null;
  11197. this.checkInputs = function () { };
  11198. };
  11199. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11200. var inputs = {};
  11201. for (var cam in this.attached) {
  11202. var input = this.attached[cam];
  11203. var res = BABYLON.SerializationHelper.Serialize(input, serializedCamera);
  11204. inputs[input.getTypeName()] = res;
  11205. }
  11206. serializedCamera.inputsmgr = inputs;
  11207. };
  11208. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11209. var parsedInputs = parsedCamera.inputsmgr;
  11210. if (parsedInputs) {
  11211. this.clear();
  11212. for (var n in parsedInputs) {
  11213. var construct = BABYLON.CameraInputTypes[n];
  11214. if (construct) {
  11215. var parsedinput = parsedInputs[n];
  11216. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11217. this.add(input);
  11218. }
  11219. }
  11220. }
  11221. else {
  11222. //2016-03-08 this part is for managing backward compatibility
  11223. for (var n in this.attached) {
  11224. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11225. if (construct) {
  11226. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11227. this.add(input);
  11228. }
  11229. }
  11230. }
  11231. };
  11232. return CameraInputsManager;
  11233. })();
  11234. BABYLON.CameraInputsManager = CameraInputsManager;
  11235. })(BABYLON || (BABYLON = {}));
  11236. var BABYLON;
  11237. (function (BABYLON) {
  11238. var FreeCameraMouseInput = (function () {
  11239. function FreeCameraMouseInput() {
  11240. this.angularSensibility = 2000.0;
  11241. }
  11242. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11243. var _this = this;
  11244. if (this._onMouseDown === undefined) {
  11245. var camera = this.camera;
  11246. var engine = this.camera.getEngine();
  11247. this._onMouseDown = function (evt) {
  11248. _this.previousPosition = {
  11249. x: evt.clientX,
  11250. y: evt.clientY
  11251. };
  11252. if (!noPreventDefault) {
  11253. evt.preventDefault();
  11254. }
  11255. };
  11256. this._onMouseUp = function (evt) {
  11257. _this.previousPosition = null;
  11258. if (!noPreventDefault) {
  11259. evt.preventDefault();
  11260. }
  11261. };
  11262. this._onMouseOut = function (evt) {
  11263. _this.previousPosition = null;
  11264. if (!noPreventDefault) {
  11265. evt.preventDefault();
  11266. }
  11267. };
  11268. this._onMouseMove = function (evt) {
  11269. if (!_this.previousPosition && !engine.isPointerLock) {
  11270. return;
  11271. }
  11272. var offsetX;
  11273. var offsetY;
  11274. if (!engine.isPointerLock) {
  11275. offsetX = evt.clientX - _this.previousPosition.x;
  11276. offsetY = evt.clientY - _this.previousPosition.y;
  11277. }
  11278. else {
  11279. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11280. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11281. }
  11282. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11283. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11284. _this.previousPosition = {
  11285. x: evt.clientX,
  11286. y: evt.clientY
  11287. };
  11288. if (!noPreventDefault) {
  11289. evt.preventDefault();
  11290. }
  11291. };
  11292. }
  11293. element.addEventListener("mousedown", this._onMouseDown, false);
  11294. element.addEventListener("mouseup", this._onMouseUp, false);
  11295. element.addEventListener("mouseout", this._onMouseOut, false);
  11296. element.addEventListener("mousemove", this._onMouseMove, false);
  11297. };
  11298. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11299. if (this._onMouseDown && element) {
  11300. this.previousPosition = null;
  11301. element.removeEventListener("mousedown", this._onMouseDown);
  11302. element.removeEventListener("mouseup", this._onMouseUp);
  11303. element.removeEventListener("mouseout", this._onMouseOut);
  11304. element.removeEventListener("mousemove", this._onMouseMove);
  11305. }
  11306. };
  11307. FreeCameraMouseInput.prototype.getTypeName = function () {
  11308. return "FreeCameraMouseInput";
  11309. };
  11310. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11311. return "mouse";
  11312. };
  11313. __decorate([
  11314. BABYLON.serialize()
  11315. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11316. return FreeCameraMouseInput;
  11317. })();
  11318. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11319. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11320. })(BABYLON || (BABYLON = {}));
  11321. var BABYLON;
  11322. (function (BABYLON) {
  11323. var FreeCameraKeyboardMoveInput = (function () {
  11324. function FreeCameraKeyboardMoveInput() {
  11325. this._keys = [];
  11326. this.keysUp = [38];
  11327. this.keysDown = [40];
  11328. this.keysLeft = [37];
  11329. this.keysRight = [39];
  11330. }
  11331. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11332. var _this = this;
  11333. if (this._onKeyDown === undefined) {
  11334. this._onKeyDown = function (evt) {
  11335. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11336. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11337. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11338. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11339. var index = _this._keys.indexOf(evt.keyCode);
  11340. if (index === -1) {
  11341. _this._keys.push(evt.keyCode);
  11342. }
  11343. if (!noPreventDefault) {
  11344. evt.preventDefault();
  11345. }
  11346. }
  11347. };
  11348. this._onKeyUp = function (evt) {
  11349. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11350. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11351. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11352. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11353. var index = _this._keys.indexOf(evt.keyCode);
  11354. if (index >= 0) {
  11355. _this._keys.splice(index, 1);
  11356. }
  11357. if (!noPreventDefault) {
  11358. evt.preventDefault();
  11359. }
  11360. }
  11361. };
  11362. BABYLON.Tools.RegisterTopRootEvents([
  11363. { name: "keydown", handler: this._onKeyDown },
  11364. { name: "keyup", handler: this._onKeyUp },
  11365. { name: "blur", handler: this._onLostFocus }
  11366. ]);
  11367. }
  11368. };
  11369. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11370. BABYLON.Tools.UnregisterTopRootEvents([
  11371. { name: "keydown", handler: this._onKeyDown },
  11372. { name: "keyup", handler: this._onKeyUp },
  11373. { name: "blur", handler: this._onLostFocus }
  11374. ]);
  11375. };
  11376. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11377. var camera = this.camera;
  11378. // Keyboard
  11379. for (var index = 0; index < this._keys.length; index++) {
  11380. var keyCode = this._keys[index];
  11381. var speed = camera._computeLocalCameraSpeed();
  11382. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11383. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11384. }
  11385. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11386. camera._localDirection.copyFromFloats(0, 0, speed);
  11387. }
  11388. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11389. camera._localDirection.copyFromFloats(speed, 0, 0);
  11390. }
  11391. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11392. camera._localDirection.copyFromFloats(0, 0, -speed);
  11393. }
  11394. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11395. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11396. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11397. }
  11398. };
  11399. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11400. return "FreeCameraKeyboardMoveInput";
  11401. };
  11402. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11403. this._keys = [];
  11404. };
  11405. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11406. return "keyboard";
  11407. };
  11408. __decorate([
  11409. BABYLON.serialize()
  11410. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11411. __decorate([
  11412. BABYLON.serialize()
  11413. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11414. __decorate([
  11415. BABYLON.serialize()
  11416. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11417. __decorate([
  11418. BABYLON.serialize()
  11419. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11420. return FreeCameraKeyboardMoveInput;
  11421. })();
  11422. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11423. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11424. })(BABYLON || (BABYLON = {}));
  11425. var BABYLON;
  11426. (function (BABYLON) {
  11427. var FreeCameraTouchInput = (function () {
  11428. function FreeCameraTouchInput() {
  11429. this._offsetX = null;
  11430. this._offsetY = null;
  11431. this._pointerCount = 0;
  11432. this._pointerPressed = [];
  11433. this.touchAngularSensibility = 200000.0;
  11434. this.touchMoveSensibility = 250.0;
  11435. }
  11436. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11437. var _this = this;
  11438. var previousPosition;
  11439. if (this._onPointerDown === undefined) {
  11440. this._onLostFocus = function (evt) {
  11441. _this._offsetX = null;
  11442. _this._offsetY = null;
  11443. };
  11444. this._onPointerDown = function (evt) {
  11445. if (evt.pointerType === "mouse") {
  11446. return;
  11447. }
  11448. if (!noPreventDefault) {
  11449. evt.preventDefault();
  11450. }
  11451. _this._pointerPressed.push(evt.pointerId);
  11452. if (_this._pointerPressed.length !== 1) {
  11453. return;
  11454. }
  11455. previousPosition = {
  11456. x: evt.clientX,
  11457. y: evt.clientY
  11458. };
  11459. };
  11460. this._onPointerUp = function (evt) {
  11461. if (evt.pointerType === "mouse") {
  11462. return;
  11463. }
  11464. if (!noPreventDefault) {
  11465. evt.preventDefault();
  11466. }
  11467. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11468. if (index === -1) {
  11469. return;
  11470. }
  11471. _this._pointerPressed.splice(index, 1);
  11472. if (index != 0) {
  11473. return;
  11474. }
  11475. previousPosition = null;
  11476. _this._offsetX = null;
  11477. _this._offsetY = null;
  11478. };
  11479. this._onPointerMove = function (evt) {
  11480. if (evt.pointerType === "mouse") {
  11481. return;
  11482. }
  11483. if (!noPreventDefault) {
  11484. evt.preventDefault();
  11485. }
  11486. if (!previousPosition) {
  11487. return;
  11488. }
  11489. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11490. if (index != 0) {
  11491. return;
  11492. }
  11493. _this._offsetX = evt.clientX - previousPosition.x;
  11494. _this._offsetY = -(evt.clientY - previousPosition.y);
  11495. };
  11496. }
  11497. element.addEventListener("blur", this._onLostFocus);
  11498. element.addEventListener("pointerdown", this._onPointerDown);
  11499. element.addEventListener("pointerup", this._onPointerUp);
  11500. element.addEventListener("pointerout", this._onPointerUp);
  11501. element.addEventListener("pointermove", this._onPointerMove);
  11502. };
  11503. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11504. element.removeEventListener("blur", this._onLostFocus);
  11505. element.removeEventListener("pointerdown", this._onPointerDown);
  11506. element.removeEventListener("pointerup", this._onPointerUp);
  11507. element.removeEventListener("pointerout", this._onPointerUp);
  11508. element.removeEventListener("pointermove", this._onPointerMove);
  11509. };
  11510. FreeCameraTouchInput.prototype.checkInputs = function () {
  11511. if (this._offsetX) {
  11512. var camera = this.camera;
  11513. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11514. if (this._pointerPressed.length > 1) {
  11515. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11516. }
  11517. else {
  11518. var speed = camera._computeLocalCameraSpeed();
  11519. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11520. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11521. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11522. }
  11523. }
  11524. };
  11525. FreeCameraTouchInput.prototype.getTypeName = function () {
  11526. return "FreeCameraTouchInput";
  11527. };
  11528. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11529. return "touch";
  11530. };
  11531. __decorate([
  11532. BABYLON.serialize()
  11533. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11534. __decorate([
  11535. BABYLON.serialize()
  11536. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11537. return FreeCameraTouchInput;
  11538. })();
  11539. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11540. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11541. })(BABYLON || (BABYLON = {}));
  11542. var BABYLON;
  11543. (function (BABYLON) {
  11544. var FreeCameraDeviceOrientationInput = (function () {
  11545. function FreeCameraDeviceOrientationInput() {
  11546. this._offsetX = null;
  11547. this._offsetY = null;
  11548. this._orientationGamma = 0;
  11549. this._orientationBeta = 0;
  11550. this._initialOrientationGamma = 0;
  11551. this._initialOrientationBeta = 0;
  11552. this.angularSensibility = 10000.0;
  11553. this.moveSensibility = 50.0;
  11554. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11555. this._orientationChanged = this.orientationChanged.bind(this);
  11556. }
  11557. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11558. window.addEventListener("resize", this._resetOrientationGamma, false);
  11559. window.addEventListener("deviceorientation", this._orientationChanged);
  11560. };
  11561. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11562. this._initialOrientationGamma = null;
  11563. };
  11564. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11565. if (!this._initialOrientationGamma) {
  11566. this._initialOrientationGamma = evt.gamma;
  11567. this._initialOrientationBeta = evt.beta;
  11568. }
  11569. this._orientationGamma = evt.gamma;
  11570. this._orientationBeta = evt.beta;
  11571. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11572. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11573. };
  11574. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11575. window.removeEventListener("resize", this._resetOrientationGamma);
  11576. window.removeEventListener("deviceorientation", this._orientationChanged);
  11577. this._orientationGamma = 0;
  11578. this._orientationBeta = 0;
  11579. this._initialOrientationGamma = 0;
  11580. this._initialOrientationBeta = 0;
  11581. };
  11582. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11583. if (!this._offsetX) {
  11584. return;
  11585. }
  11586. var camera = this.camera;
  11587. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11588. var speed = camera._computeLocalCameraSpeed();
  11589. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11590. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11591. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11592. };
  11593. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11594. return "FreeCameraDeviceOrientationInput";
  11595. };
  11596. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11597. return "deviceOrientation";
  11598. };
  11599. __decorate([
  11600. BABYLON.serialize()
  11601. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11602. __decorate([
  11603. BABYLON.serialize()
  11604. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11605. return FreeCameraDeviceOrientationInput;
  11606. })();
  11607. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11608. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11609. })(BABYLON || (BABYLON = {}));
  11610. var BABYLON;
  11611. (function (BABYLON) {
  11612. var FreeCameraVRDeviceOrientationInput = (function () {
  11613. function FreeCameraVRDeviceOrientationInput() {
  11614. this.alphaCorrection = 1;
  11615. this.betaCorrection = 1;
  11616. this.gammaCorrection = 1;
  11617. this._alpha = 0;
  11618. this._beta = 0;
  11619. this._gamma = 0;
  11620. this._dirty = false;
  11621. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11622. }
  11623. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11624. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11625. };
  11626. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11627. var camera = this.camera;
  11628. this._alpha = +evt.alpha | 0;
  11629. this._beta = +evt.beta | 0;
  11630. this._gamma = +evt.gamma | 0;
  11631. this._dirty = true;
  11632. };
  11633. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  11634. if (this._dirty) {
  11635. this._dirty = false;
  11636. var rotationX = this._gamma;
  11637. if (rotationX < 0) {
  11638. rotationX = 90 + rotationX;
  11639. }
  11640. else {
  11641. // Incline it in the correct angle.
  11642. rotationX = 270 - rotationX;
  11643. }
  11644. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  11645. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  11646. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  11647. }
  11648. };
  11649. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  11650. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11651. };
  11652. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  11653. return "FreeCameraVRDeviceOrientationInput";
  11654. };
  11655. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  11656. return "VRDeviceOrientation";
  11657. };
  11658. return FreeCameraVRDeviceOrientationInput;
  11659. })();
  11660. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  11661. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  11662. })(BABYLON || (BABYLON = {}));
  11663. var BABYLON;
  11664. (function (BABYLON) {
  11665. var FreeCameraGamepadInput = (function () {
  11666. function FreeCameraGamepadInput() {
  11667. this.gamepadAngularSensibility = 200;
  11668. this.gamepadMoveSensibility = 40;
  11669. }
  11670. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  11671. var _this = this;
  11672. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11673. };
  11674. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  11675. if (this._gamepads) {
  11676. this._gamepads.dispose();
  11677. }
  11678. this.gamepad = null;
  11679. };
  11680. FreeCameraGamepadInput.prototype.checkInputs = function () {
  11681. if (this.gamepad) {
  11682. var camera = this.camera;
  11683. var LSValues = this.gamepad.leftStick;
  11684. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  11685. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  11686. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11687. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11688. var RSValues = this.gamepad.rightStick;
  11689. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  11690. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  11691. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11692. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11693. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11694. var speed = camera._computeLocalCameraSpeed() * 50.0;
  11695. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11696. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11697. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11698. }
  11699. };
  11700. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  11701. // Only the first gamepad can control the camera
  11702. if (gamepad.index === 0) {
  11703. this.gamepad = gamepad;
  11704. }
  11705. };
  11706. FreeCameraGamepadInput.prototype.getTypeName = function () {
  11707. return "FreeCameraGamepadInput";
  11708. };
  11709. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  11710. return "gamepad";
  11711. };
  11712. __decorate([
  11713. BABYLON.serialize()
  11714. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  11715. __decorate([
  11716. BABYLON.serialize()
  11717. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  11718. return FreeCameraGamepadInput;
  11719. })();
  11720. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  11721. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  11722. })(BABYLON || (BABYLON = {}));
  11723. var BABYLON;
  11724. (function (BABYLON) {
  11725. var FreeCameraVirtualJoystickInput = (function () {
  11726. function FreeCameraVirtualJoystickInput() {
  11727. }
  11728. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  11729. return this._leftjoystick;
  11730. };
  11731. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  11732. return this._rightjoystick;
  11733. };
  11734. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  11735. if (this._leftjoystick) {
  11736. var camera = this.camera;
  11737. var speed = camera._computeLocalCameraSpeed() * 50;
  11738. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11739. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  11740. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11741. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  11742. if (!this._leftjoystick.pressed) {
  11743. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  11744. }
  11745. if (!this._rightjoystick.pressed) {
  11746. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  11747. }
  11748. }
  11749. };
  11750. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  11751. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  11752. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  11753. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  11754. this._leftjoystick.setJoystickSensibility(0.15);
  11755. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  11756. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  11757. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  11758. this._rightjoystick.reverseUpDown = true;
  11759. this._rightjoystick.setJoystickSensibility(0.05);
  11760. this._rightjoystick.setJoystickColor("yellow");
  11761. };
  11762. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  11763. this._leftjoystick.releaseCanvas();
  11764. this._rightjoystick.releaseCanvas();
  11765. };
  11766. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  11767. return "FreeCameraVirtualJoystickInput";
  11768. };
  11769. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  11770. return "virtualJoystick";
  11771. };
  11772. return FreeCameraVirtualJoystickInput;
  11773. })();
  11774. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  11775. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  11776. })(BABYLON || (BABYLON = {}));
  11777. var BABYLON;
  11778. (function (BABYLON) {
  11779. var ArcRotateCameraKeyboardMoveInput = (function () {
  11780. function ArcRotateCameraKeyboardMoveInput() {
  11781. this._keys = [];
  11782. this.keysUp = [38];
  11783. this.keysDown = [40];
  11784. this.keysLeft = [37];
  11785. this.keysRight = [39];
  11786. }
  11787. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11788. var _this = this;
  11789. this._onKeyDown = function (evt) {
  11790. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11791. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11792. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11793. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11794. var index = _this._keys.indexOf(evt.keyCode);
  11795. if (index === -1) {
  11796. _this._keys.push(evt.keyCode);
  11797. }
  11798. if (evt.preventDefault) {
  11799. if (!noPreventDefault) {
  11800. evt.preventDefault();
  11801. }
  11802. }
  11803. }
  11804. };
  11805. this._onKeyUp = function (evt) {
  11806. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11807. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11808. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11809. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11810. var index = _this._keys.indexOf(evt.keyCode);
  11811. if (index >= 0) {
  11812. _this._keys.splice(index, 1);
  11813. }
  11814. if (evt.preventDefault) {
  11815. if (!noPreventDefault) {
  11816. evt.preventDefault();
  11817. }
  11818. }
  11819. }
  11820. };
  11821. this._onLostFocus = function () {
  11822. _this._keys = [];
  11823. };
  11824. BABYLON.Tools.RegisterTopRootEvents([
  11825. { name: "keydown", handler: this._onKeyDown },
  11826. { name: "keyup", handler: this._onKeyUp },
  11827. { name: "blur", handler: this._onLostFocus }
  11828. ]);
  11829. };
  11830. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11831. BABYLON.Tools.UnregisterTopRootEvents([
  11832. { name: "keydown", handler: this._onKeyDown },
  11833. { name: "keyup", handler: this._onKeyUp },
  11834. { name: "blur", handler: this._onLostFocus }
  11835. ]);
  11836. };
  11837. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11838. var camera = this.camera;
  11839. for (var index = 0; index < this._keys.length; index++) {
  11840. var keyCode = this._keys[index];
  11841. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11842. camera.inertialAlphaOffset -= 0.01;
  11843. }
  11844. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11845. camera.inertialBetaOffset -= 0.01;
  11846. }
  11847. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11848. camera.inertialAlphaOffset += 0.01;
  11849. }
  11850. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11851. camera.inertialBetaOffset += 0.01;
  11852. }
  11853. }
  11854. };
  11855. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11856. return "ArcRotateCameraKeyboardMoveInput";
  11857. };
  11858. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11859. return "keyboard";
  11860. };
  11861. __decorate([
  11862. BABYLON.serialize()
  11863. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11864. __decorate([
  11865. BABYLON.serialize()
  11866. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11867. __decorate([
  11868. BABYLON.serialize()
  11869. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11870. __decorate([
  11871. BABYLON.serialize()
  11872. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11873. return ArcRotateCameraKeyboardMoveInput;
  11874. })();
  11875. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  11876. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  11877. })(BABYLON || (BABYLON = {}));
  11878. var BABYLON;
  11879. (function (BABYLON) {
  11880. var ArcRotateCameraMouseWheelInput = (function () {
  11881. function ArcRotateCameraMouseWheelInput() {
  11882. this.wheelPrecision = 3.0;
  11883. }
  11884. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  11885. var _this = this;
  11886. this._wheel = function (event) {
  11887. var delta = 0;
  11888. if (event.wheelDelta) {
  11889. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11890. }
  11891. else if (event.detail) {
  11892. delta = -event.detail / _this.wheelPrecision;
  11893. }
  11894. if (delta)
  11895. _this.camera.inertialRadiusOffset += delta;
  11896. if (event.preventDefault) {
  11897. if (!_this.camera._noPreventDefault) {
  11898. event.preventDefault();
  11899. }
  11900. }
  11901. };
  11902. element.addEventListener('mousewheel', this._wheel, false);
  11903. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11904. };
  11905. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  11906. if (this._wheel && element) {
  11907. element.removeEventListener('mousewheel', this._wheel);
  11908. element.removeEventListener('DOMMouseScroll', this._wheel);
  11909. }
  11910. };
  11911. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  11912. return "ArcRotateCameraMouseWheelInput";
  11913. };
  11914. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  11915. return "mousewheel";
  11916. };
  11917. __decorate([
  11918. BABYLON.serialize()
  11919. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  11920. return ArcRotateCameraMouseWheelInput;
  11921. })();
  11922. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  11923. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  11924. })(BABYLON || (BABYLON = {}));
  11925. var BABYLON;
  11926. (function (BABYLON) {
  11927. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11928. var ArcRotateCameraPointersInput = (function () {
  11929. function ArcRotateCameraPointersInput() {
  11930. this._isRightClick = false;
  11931. this._isCtrlPushed = false;
  11932. this.pinchInwards = true;
  11933. this.angularSensibilityX = 1000.0;
  11934. this.angularSensibilityY = 1000.0;
  11935. this.pinchPrecision = 6.0;
  11936. this.panningSensibility = 50.0;
  11937. }
  11938. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  11939. var _this = this;
  11940. var engine = this.camera.getEngine();
  11941. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11942. var pointers = new BABYLON.SmartCollection();
  11943. var previousPinchDistance = 0;
  11944. if (!this.camera._useCtrlForPanning) {
  11945. element.addEventListener("contextmenu", this._onContextMenu, false);
  11946. }
  11947. this._onLostFocus = function () {
  11948. //this._keys = [];
  11949. pointers.empty();
  11950. previousPinchDistance = 0;
  11951. cacheSoloPointer = null;
  11952. };
  11953. this._onKeyDown = function (evt) {
  11954. _this._isCtrlPushed = evt.ctrlKey;
  11955. };
  11956. this._onKeyUp = function (evt) {
  11957. _this._isCtrlPushed = evt.ctrlKey;
  11958. };
  11959. this._onPointerDown = function (evt) {
  11960. // Manage panning with right click
  11961. _this._isRightClick = evt.button === 2;
  11962. // manage pointers
  11963. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11964. cacheSoloPointer = pointers.item(evt.pointerId);
  11965. if (!noPreventDefault) {
  11966. evt.preventDefault();
  11967. }
  11968. };
  11969. this._onPointerUp = function (evt) {
  11970. cacheSoloPointer = null;
  11971. previousPinchDistance = 0;
  11972. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11973. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11974. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11975. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11976. pointers.empty();
  11977. if (!noPreventDefault) {
  11978. evt.preventDefault();
  11979. }
  11980. };
  11981. this._onContextMenu = function (evt) {
  11982. evt.preventDefault();
  11983. };
  11984. this._onPointerMove = function (evt) {
  11985. if (!noPreventDefault) {
  11986. evt.preventDefault();
  11987. }
  11988. switch (pointers.count) {
  11989. case 1:
  11990. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  11991. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11992. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11993. }
  11994. else {
  11995. var offsetX = evt.clientX - cacheSoloPointer.x;
  11996. var offsetY = evt.clientY - cacheSoloPointer.y;
  11997. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11998. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11999. }
  12000. cacheSoloPointer.x = evt.clientX;
  12001. cacheSoloPointer.y = evt.clientY;
  12002. break;
  12003. case 2:
  12004. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12005. pointers.item(evt.pointerId).x = evt.clientX;
  12006. pointers.item(evt.pointerId).y = evt.clientY;
  12007. var direction = _this.pinchInwards ? 1 : -1;
  12008. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  12009. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  12010. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12011. if (previousPinchDistance === 0) {
  12012. previousPinchDistance = pinchSquaredDistance;
  12013. return;
  12014. }
  12015. if (pinchSquaredDistance !== previousPinchDistance) {
  12016. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12017. previousPinchDistance = pinchSquaredDistance;
  12018. }
  12019. break;
  12020. default:
  12021. if (pointers.item(evt.pointerId)) {
  12022. pointers.item(evt.pointerId).x = evt.clientX;
  12023. pointers.item(evt.pointerId).y = evt.clientY;
  12024. }
  12025. }
  12026. };
  12027. this._onMouseMove = function (evt) {
  12028. if (!engine.isPointerLock) {
  12029. return;
  12030. }
  12031. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12032. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12033. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12034. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12035. if (!noPreventDefault) {
  12036. evt.preventDefault();
  12037. }
  12038. };
  12039. this._onGestureStart = function (e) {
  12040. if (window.MSGesture === undefined) {
  12041. return;
  12042. }
  12043. if (!_this._MSGestureHandler) {
  12044. _this._MSGestureHandler = new MSGesture();
  12045. _this._MSGestureHandler.target = element;
  12046. }
  12047. _this._MSGestureHandler.addPointer(e.pointerId);
  12048. };
  12049. this._onGesture = function (e) {
  12050. _this.camera.radius *= e.scale;
  12051. if (e.preventDefault) {
  12052. if (!noPreventDefault) {
  12053. e.stopPropagation();
  12054. e.preventDefault();
  12055. }
  12056. }
  12057. };
  12058. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12059. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12060. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12061. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12062. element.addEventListener("mousemove", this._onMouseMove, false);
  12063. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12064. element.addEventListener("MSGestureChange", this._onGesture, false);
  12065. BABYLON.Tools.RegisterTopRootEvents([
  12066. { name: "blur", handler: this._onLostFocus }
  12067. ]);
  12068. };
  12069. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12070. this._MSGestureHandler = null;
  12071. if (element && this._onPointerDown) {
  12072. element.removeEventListener("contextmenu", this._onContextMenu);
  12073. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12074. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12075. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12076. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12077. element.removeEventListener("mousemove", this._onMouseMove);
  12078. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12079. element.removeEventListener("MSGestureChange", this._onGesture);
  12080. }
  12081. BABYLON.Tools.UnregisterTopRootEvents([
  12082. { name: "blur", handler: this._onLostFocus }
  12083. ]);
  12084. };
  12085. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12086. return "ArcRotateCameraPointersInput";
  12087. };
  12088. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12089. return "pointers";
  12090. };
  12091. __decorate([
  12092. BABYLON.serialize()
  12093. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12094. __decorate([
  12095. BABYLON.serialize()
  12096. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12097. __decorate([
  12098. BABYLON.serialize()
  12099. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12100. __decorate([
  12101. BABYLON.serialize()
  12102. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12103. return ArcRotateCameraPointersInput;
  12104. })();
  12105. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12106. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12107. })(BABYLON || (BABYLON = {}));
  12108. var BABYLON;
  12109. (function (BABYLON) {
  12110. var ArcRotateCameraGamepadInput = (function () {
  12111. function ArcRotateCameraGamepadInput() {
  12112. this.gamepadRotationSensibility = 80;
  12113. this.gamepadMoveSensibility = 40;
  12114. }
  12115. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12116. var _this = this;
  12117. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12118. };
  12119. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12120. if (this._gamepads) {
  12121. this._gamepads.dispose();
  12122. }
  12123. this.gamepad = null;
  12124. };
  12125. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12126. if (this.gamepad) {
  12127. var camera = this.camera;
  12128. var RSValues = this.gamepad.rightStick;
  12129. if (RSValues.x != 0) {
  12130. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12131. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12132. camera.inertialAlphaOffset += normalizedRX;
  12133. }
  12134. }
  12135. if (RSValues.y != 0) {
  12136. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12137. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12138. camera.inertialBetaOffset += normalizedRY;
  12139. }
  12140. }
  12141. var LSValues = this.gamepad.leftStick;
  12142. if (LSValues.y != 0) {
  12143. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12144. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12145. this.camera.inertialRadiusOffset -= normalizedLY;
  12146. }
  12147. }
  12148. }
  12149. };
  12150. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12151. // Only the first gamepad can control the camera
  12152. if (gamepad.index === 0) {
  12153. this.gamepad = gamepad;
  12154. }
  12155. };
  12156. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12157. return "ArcRotateCameraGamepadInput";
  12158. };
  12159. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12160. return "gamepad";
  12161. };
  12162. __decorate([
  12163. BABYLON.serialize()
  12164. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12165. __decorate([
  12166. BABYLON.serialize()
  12167. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12168. return ArcRotateCameraGamepadInput;
  12169. })();
  12170. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12171. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12172. })(BABYLON || (BABYLON = {}));
  12173. var BABYLON;
  12174. (function (BABYLON) {
  12175. var TargetCamera = (function (_super) {
  12176. __extends(TargetCamera, _super);
  12177. function TargetCamera(name, position, scene) {
  12178. _super.call(this, name, position, scene);
  12179. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12180. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12181. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12182. this.speed = 2.0;
  12183. this.noRotationConstraint = false;
  12184. this.lockedTarget = null;
  12185. this._currentTarget = BABYLON.Vector3.Zero();
  12186. this._viewMatrix = BABYLON.Matrix.Zero();
  12187. this._camMatrix = BABYLON.Matrix.Zero();
  12188. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12189. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12190. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12191. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12192. this._lookAtTemp = BABYLON.Matrix.Zero();
  12193. this._tempMatrix = BABYLON.Matrix.Zero();
  12194. }
  12195. TargetCamera.prototype.getFrontPosition = function (distance) {
  12196. var direction = this.getTarget().subtract(this.position);
  12197. direction.normalize();
  12198. direction.scaleInPlace(distance);
  12199. return this.globalPosition.add(direction);
  12200. };
  12201. TargetCamera.prototype._getLockedTargetPosition = function () {
  12202. if (!this.lockedTarget) {
  12203. return null;
  12204. }
  12205. return this.lockedTarget.position || this.lockedTarget;
  12206. };
  12207. // Cache
  12208. TargetCamera.prototype._initCache = function () {
  12209. _super.prototype._initCache.call(this);
  12210. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12211. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12212. };
  12213. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12214. if (!ignoreParentClass) {
  12215. _super.prototype._updateCache.call(this);
  12216. }
  12217. var lockedTargetPosition = this._getLockedTargetPosition();
  12218. if (!lockedTargetPosition) {
  12219. this._cache.lockedTarget = null;
  12220. }
  12221. else {
  12222. if (!this._cache.lockedTarget) {
  12223. this._cache.lockedTarget = lockedTargetPosition.clone();
  12224. }
  12225. else {
  12226. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12227. }
  12228. }
  12229. this._cache.rotation.copyFrom(this.rotation);
  12230. };
  12231. // Synchronized
  12232. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12233. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12234. return false;
  12235. }
  12236. var lockedTargetPosition = this._getLockedTargetPosition();
  12237. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12238. && this._cache.rotation.equals(this.rotation);
  12239. };
  12240. // Methods
  12241. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12242. var engine = this.getEngine();
  12243. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12244. };
  12245. // Target
  12246. TargetCamera.prototype.setTarget = function (target) {
  12247. this.upVector.normalize();
  12248. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12249. this._camMatrix.invert();
  12250. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12251. var vDir = target.subtract(this.position);
  12252. if (vDir.x >= 0.0) {
  12253. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12254. }
  12255. else {
  12256. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12257. }
  12258. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12259. if (isNaN(this.rotation.x)) {
  12260. this.rotation.x = 0;
  12261. }
  12262. if (isNaN(this.rotation.y)) {
  12263. this.rotation.y = 0;
  12264. }
  12265. if (isNaN(this.rotation.z)) {
  12266. this.rotation.z = 0;
  12267. }
  12268. };
  12269. TargetCamera.prototype.getTarget = function () {
  12270. return this._currentTarget;
  12271. };
  12272. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12273. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12274. };
  12275. TargetCamera.prototype._updatePosition = function () {
  12276. this.position.addInPlace(this.cameraDirection);
  12277. };
  12278. TargetCamera.prototype._checkInputs = function () {
  12279. var needToMove = this._decideIfNeedsToMove();
  12280. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12281. // Move
  12282. if (needToMove) {
  12283. this._updatePosition();
  12284. }
  12285. // Rotate
  12286. if (needToRotate) {
  12287. this.rotation.x += this.cameraRotation.x;
  12288. this.rotation.y += this.cameraRotation.y;
  12289. if (!this.noRotationConstraint) {
  12290. var limit = (Math.PI / 2) * 0.95;
  12291. if (this.rotation.x > limit)
  12292. this.rotation.x = limit;
  12293. if (this.rotation.x < -limit)
  12294. this.rotation.x = -limit;
  12295. }
  12296. }
  12297. // Inertia
  12298. if (needToMove) {
  12299. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12300. this.cameraDirection.x = 0;
  12301. }
  12302. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12303. this.cameraDirection.y = 0;
  12304. }
  12305. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12306. this.cameraDirection.z = 0;
  12307. }
  12308. this.cameraDirection.scaleInPlace(this.inertia);
  12309. }
  12310. if (needToRotate) {
  12311. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12312. this.cameraRotation.x = 0;
  12313. }
  12314. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12315. this.cameraRotation.y = 0;
  12316. }
  12317. this.cameraRotation.scaleInPlace(this.inertia);
  12318. }
  12319. _super.prototype._checkInputs.call(this);
  12320. };
  12321. TargetCamera.prototype._getViewMatrix = function () {
  12322. if (!this.lockedTarget) {
  12323. // Compute
  12324. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12325. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12326. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12327. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12328. this._lookAtTemp.invert();
  12329. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12330. }
  12331. else {
  12332. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12333. }
  12334. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12335. // Computing target and final matrix
  12336. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12337. }
  12338. else {
  12339. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12340. }
  12341. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12342. return this._viewMatrix;
  12343. };
  12344. TargetCamera.prototype._getVRViewMatrix = function () {
  12345. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12346. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12347. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12348. // Computing target and final matrix
  12349. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12350. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12351. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12352. return this._viewMatrix;
  12353. };
  12354. /**
  12355. * @override
  12356. * Override Camera.createRigCamera
  12357. */
  12358. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12359. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12360. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12361. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12362. rigCamera._cameraRigParams = {};
  12363. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12364. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12365. }
  12366. return rigCamera;
  12367. }
  12368. return null;
  12369. };
  12370. /**
  12371. * @override
  12372. * Override Camera._updateRigCameras
  12373. */
  12374. TargetCamera.prototype._updateRigCameras = function () {
  12375. switch (this.cameraRigMode) {
  12376. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12377. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12379. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12380. case BABYLON.Camera.RIG_MODE_VR:
  12381. var camLeft = this._rigCameras[0];
  12382. var camRight = this._rigCameras[1];
  12383. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12384. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12385. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12386. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12387. camLeft.position.copyFrom(this.position);
  12388. camRight.position.copyFrom(this.position);
  12389. }
  12390. else {
  12391. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12392. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12393. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12394. camLeft.setTarget(this.getTarget());
  12395. camRight.setTarget(this.getTarget());
  12396. }
  12397. break;
  12398. }
  12399. _super.prototype._updateRigCameras.call(this);
  12400. };
  12401. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12402. if (!this._rigCamTransformMatrix) {
  12403. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12404. }
  12405. var target = this.getTarget();
  12406. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12407. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12408. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12409. };
  12410. TargetCamera.prototype.getTypeName = function () {
  12411. return "TargetCamera";
  12412. };
  12413. __decorate([
  12414. BABYLON.serializeAsVector3()
  12415. ], TargetCamera.prototype, "rotation", void 0);
  12416. __decorate([
  12417. BABYLON.serialize()
  12418. ], TargetCamera.prototype, "speed", void 0);
  12419. __decorate([
  12420. BABYLON.serializeAsMeshReference("lockedTargetId")
  12421. ], TargetCamera.prototype, "lockedTarget", void 0);
  12422. return TargetCamera;
  12423. })(BABYLON.Camera);
  12424. BABYLON.TargetCamera = TargetCamera;
  12425. })(BABYLON || (BABYLON = {}));
  12426. var BABYLON;
  12427. (function (BABYLON) {
  12428. var FreeCamera = (function (_super) {
  12429. __extends(FreeCamera, _super);
  12430. function FreeCamera(name, position, scene) {
  12431. var _this = this;
  12432. _super.call(this, name, position, scene);
  12433. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12434. this.checkCollisions = false;
  12435. this.applyGravity = false;
  12436. this._collider = new BABYLON.Collider();
  12437. this._needMoveForGravity = false;
  12438. this._oldPosition = BABYLON.Vector3.Zero();
  12439. this._diffPosition = BABYLON.Vector3.Zero();
  12440. this._newPosition = BABYLON.Vector3.Zero();
  12441. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12442. if (collidedMesh === void 0) { collidedMesh = null; }
  12443. //TODO move this to the collision coordinator!
  12444. if (_this.getScene().workerCollisions)
  12445. newPosition.multiplyInPlace(_this._collider.radius);
  12446. var updatePosition = function (newPos) {
  12447. _this._newPosition.copyFrom(newPos);
  12448. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12449. var oldPosition = _this.position.clone();
  12450. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12451. _this.position.addInPlace(_this._diffPosition);
  12452. if (_this.onCollide && collidedMesh) {
  12453. _this.onCollide(collidedMesh);
  12454. }
  12455. }
  12456. };
  12457. updatePosition(newPosition);
  12458. };
  12459. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12460. this.inputs.addKeyboard().addMouse();
  12461. }
  12462. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12463. //-- begin properties for backward compatibility for inputs
  12464. get: function () {
  12465. var mouse = this.inputs.attached["mouse"];
  12466. if (mouse)
  12467. return mouse.angularSensibility;
  12468. },
  12469. set: function (value) {
  12470. var mouse = this.inputs.attached["mouse"];
  12471. if (mouse)
  12472. mouse.angularSensibility = value;
  12473. },
  12474. enumerable: true,
  12475. configurable: true
  12476. });
  12477. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12478. get: function () {
  12479. var keyboard = this.inputs.attached["keyboard"];
  12480. if (keyboard)
  12481. return keyboard.keysUp;
  12482. },
  12483. set: function (value) {
  12484. var keyboard = this.inputs.attached["keyboard"];
  12485. if (keyboard)
  12486. keyboard.keysUp = value;
  12487. },
  12488. enumerable: true,
  12489. configurable: true
  12490. });
  12491. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12492. get: function () {
  12493. var keyboard = this.inputs.attached["keyboard"];
  12494. if (keyboard)
  12495. return keyboard.keysDown;
  12496. },
  12497. set: function (value) {
  12498. var keyboard = this.inputs.attached["keyboard"];
  12499. if (keyboard)
  12500. keyboard.keysDown = value;
  12501. },
  12502. enumerable: true,
  12503. configurable: true
  12504. });
  12505. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12506. get: function () {
  12507. var keyboard = this.inputs.attached["keyboard"];
  12508. if (keyboard)
  12509. return keyboard.keysLeft;
  12510. },
  12511. set: function (value) {
  12512. var keyboard = this.inputs.attached["keyboard"];
  12513. if (keyboard)
  12514. keyboard.keysLeft = value;
  12515. },
  12516. enumerable: true,
  12517. configurable: true
  12518. });
  12519. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12520. get: function () {
  12521. var keyboard = this.inputs.attached["keyboard"];
  12522. if (keyboard)
  12523. return keyboard.keysRight;
  12524. },
  12525. set: function (value) {
  12526. var keyboard = this.inputs.attached["keyboard"];
  12527. if (keyboard)
  12528. keyboard.keysRight = value;
  12529. },
  12530. enumerable: true,
  12531. configurable: true
  12532. });
  12533. // Controls
  12534. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12535. if (this._attachedElement) {
  12536. return;
  12537. }
  12538. this._noPreventDefault = noPreventDefault;
  12539. this._attachedElement = element;
  12540. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12541. this.inputs.attachElement(element, noPreventDefault);
  12542. };
  12543. FreeCamera.prototype.detachControl = function (element) {
  12544. if (this._attachedElement !== element) {
  12545. return;
  12546. }
  12547. this.inputs.detachElement(this._attachedElement);
  12548. this._attachedElement = null;
  12549. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12550. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12551. };
  12552. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12553. var globalPosition;
  12554. if (this.parent) {
  12555. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12556. }
  12557. else {
  12558. globalPosition = this.position;
  12559. }
  12560. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12561. this._collider.radius = this.ellipsoid;
  12562. //no need for clone, as long as gravity is not on.
  12563. var actualVelocity = velocity;
  12564. //add gravity to the velocity to prevent the dual-collision checking
  12565. if (this.applyGravity) {
  12566. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12567. actualVelocity = velocity.add(this.getScene().gravity);
  12568. }
  12569. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12570. };
  12571. FreeCamera.prototype._checkInputs = function () {
  12572. if (!this._localDirection) {
  12573. this._localDirection = BABYLON.Vector3.Zero();
  12574. this._transformedDirection = BABYLON.Vector3.Zero();
  12575. }
  12576. this.inputs.checkInputs();
  12577. _super.prototype._checkInputs.call(this);
  12578. };
  12579. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12580. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12581. };
  12582. FreeCamera.prototype._updatePosition = function () {
  12583. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  12584. this._collideWithWorld(this.cameraDirection);
  12585. }
  12586. else {
  12587. this.position.addInPlace(this.cameraDirection);
  12588. }
  12589. };
  12590. FreeCamera.prototype.dispose = function () {
  12591. this.inputs.clear();
  12592. _super.prototype.dispose.call(this);
  12593. };
  12594. FreeCamera.prototype.getTypeName = function () {
  12595. return "FreeCamera";
  12596. };
  12597. __decorate([
  12598. BABYLON.serializeAsVector3()
  12599. ], FreeCamera.prototype, "ellipsoid", void 0);
  12600. __decorate([
  12601. BABYLON.serialize()
  12602. ], FreeCamera.prototype, "checkCollisions", void 0);
  12603. __decorate([
  12604. BABYLON.serialize()
  12605. ], FreeCamera.prototype, "applyGravity", void 0);
  12606. return FreeCamera;
  12607. })(BABYLON.TargetCamera);
  12608. BABYLON.FreeCamera = FreeCamera;
  12609. })(BABYLON || (BABYLON = {}));
  12610. var BABYLON;
  12611. (function (BABYLON) {
  12612. var FreeCameraInputsManager = (function (_super) {
  12613. __extends(FreeCameraInputsManager, _super);
  12614. function FreeCameraInputsManager(camera) {
  12615. _super.call(this, camera);
  12616. }
  12617. FreeCameraInputsManager.prototype.addKeyboard = function () {
  12618. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  12619. return this;
  12620. };
  12621. FreeCameraInputsManager.prototype.addMouse = function () {
  12622. this.add(new BABYLON.FreeCameraMouseInput());
  12623. return this;
  12624. };
  12625. FreeCameraInputsManager.prototype.addGamepad = function () {
  12626. this.add(new BABYLON.FreeCameraGamepadInput());
  12627. return this;
  12628. };
  12629. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  12630. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  12631. return this;
  12632. };
  12633. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  12634. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  12635. return this;
  12636. };
  12637. FreeCameraInputsManager.prototype.addTouch = function () {
  12638. this.add(new BABYLON.FreeCameraTouchInput());
  12639. return this;
  12640. };
  12641. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  12642. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  12643. return this;
  12644. };
  12645. return FreeCameraInputsManager;
  12646. })(BABYLON.CameraInputsManager);
  12647. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  12648. })(BABYLON || (BABYLON = {}));
  12649. var BABYLON;
  12650. (function (BABYLON) {
  12651. var FollowCamera = (function (_super) {
  12652. __extends(FollowCamera, _super);
  12653. function FollowCamera(name, position, scene, target) {
  12654. _super.call(this, name, position, scene);
  12655. this.radius = 12;
  12656. this.rotationOffset = 0;
  12657. this.heightOffset = 4;
  12658. this.cameraAcceleration = 0.05;
  12659. this.maxCameraSpeed = 20;
  12660. this.target = target;
  12661. }
  12662. FollowCamera.prototype.getRadians = function (degrees) {
  12663. return degrees * Math.PI / 180;
  12664. };
  12665. FollowCamera.prototype.follow = function (cameraTarget) {
  12666. if (!cameraTarget)
  12667. return;
  12668. var yRotation;
  12669. if (cameraTarget.rotationQuaternion) {
  12670. var rotMatrix = new BABYLON.Matrix();
  12671. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  12672. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  12673. }
  12674. else {
  12675. yRotation = cameraTarget.rotation.y;
  12676. }
  12677. var radians = this.getRadians(this.rotationOffset) + yRotation;
  12678. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  12679. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  12680. var dx = targetX - this.position.x;
  12681. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  12682. var dz = (targetZ) - this.position.z;
  12683. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  12684. var vy = dy * this.cameraAcceleration;
  12685. var vz = dz * this.cameraAcceleration * 2;
  12686. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  12687. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12688. }
  12689. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  12690. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12691. }
  12692. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  12693. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12694. }
  12695. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  12696. this.setTarget(cameraTarget.position);
  12697. };
  12698. FollowCamera.prototype._checkInputs = function () {
  12699. _super.prototype._checkInputs.call(this);
  12700. this.follow(this.target);
  12701. };
  12702. FollowCamera.prototype.getTypeName = function () {
  12703. return "FollowCamera";
  12704. };
  12705. __decorate([
  12706. BABYLON.serialize()
  12707. ], FollowCamera.prototype, "radius", void 0);
  12708. __decorate([
  12709. BABYLON.serialize()
  12710. ], FollowCamera.prototype, "rotationOffset", void 0);
  12711. __decorate([
  12712. BABYLON.serialize()
  12713. ], FollowCamera.prototype, "heightOffset", void 0);
  12714. __decorate([
  12715. BABYLON.serialize()
  12716. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  12717. __decorate([
  12718. BABYLON.serialize()
  12719. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  12720. __decorate([
  12721. BABYLON.serializeAsMeshReference("lockedTargetId")
  12722. ], FollowCamera.prototype, "target", void 0);
  12723. return FollowCamera;
  12724. })(BABYLON.TargetCamera);
  12725. BABYLON.FollowCamera = FollowCamera;
  12726. var ArcFollowCamera = (function (_super) {
  12727. __extends(ArcFollowCamera, _super);
  12728. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  12729. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12730. this.alpha = alpha;
  12731. this.beta = beta;
  12732. this.radius = radius;
  12733. this.target = target;
  12734. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  12735. this.follow();
  12736. }
  12737. ArcFollowCamera.prototype.follow = function () {
  12738. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  12739. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  12740. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  12741. this.position = this.target.position.add(this._cartesianCoordinates);
  12742. this.setTarget(this.target.position);
  12743. };
  12744. ArcFollowCamera.prototype._checkInputs = function () {
  12745. _super.prototype._checkInputs.call(this);
  12746. this.follow();
  12747. };
  12748. ArcFollowCamera.prototype.getTypeName = function () {
  12749. return "ArcFollowCamera";
  12750. };
  12751. return ArcFollowCamera;
  12752. })(BABYLON.TargetCamera);
  12753. BABYLON.ArcFollowCamera = ArcFollowCamera;
  12754. })(BABYLON || (BABYLON = {}));
  12755. var BABYLON;
  12756. (function (BABYLON) {
  12757. // We're mainly based on the logic defined into the FreeCamera code
  12758. var TouchCamera = (function (_super) {
  12759. __extends(TouchCamera, _super);
  12760. //-- end properties for backward compatibility for inputs
  12761. function TouchCamera(name, position, scene) {
  12762. _super.call(this, name, position, scene);
  12763. this.inputs.addTouch();
  12764. }
  12765. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  12766. //-- Begin properties for backward compatibility for inputs
  12767. get: function () {
  12768. var touch = this.inputs.attached["touch"];
  12769. if (touch)
  12770. return touch.touchAngularSensibility;
  12771. },
  12772. set: function (value) {
  12773. var touch = this.inputs.attached["touch"];
  12774. if (touch)
  12775. touch.touchAngularSensibility = value;
  12776. },
  12777. enumerable: true,
  12778. configurable: true
  12779. });
  12780. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  12781. get: function () {
  12782. var touch = this.inputs.attached["touch"];
  12783. if (touch)
  12784. return touch.touchMoveSensibility;
  12785. },
  12786. set: function (value) {
  12787. var touch = this.inputs.attached["touch"];
  12788. if (touch)
  12789. touch.touchMoveSensibility = value;
  12790. },
  12791. enumerable: true,
  12792. configurable: true
  12793. });
  12794. TouchCamera.prototype.getTypeName = function () {
  12795. return "TouchCamera";
  12796. };
  12797. return TouchCamera;
  12798. })(BABYLON.FreeCamera);
  12799. BABYLON.TouchCamera = TouchCamera;
  12800. })(BABYLON || (BABYLON = {}));
  12801. var BABYLON;
  12802. (function (BABYLON) {
  12803. var ArcRotateCamera = (function (_super) {
  12804. __extends(ArcRotateCamera, _super);
  12805. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  12806. var _this = this;
  12807. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12808. this.inertialAlphaOffset = 0;
  12809. this.inertialBetaOffset = 0;
  12810. this.inertialRadiusOffset = 0;
  12811. this.lowerAlphaLimit = null;
  12812. this.upperAlphaLimit = null;
  12813. this.lowerBetaLimit = 0.01;
  12814. this.upperBetaLimit = Math.PI;
  12815. this.lowerRadiusLimit = null;
  12816. this.upperRadiusLimit = null;
  12817. this.inertialPanningX = 0;
  12818. this.inertialPanningY = 0;
  12819. //-- end properties for backward compatibility for inputs
  12820. this.zoomOnFactor = 1;
  12821. this.targetScreenOffset = BABYLON.Vector2.Zero();
  12822. this.allowUpsideDown = true;
  12823. this._viewMatrix = new BABYLON.Matrix();
  12824. // Panning
  12825. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  12826. this.checkCollisions = false;
  12827. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12828. this._collider = new BABYLON.Collider();
  12829. this._previousPosition = BABYLON.Vector3.Zero();
  12830. this._collisionVelocity = BABYLON.Vector3.Zero();
  12831. this._newPosition = BABYLON.Vector3.Zero();
  12832. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12833. if (collidedMesh === void 0) { collidedMesh = null; }
  12834. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  12835. newPosition.multiplyInPlace(_this._collider.radius);
  12836. }
  12837. if (!collidedMesh) {
  12838. _this._previousPosition.copyFrom(_this.position);
  12839. }
  12840. else {
  12841. _this.setPosition(newPosition);
  12842. if (_this.onCollide) {
  12843. _this.onCollide(collidedMesh);
  12844. }
  12845. }
  12846. // Recompute because of constraints
  12847. var cosa = Math.cos(_this.alpha);
  12848. var sina = Math.sin(_this.alpha);
  12849. var cosb = Math.cos(_this.beta);
  12850. var sinb = Math.sin(_this.beta);
  12851. if (sinb === 0) {
  12852. sinb = 0.0001;
  12853. }
  12854. var target = _this._getTargetPosition();
  12855. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  12856. _this.position.copyFrom(_this._newPosition);
  12857. var up = _this.upVector;
  12858. if (_this.allowUpsideDown && _this.beta < 0) {
  12859. up = up.clone();
  12860. up = up.negate();
  12861. }
  12862. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  12863. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  12864. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  12865. _this._collisionTriggered = false;
  12866. };
  12867. if (!target) {
  12868. this.target = BABYLON.Vector3.Zero();
  12869. }
  12870. else {
  12871. this.target = target;
  12872. }
  12873. this.alpha = alpha;
  12874. this.beta = beta;
  12875. this.radius = radius;
  12876. this.getViewMatrix();
  12877. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  12878. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  12879. }
  12880. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  12881. //-- begin properties for backward compatibility for inputs
  12882. get: function () {
  12883. var pointers = this.inputs.attached["pointers"];
  12884. if (pointers)
  12885. return pointers.angularSensibilityX;
  12886. },
  12887. set: function (value) {
  12888. var pointers = this.inputs.attached["pointers"];
  12889. if (pointers) {
  12890. pointers.angularSensibilityX = value;
  12891. }
  12892. },
  12893. enumerable: true,
  12894. configurable: true
  12895. });
  12896. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  12897. get: function () {
  12898. var pointers = this.inputs.attached["pointers"];
  12899. if (pointers)
  12900. return pointers.angularSensibilityY;
  12901. },
  12902. set: function (value) {
  12903. var pointers = this.inputs.attached["pointers"];
  12904. if (pointers) {
  12905. pointers.angularSensibilityY = value;
  12906. }
  12907. },
  12908. enumerable: true,
  12909. configurable: true
  12910. });
  12911. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  12912. get: function () {
  12913. var pointers = this.inputs.attached["pointers"];
  12914. if (pointers)
  12915. return pointers.pinchPrecision;
  12916. },
  12917. set: function (value) {
  12918. var pointers = this.inputs.attached["pointers"];
  12919. if (pointers) {
  12920. pointers.pinchPrecision = value;
  12921. }
  12922. },
  12923. enumerable: true,
  12924. configurable: true
  12925. });
  12926. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  12927. get: function () {
  12928. var pointers = this.inputs.attached["pointers"];
  12929. if (pointers)
  12930. return pointers.panningSensibility;
  12931. },
  12932. set: function (value) {
  12933. var pointers = this.inputs.attached["pointers"];
  12934. if (pointers) {
  12935. pointers.panningSensibility = value;
  12936. }
  12937. },
  12938. enumerable: true,
  12939. configurable: true
  12940. });
  12941. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  12942. get: function () {
  12943. var keyboard = this.inputs.attached["keyboard"];
  12944. if (keyboard)
  12945. return keyboard.keysUp;
  12946. },
  12947. set: function (value) {
  12948. var keyboard = this.inputs.attached["keyboard"];
  12949. if (keyboard)
  12950. keyboard.keysUp = value;
  12951. },
  12952. enumerable: true,
  12953. configurable: true
  12954. });
  12955. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  12956. get: function () {
  12957. var keyboard = this.inputs.attached["keyboard"];
  12958. if (keyboard)
  12959. return keyboard.keysDown;
  12960. },
  12961. set: function (value) {
  12962. var keyboard = this.inputs.attached["keyboard"];
  12963. if (keyboard)
  12964. keyboard.keysDown = value;
  12965. },
  12966. enumerable: true,
  12967. configurable: true
  12968. });
  12969. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  12970. get: function () {
  12971. var keyboard = this.inputs.attached["keyboard"];
  12972. if (keyboard)
  12973. return keyboard.keysLeft;
  12974. },
  12975. set: function (value) {
  12976. var keyboard = this.inputs.attached["keyboard"];
  12977. if (keyboard)
  12978. keyboard.keysLeft = value;
  12979. },
  12980. enumerable: true,
  12981. configurable: true
  12982. });
  12983. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  12984. get: function () {
  12985. var keyboard = this.inputs.attached["keyboard"];
  12986. if (keyboard)
  12987. return keyboard.keysRight;
  12988. },
  12989. set: function (value) {
  12990. var keyboard = this.inputs.attached["keyboard"];
  12991. if (keyboard)
  12992. keyboard.keysRight = value;
  12993. },
  12994. enumerable: true,
  12995. configurable: true
  12996. });
  12997. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  12998. get: function () {
  12999. var mousewheel = this.inputs.attached["mousewheel"];
  13000. if (mousewheel)
  13001. return mousewheel.wheelPrecision;
  13002. },
  13003. set: function (value) {
  13004. var mousewheel = this.inputs.attached["mousewheel"];
  13005. if (mousewheel)
  13006. mousewheel.wheelPrecision = value;
  13007. },
  13008. enumerable: true,
  13009. configurable: true
  13010. });
  13011. // Cache
  13012. ArcRotateCamera.prototype._initCache = function () {
  13013. _super.prototype._initCache.call(this);
  13014. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13015. this._cache.alpha = undefined;
  13016. this._cache.beta = undefined;
  13017. this._cache.radius = undefined;
  13018. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13019. };
  13020. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13021. if (!ignoreParentClass) {
  13022. _super.prototype._updateCache.call(this);
  13023. }
  13024. this._cache.target.copyFrom(this._getTargetPosition());
  13025. this._cache.alpha = this.alpha;
  13026. this._cache.beta = this.beta;
  13027. this._cache.radius = this.radius;
  13028. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13029. };
  13030. ArcRotateCamera.prototype._getTargetPosition = function () {
  13031. if (this.target.getAbsolutePosition) {
  13032. return this.target.getAbsolutePosition();
  13033. }
  13034. return this.target;
  13035. };
  13036. // Synchronized
  13037. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13038. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13039. return false;
  13040. return this._cache.target.equals(this.target)
  13041. && this._cache.alpha === this.alpha
  13042. && this._cache.beta === this.beta
  13043. && this._cache.radius === this.radius
  13044. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13045. };
  13046. // Methods
  13047. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13048. var _this = this;
  13049. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13050. if (this._attachedElement) {
  13051. return;
  13052. }
  13053. this._attachedElement = element;
  13054. this._noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13055. this._useCtrlForPanning = useCtrlForPanning;
  13056. this.inputs.attachElement(element, noPreventDefault);
  13057. this._reset = function () {
  13058. _this.inertialAlphaOffset = 0;
  13059. _this.inertialBetaOffset = 0;
  13060. _this.inertialRadiusOffset = 0;
  13061. };
  13062. };
  13063. ArcRotateCamera.prototype.detachControl = function (element) {
  13064. if (this._attachedElement !== element) {
  13065. return;
  13066. }
  13067. this.inputs.detachElement(this._attachedElement);
  13068. this._attachedElement = null;
  13069. if (this._reset) {
  13070. this._reset();
  13071. }
  13072. };
  13073. ArcRotateCamera.prototype._checkInputs = function () {
  13074. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13075. if (this._collisionTriggered) {
  13076. return;
  13077. }
  13078. this.inputs.checkInputs();
  13079. // Inertia
  13080. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13081. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13082. this.beta += this.inertialBetaOffset;
  13083. this.radius -= this.inertialRadiusOffset;
  13084. this.inertialAlphaOffset *= this.inertia;
  13085. this.inertialBetaOffset *= this.inertia;
  13086. this.inertialRadiusOffset *= this.inertia;
  13087. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13088. this.inertialAlphaOffset = 0;
  13089. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13090. this.inertialBetaOffset = 0;
  13091. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13092. this.inertialRadiusOffset = 0;
  13093. }
  13094. // Panning inertia
  13095. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13096. if (!this._localDirection) {
  13097. this._localDirection = BABYLON.Vector3.Zero();
  13098. this._transformedDirection = BABYLON.Vector3.Zero();
  13099. }
  13100. this.inertialPanningX *= this.inertia;
  13101. this.inertialPanningY *= this.inertia;
  13102. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13103. this.inertialPanningX = 0;
  13104. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13105. this.inertialPanningY = 0;
  13106. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13107. this._localDirection.multiplyInPlace(this.panningAxis);
  13108. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13109. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13110. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13111. if (!this.panningAxis.y) {
  13112. this._transformedDirection.y = 0;
  13113. }
  13114. this.target.addInPlace(this._transformedDirection);
  13115. }
  13116. // Limits
  13117. this._checkLimits();
  13118. _super.prototype._checkInputs.call(this);
  13119. };
  13120. ArcRotateCamera.prototype._checkLimits = function () {
  13121. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13122. if (this.allowUpsideDown && this.beta > Math.PI) {
  13123. this.beta = this.beta - (2 * Math.PI);
  13124. }
  13125. }
  13126. else {
  13127. if (this.beta < this.lowerBetaLimit) {
  13128. this.beta = this.lowerBetaLimit;
  13129. }
  13130. }
  13131. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13132. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13133. this.beta = this.beta + (2 * Math.PI);
  13134. }
  13135. }
  13136. else {
  13137. if (this.beta > this.upperBetaLimit) {
  13138. this.beta = this.upperBetaLimit;
  13139. }
  13140. }
  13141. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13142. this.alpha = this.lowerAlphaLimit;
  13143. }
  13144. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13145. this.alpha = this.upperAlphaLimit;
  13146. }
  13147. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13148. this.radius = this.lowerRadiusLimit;
  13149. }
  13150. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13151. this.radius = this.upperRadiusLimit;
  13152. }
  13153. };
  13154. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13155. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13156. this.radius = radiusv3.length();
  13157. // Alpha
  13158. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13159. if (radiusv3.z < 0) {
  13160. this.alpha = 2 * Math.PI - this.alpha;
  13161. }
  13162. // Beta
  13163. this.beta = Math.acos(radiusv3.y / this.radius);
  13164. this._checkLimits();
  13165. };
  13166. ArcRotateCamera.prototype.setPosition = function (position) {
  13167. if (this.position.equals(position)) {
  13168. return;
  13169. }
  13170. this.position = position;
  13171. this.rebuildAnglesAndRadius();
  13172. };
  13173. ArcRotateCamera.prototype.setTarget = function (target) {
  13174. if (this._getTargetPosition().equals(target)) {
  13175. return;
  13176. }
  13177. this.target = target;
  13178. this.rebuildAnglesAndRadius();
  13179. };
  13180. ArcRotateCamera.prototype._getViewMatrix = function () {
  13181. // Compute
  13182. var cosa = Math.cos(this.alpha);
  13183. var sina = Math.sin(this.alpha);
  13184. var cosb = Math.cos(this.beta);
  13185. var sinb = Math.sin(this.beta);
  13186. if (sinb === 0) {
  13187. sinb = 0.0001;
  13188. }
  13189. var target = this._getTargetPosition();
  13190. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13191. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13192. this._collider.radius = this.collisionRadius;
  13193. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13194. this._collisionTriggered = true;
  13195. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13196. }
  13197. else {
  13198. this.position.copyFrom(this._newPosition);
  13199. var up = this.upVector;
  13200. if (this.allowUpsideDown && this.beta < 0) {
  13201. up = up.clone();
  13202. up = up.negate();
  13203. }
  13204. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13205. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13206. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13207. }
  13208. return this._viewMatrix;
  13209. };
  13210. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13211. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13212. meshes = meshes || this.getScene().meshes;
  13213. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13214. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13215. this.radius = distance * this.zoomOnFactor;
  13216. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13217. };
  13218. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13219. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13220. var meshesOrMinMaxVector;
  13221. var distance;
  13222. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13223. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13224. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13225. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13226. }
  13227. else {
  13228. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13229. distance = meshesOrMinMaxVectorAndDistance.distance;
  13230. }
  13231. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13232. if (!doNotUpdateMaxZ) {
  13233. this.maxZ = distance * 2;
  13234. }
  13235. };
  13236. /**
  13237. * @override
  13238. * Override Camera.createRigCamera
  13239. */
  13240. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13241. switch (this.cameraRigMode) {
  13242. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13243. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13245. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13246. case BABYLON.Camera.RIG_MODE_VR:
  13247. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13248. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13249. }
  13250. return null;
  13251. };
  13252. /**
  13253. * @override
  13254. * Override Camera._updateRigCameras
  13255. */
  13256. ArcRotateCamera.prototype._updateRigCameras = function () {
  13257. switch (this.cameraRigMode) {
  13258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13259. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13260. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13261. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13262. case BABYLON.Camera.RIG_MODE_VR:
  13263. var camLeft = this._rigCameras[0];
  13264. var camRight = this._rigCameras[1];
  13265. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13266. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13267. camLeft.beta = camRight.beta = this.beta;
  13268. camLeft.radius = camRight.radius = this.radius;
  13269. break;
  13270. }
  13271. _super.prototype._updateRigCameras.call(this);
  13272. };
  13273. ArcRotateCamera.prototype.dispose = function () {
  13274. this.inputs.clear();
  13275. _super.prototype.dispose.call(this);
  13276. };
  13277. ArcRotateCamera.prototype.getTypeName = function () {
  13278. return "ArcRotateCamera";
  13279. };
  13280. __decorate([
  13281. BABYLON.serialize()
  13282. ], ArcRotateCamera.prototype, "alpha", void 0);
  13283. __decorate([
  13284. BABYLON.serialize()
  13285. ], ArcRotateCamera.prototype, "beta", void 0);
  13286. __decorate([
  13287. BABYLON.serialize()
  13288. ], ArcRotateCamera.prototype, "radius", void 0);
  13289. __decorate([
  13290. BABYLON.serializeAsVector3()
  13291. ], ArcRotateCamera.prototype, "target", void 0);
  13292. __decorate([
  13293. BABYLON.serialize()
  13294. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13295. __decorate([
  13296. BABYLON.serialize()
  13297. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13298. __decorate([
  13299. BABYLON.serialize()
  13300. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13301. __decorate([
  13302. BABYLON.serialize()
  13303. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13304. __decorate([
  13305. BABYLON.serialize()
  13306. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13307. __decorate([
  13308. BABYLON.serialize()
  13309. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13310. __decorate([
  13311. BABYLON.serialize()
  13312. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13313. __decorate([
  13314. BABYLON.serialize()
  13315. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13316. __decorate([
  13317. BABYLON.serialize()
  13318. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13319. __decorate([
  13320. BABYLON.serialize()
  13321. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13322. __decorate([
  13323. BABYLON.serialize()
  13324. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13325. __decorate([
  13326. BABYLON.serialize()
  13327. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13328. __decorate([
  13329. BABYLON.serialize()
  13330. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13331. return ArcRotateCamera;
  13332. })(BABYLON.TargetCamera);
  13333. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13334. })(BABYLON || (BABYLON = {}));
  13335. var BABYLON;
  13336. (function (BABYLON) {
  13337. var ArcRotateCameraInputsManager = (function (_super) {
  13338. __extends(ArcRotateCameraInputsManager, _super);
  13339. function ArcRotateCameraInputsManager(camera) {
  13340. _super.call(this, camera);
  13341. }
  13342. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13343. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13344. return this;
  13345. };
  13346. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13347. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13348. return this;
  13349. };
  13350. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13351. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13352. return this;
  13353. };
  13354. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13355. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13356. return this;
  13357. };
  13358. return ArcRotateCameraInputsManager;
  13359. })(BABYLON.CameraInputsManager);
  13360. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13361. })(BABYLON || (BABYLON = {}));
  13362. var BABYLON;
  13363. (function (BABYLON) {
  13364. var RenderingManager = (function () {
  13365. function RenderingManager(scene) {
  13366. this._renderingGroups = new Array();
  13367. this._scene = scene;
  13368. }
  13369. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13370. if (this._scene._activeParticleSystems.length === 0) {
  13371. return;
  13372. }
  13373. // Particles
  13374. var activeCamera = this._scene.activeCamera;
  13375. var beforeParticlesDate = BABYLON.Tools.Now;
  13376. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13377. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13378. if (particleSystem.renderingGroupId !== index) {
  13379. continue;
  13380. }
  13381. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13382. continue;
  13383. }
  13384. this._clearDepthBuffer();
  13385. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13386. this._scene._activeParticles += particleSystem.render();
  13387. }
  13388. }
  13389. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13390. };
  13391. RenderingManager.prototype._renderSprites = function (index) {
  13392. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13393. return;
  13394. }
  13395. // Sprites
  13396. var activeCamera = this._scene.activeCamera;
  13397. var beforeSpritessDate = BABYLON.Tools.Now;
  13398. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13399. var spriteManager = this._scene.spriteManagers[id];
  13400. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13401. this._clearDepthBuffer();
  13402. spriteManager.render();
  13403. }
  13404. }
  13405. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13406. };
  13407. RenderingManager.prototype._clearDepthBuffer = function () {
  13408. if (this._depthBufferAlreadyCleaned) {
  13409. return;
  13410. }
  13411. this._scene.getEngine().clear(0, false, true);
  13412. this._depthBufferAlreadyCleaned = true;
  13413. };
  13414. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13415. if (this._currentRenderSprites) {
  13416. this._renderSprites(this._currentIndex);
  13417. }
  13418. if (this._currentRenderParticles) {
  13419. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13420. }
  13421. };
  13422. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13423. this._currentActiveMeshes = activeMeshes;
  13424. this._currentRenderParticles = renderParticles;
  13425. this._currentRenderSprites = renderSprites;
  13426. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13427. this._depthBufferAlreadyCleaned = index == 0;
  13428. var renderingGroup = this._renderingGroups[index];
  13429. var needToStepBack = false;
  13430. this._currentIndex = index;
  13431. if (renderingGroup) {
  13432. this._clearDepthBuffer();
  13433. if (!renderingGroup.onBeforeTransparentRendering) {
  13434. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13435. }
  13436. if (!renderingGroup.render(customRenderFunction)) {
  13437. this._renderingGroups.splice(index, 1);
  13438. needToStepBack = true;
  13439. this._renderSpritesAndParticles();
  13440. }
  13441. }
  13442. else {
  13443. this._renderSpritesAndParticles();
  13444. }
  13445. if (needToStepBack) {
  13446. index--;
  13447. }
  13448. }
  13449. };
  13450. RenderingManager.prototype.reset = function () {
  13451. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13452. if (renderingGroup) {
  13453. renderingGroup.prepare();
  13454. }
  13455. });
  13456. };
  13457. RenderingManager.prototype.dispatch = function (subMesh) {
  13458. var mesh = subMesh.getMesh();
  13459. var renderingGroupId = mesh.renderingGroupId || 0;
  13460. if (!this._renderingGroups[renderingGroupId]) {
  13461. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13462. }
  13463. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13464. };
  13465. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13466. return RenderingManager;
  13467. })();
  13468. BABYLON.RenderingManager = RenderingManager;
  13469. })(BABYLON || (BABYLON = {}));
  13470. var BABYLON;
  13471. (function (BABYLON) {
  13472. var RenderingGroup = (function () {
  13473. function RenderingGroup(index, scene) {
  13474. this.index = index;
  13475. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13476. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13477. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13478. this._scene = scene;
  13479. }
  13480. RenderingGroup.prototype.render = function (customRenderFunction) {
  13481. if (customRenderFunction) {
  13482. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13483. return true;
  13484. }
  13485. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13486. if (this.onBeforeTransparentRendering) {
  13487. this.onBeforeTransparentRendering();
  13488. }
  13489. return false;
  13490. }
  13491. var engine = this._scene.getEngine();
  13492. // Opaque
  13493. var subIndex;
  13494. var submesh;
  13495. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13496. submesh = this._opaqueSubMeshes.data[subIndex];
  13497. submesh.render(false);
  13498. }
  13499. // Alpha test
  13500. engine.setAlphaTesting(true);
  13501. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13502. submesh = this._alphaTestSubMeshes.data[subIndex];
  13503. submesh.render(false);
  13504. }
  13505. engine.setAlphaTesting(false);
  13506. if (this.onBeforeTransparentRendering) {
  13507. this.onBeforeTransparentRendering();
  13508. }
  13509. // Transparent
  13510. if (this._transparentSubMeshes.length) {
  13511. // Sorting
  13512. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13513. submesh = this._transparentSubMeshes.data[subIndex];
  13514. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13515. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13516. }
  13517. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13518. sortedArray.sort(function (a, b) {
  13519. // Alpha index first
  13520. if (a._alphaIndex > b._alphaIndex) {
  13521. return 1;
  13522. }
  13523. if (a._alphaIndex < b._alphaIndex) {
  13524. return -1;
  13525. }
  13526. // Then distance to camera
  13527. if (a._distanceToCamera < b._distanceToCamera) {
  13528. return 1;
  13529. }
  13530. if (a._distanceToCamera > b._distanceToCamera) {
  13531. return -1;
  13532. }
  13533. return 0;
  13534. });
  13535. // Rendering
  13536. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13537. submesh = sortedArray[subIndex];
  13538. submesh.render(true);
  13539. }
  13540. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13541. }
  13542. return true;
  13543. };
  13544. RenderingGroup.prototype.prepare = function () {
  13545. this._opaqueSubMeshes.reset();
  13546. this._transparentSubMeshes.reset();
  13547. this._alphaTestSubMeshes.reset();
  13548. };
  13549. RenderingGroup.prototype.dispatch = function (subMesh) {
  13550. var material = subMesh.getMaterial();
  13551. var mesh = subMesh.getMesh();
  13552. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13553. this._transparentSubMeshes.push(subMesh);
  13554. }
  13555. else if (material.needAlphaTesting()) {
  13556. this._alphaTestSubMeshes.push(subMesh);
  13557. }
  13558. else {
  13559. this._opaqueSubMeshes.push(subMesh); // Opaque
  13560. }
  13561. };
  13562. return RenderingGroup;
  13563. })();
  13564. BABYLON.RenderingGroup = RenderingGroup;
  13565. })(BABYLON || (BABYLON = {}));
  13566. var BABYLON;
  13567. (function (BABYLON) {
  13568. /**
  13569. * Represents a scene to be rendered by the engine.
  13570. * @see http://doc.babylonjs.com/page.php?p=21911
  13571. */
  13572. var Scene = (function () {
  13573. /**
  13574. * @constructor
  13575. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  13576. */
  13577. function Scene(engine) {
  13578. // Members
  13579. this.autoClear = true;
  13580. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13581. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13582. this.forceWireframe = false;
  13583. this.forcePointsCloud = false;
  13584. this.forceShowBoundingBoxes = false;
  13585. this.animationsEnabled = true;
  13586. this.constantlyUpdateMeshUnderPointer = false;
  13587. // Animations
  13588. this.animations = [];
  13589. 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
  13590. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  13591. this._startingPointerTime = 0;
  13592. // Fog
  13593. /**
  13594. * is fog enabled on this scene.
  13595. * @type {boolean}
  13596. */
  13597. this.fogEnabled = true;
  13598. this.fogMode = Scene.FOGMODE_NONE;
  13599. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13600. this.fogDensity = 0.1;
  13601. this.fogStart = 0;
  13602. this.fogEnd = 1000.0;
  13603. // Lights
  13604. /**
  13605. * is shadow enabled on this scene.
  13606. * @type {boolean}
  13607. */
  13608. this.shadowsEnabled = true;
  13609. /**
  13610. * is light enabled on this scene.
  13611. * @type {boolean}
  13612. */
  13613. this.lightsEnabled = true;
  13614. /**
  13615. * All of the lights added to this scene.
  13616. * @see BABYLON.Light
  13617. * @type {BABYLON.Light[]}
  13618. */
  13619. this.lights = new Array();
  13620. // Cameras
  13621. /**
  13622. * All of the cameras added to this scene.
  13623. * @see BABYLON.Camera
  13624. * @type {BABYLON.Camera[]}
  13625. */
  13626. this.cameras = new Array();
  13627. this.activeCameras = new Array();
  13628. // Meshes
  13629. /**
  13630. * All of the (abstract) meshes added to this scene.
  13631. * @see BABYLON.AbstractMesh
  13632. * @type {BABYLON.AbstractMesh[]}
  13633. */
  13634. this.meshes = new Array();
  13635. // Geometries
  13636. this._geometries = new Array();
  13637. this.materials = new Array();
  13638. this.multiMaterials = new Array();
  13639. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  13640. // Textures
  13641. this.texturesEnabled = true;
  13642. this.textures = new Array();
  13643. // Particles
  13644. this.particlesEnabled = true;
  13645. this.particleSystems = new Array();
  13646. // Sprites
  13647. this.spritesEnabled = true;
  13648. this.spriteManagers = new Array();
  13649. // Layers
  13650. this.layers = new Array();
  13651. // Skeletons
  13652. this.skeletonsEnabled = true;
  13653. this.skeletons = new Array();
  13654. // Lens flares
  13655. this.lensFlaresEnabled = true;
  13656. this.lensFlareSystems = new Array();
  13657. // Collisions
  13658. this.collisionsEnabled = true;
  13659. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  13660. // Postprocesses
  13661. this.postProcessesEnabled = true;
  13662. // Customs render targets
  13663. this.renderTargetsEnabled = true;
  13664. this.dumpNextRenderTargets = false;
  13665. this.customRenderTargets = new Array();
  13666. // Imported meshes
  13667. this.importedMeshesFiles = new Array();
  13668. // Probes
  13669. this.probesEnabled = true;
  13670. this.reflectionProbes = new Array();
  13671. this._actionManagers = new Array();
  13672. this._meshesForIntersections = new BABYLON.SmartArray(256);
  13673. // Procedural textures
  13674. this.proceduralTexturesEnabled = true;
  13675. this._proceduralTextures = new Array();
  13676. this.soundTracks = new Array();
  13677. this._audioEnabled = true;
  13678. this._headphone = false;
  13679. this._totalVertices = 0;
  13680. this._activeIndices = 0;
  13681. this._activeParticles = 0;
  13682. this._lastFrameDuration = 0;
  13683. this._evaluateActiveMeshesDuration = 0;
  13684. this._renderTargetsDuration = 0;
  13685. this._particlesDuration = 0;
  13686. this._renderDuration = 0;
  13687. this._spritesDuration = 0;
  13688. this._animationRatio = 0;
  13689. this._renderId = 0;
  13690. this._executeWhenReadyTimeoutId = -1;
  13691. this._toBeDisposed = new BABYLON.SmartArray(256);
  13692. this._onReadyCallbacks = new Array();
  13693. this._pendingData = []; //ANY
  13694. this._onBeforeRenderCallbacks = new Array();
  13695. this._onAfterRenderCallbacks = new Array();
  13696. this._activeMeshes = new BABYLON.SmartArray(256);
  13697. this._processedMaterials = new BABYLON.SmartArray(256);
  13698. this._renderTargets = new BABYLON.SmartArray(256);
  13699. this._activeParticleSystems = new BABYLON.SmartArray(256);
  13700. this._activeSkeletons = new BABYLON.SmartArray(32);
  13701. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  13702. this._activeBones = 0;
  13703. this._activeAnimatables = new Array();
  13704. this._transformMatrix = BABYLON.Matrix.Zero();
  13705. this._edgesRenderers = new BABYLON.SmartArray(16);
  13706. this._uniqueIdCounter = 0;
  13707. this._engine = engine;
  13708. engine.scenes.push(this);
  13709. this._renderingManager = new BABYLON.RenderingManager(this);
  13710. this.postProcessManager = new BABYLON.PostProcessManager(this);
  13711. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  13712. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  13713. if (BABYLON.OutlineRenderer) {
  13714. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  13715. }
  13716. this.attachControl();
  13717. this._debugLayer = new BABYLON.DebugLayer(this);
  13718. if (BABYLON.SoundTrack) {
  13719. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  13720. }
  13721. //simplification queue
  13722. if (BABYLON.SimplificationQueue) {
  13723. this.simplificationQueue = new BABYLON.SimplificationQueue();
  13724. }
  13725. //collision coordinator initialization. For now legacy per default.
  13726. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  13727. }
  13728. Object.defineProperty(Scene, "FOGMODE_NONE", {
  13729. get: function () {
  13730. return Scene._FOGMODE_NONE;
  13731. },
  13732. enumerable: true,
  13733. configurable: true
  13734. });
  13735. Object.defineProperty(Scene, "FOGMODE_EXP", {
  13736. get: function () {
  13737. return Scene._FOGMODE_EXP;
  13738. },
  13739. enumerable: true,
  13740. configurable: true
  13741. });
  13742. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  13743. get: function () {
  13744. return Scene._FOGMODE_EXP2;
  13745. },
  13746. enumerable: true,
  13747. configurable: true
  13748. });
  13749. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  13750. get: function () {
  13751. return Scene._FOGMODE_LINEAR;
  13752. },
  13753. enumerable: true,
  13754. configurable: true
  13755. });
  13756. Object.defineProperty(Scene.prototype, "debugLayer", {
  13757. // Properties
  13758. get: function () {
  13759. return this._debugLayer;
  13760. },
  13761. enumerable: true,
  13762. configurable: true
  13763. });
  13764. Object.defineProperty(Scene.prototype, "workerCollisions", {
  13765. get: function () {
  13766. return this._workerCollisions;
  13767. },
  13768. set: function (enabled) {
  13769. enabled = (enabled && !!Worker);
  13770. this._workerCollisions = enabled;
  13771. if (this.collisionCoordinator) {
  13772. this.collisionCoordinator.destroy();
  13773. }
  13774. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  13775. this.collisionCoordinator.init(this);
  13776. },
  13777. enumerable: true,
  13778. configurable: true
  13779. });
  13780. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  13781. get: function () {
  13782. return this._selectionOctree;
  13783. },
  13784. enumerable: true,
  13785. configurable: true
  13786. });
  13787. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  13788. /**
  13789. * The mesh that is currently under the pointer.
  13790. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  13791. */
  13792. get: function () {
  13793. return this._pointerOverMesh;
  13794. },
  13795. enumerable: true,
  13796. configurable: true
  13797. });
  13798. Object.defineProperty(Scene.prototype, "pointerX", {
  13799. /**
  13800. * Current on-screen X position of the pointer
  13801. * @return {number} X position of the pointer
  13802. */
  13803. get: function () {
  13804. return this._pointerX;
  13805. },
  13806. enumerable: true,
  13807. configurable: true
  13808. });
  13809. Object.defineProperty(Scene.prototype, "pointerY", {
  13810. /**
  13811. * Current on-screen Y position of the pointer
  13812. * @return {number} Y position of the pointer
  13813. */
  13814. get: function () {
  13815. return this._pointerY;
  13816. },
  13817. enumerable: true,
  13818. configurable: true
  13819. });
  13820. Scene.prototype.getCachedMaterial = function () {
  13821. return this._cachedMaterial;
  13822. };
  13823. Scene.prototype.getBoundingBoxRenderer = function () {
  13824. return this._boundingBoxRenderer;
  13825. };
  13826. Scene.prototype.getOutlineRenderer = function () {
  13827. return this._outlineRenderer;
  13828. };
  13829. Scene.prototype.getEngine = function () {
  13830. return this._engine;
  13831. };
  13832. Scene.prototype.getTotalVertices = function () {
  13833. return this._totalVertices;
  13834. };
  13835. Scene.prototype.getActiveIndices = function () {
  13836. return this._activeIndices;
  13837. };
  13838. Scene.prototype.getActiveParticles = function () {
  13839. return this._activeParticles;
  13840. };
  13841. Scene.prototype.getActiveBones = function () {
  13842. return this._activeBones;
  13843. };
  13844. // Stats
  13845. Scene.prototype.getLastFrameDuration = function () {
  13846. return this._lastFrameDuration;
  13847. };
  13848. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  13849. return this._evaluateActiveMeshesDuration;
  13850. };
  13851. Scene.prototype.getActiveMeshes = function () {
  13852. return this._activeMeshes;
  13853. };
  13854. Scene.prototype.getRenderTargetsDuration = function () {
  13855. return this._renderTargetsDuration;
  13856. };
  13857. Scene.prototype.getRenderDuration = function () {
  13858. return this._renderDuration;
  13859. };
  13860. Scene.prototype.getParticlesDuration = function () {
  13861. return this._particlesDuration;
  13862. };
  13863. Scene.prototype.getSpritesDuration = function () {
  13864. return this._spritesDuration;
  13865. };
  13866. Scene.prototype.getAnimationRatio = function () {
  13867. return this._animationRatio;
  13868. };
  13869. Scene.prototype.getRenderId = function () {
  13870. return this._renderId;
  13871. };
  13872. Scene.prototype.incrementRenderId = function () {
  13873. this._renderId++;
  13874. };
  13875. Scene.prototype._updatePointerPosition = function (evt) {
  13876. var canvasRect = this._engine.getRenderingCanvasClientRect();
  13877. this._pointerX = evt.clientX - canvasRect.left;
  13878. this._pointerY = evt.clientY - canvasRect.top;
  13879. this._unTranslatedPointerX = this._pointerX;
  13880. this._unTranslatedPointerY = this._pointerY;
  13881. if (this.cameraToUseForPointers) {
  13882. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  13883. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  13884. }
  13885. };
  13886. // Pointers handling
  13887. Scene.prototype.attachControl = function () {
  13888. var _this = this;
  13889. var spritePredicate = function (sprite) {
  13890. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  13891. };
  13892. this._onPointerMove = function (evt) {
  13893. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13894. return;
  13895. }
  13896. var canvas = _this._engine.getRenderingCanvas();
  13897. _this._updatePointerPosition(evt);
  13898. if (!_this.pointerMovePredicate) {
  13899. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  13900. }
  13901. // Meshes
  13902. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  13903. if (pickResult.hit && pickResult.pickedMesh) {
  13904. _this.setPointerOverSprite(null);
  13905. _this.setPointerOverMesh(pickResult.pickedMesh);
  13906. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  13907. canvas.style.cursor = "pointer";
  13908. }
  13909. else {
  13910. canvas.style.cursor = "";
  13911. }
  13912. }
  13913. else {
  13914. _this.setPointerOverMesh(null);
  13915. // Sprites
  13916. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13917. if (pickResult.hit && pickResult.pickedSprite) {
  13918. canvas.style.cursor = "pointer";
  13919. _this.setPointerOverSprite(pickResult.pickedSprite);
  13920. }
  13921. else {
  13922. _this.setPointerOverSprite(null);
  13923. // Restore pointer
  13924. canvas.style.cursor = "";
  13925. }
  13926. }
  13927. if (_this.onPointerMove) {
  13928. _this.onPointerMove(evt, pickResult);
  13929. }
  13930. };
  13931. this._onPointerDown = function (evt) {
  13932. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13933. return;
  13934. }
  13935. _this._updatePointerPosition(evt);
  13936. _this._startingPointerPosition.x = _this._pointerX;
  13937. _this._startingPointerPosition.y = _this._pointerY;
  13938. _this._startingPointerTime = new Date().getTime();
  13939. if (!_this.pointerDownPredicate) {
  13940. _this.pointerDownPredicate = function (mesh) {
  13941. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  13942. };
  13943. }
  13944. // Meshes
  13945. _this._pickedDownMesh = null;
  13946. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  13947. if (pickResult.hit && pickResult.pickedMesh) {
  13948. if (pickResult.pickedMesh.actionManager) {
  13949. _this._pickedDownMesh = pickResult.pickedMesh;
  13950. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  13951. switch (evt.button) {
  13952. case 0:
  13953. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13954. break;
  13955. case 1:
  13956. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13957. break;
  13958. case 2:
  13959. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13960. break;
  13961. }
  13962. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13963. }
  13964. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  13965. var that = _this;
  13966. window.setTimeout(function () {
  13967. 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);
  13968. if (pickResult.hit && pickResult.pickedMesh) {
  13969. if (pickResult.pickedMesh.actionManager) {
  13970. 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)) {
  13971. that._startingPointerTime = 0;
  13972. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13973. }
  13974. }
  13975. }
  13976. }, BABYLON.ActionManager.LongPressDelay);
  13977. }
  13978. }
  13979. }
  13980. if (_this.onPointerDown) {
  13981. _this.onPointerDown(evt, pickResult);
  13982. }
  13983. // Sprites
  13984. _this._pickedDownSprite = null;
  13985. if (_this.spriteManagers.length > 0) {
  13986. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13987. if (pickResult.hit && pickResult.pickedSprite) {
  13988. if (pickResult.pickedSprite.actionManager) {
  13989. _this._pickedDownSprite = pickResult.pickedSprite;
  13990. switch (evt.button) {
  13991. case 0:
  13992. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13993. break;
  13994. case 1:
  13995. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13996. break;
  13997. case 2:
  13998. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13999. break;
  14000. }
  14001. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14002. }
  14003. }
  14004. }
  14005. };
  14006. this._onPointerUp = function (evt) {
  14007. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14008. return;
  14009. }
  14010. _this._updatePointerPosition(evt);
  14011. if (!_this.pointerUpPredicate) {
  14012. _this.pointerUpPredicate = function (mesh) {
  14013. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14014. };
  14015. }
  14016. // Meshes
  14017. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14018. if (pickResult.hit && pickResult.pickedMesh) {
  14019. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14020. _this.onPointerPick(evt, pickResult);
  14021. }
  14022. if (pickResult.pickedMesh.actionManager) {
  14023. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14024. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14025. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14026. }
  14027. }
  14028. }
  14029. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14030. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14031. }
  14032. if (_this.onPointerUp) {
  14033. _this.onPointerUp(evt, pickResult);
  14034. }
  14035. _this._startingPointerTime = 0;
  14036. // Sprites
  14037. if (_this.spriteManagers.length > 0) {
  14038. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14039. if (pickResult.hit && pickResult.pickedSprite) {
  14040. if (pickResult.pickedSprite.actionManager) {
  14041. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14042. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14043. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14044. }
  14045. }
  14046. }
  14047. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14048. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14049. }
  14050. }
  14051. };
  14052. this._onKeyDown = function (evt) {
  14053. if (_this.actionManager) {
  14054. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14055. }
  14056. };
  14057. this._onKeyUp = function (evt) {
  14058. if (_this.actionManager) {
  14059. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14060. }
  14061. };
  14062. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14063. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14064. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14065. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14066. // Wheel
  14067. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14068. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14069. BABYLON.Tools.RegisterTopRootEvents([
  14070. { name: "keydown", handler: this._onKeyDown },
  14071. { name: "keyup", handler: this._onKeyUp }
  14072. ]);
  14073. };
  14074. Scene.prototype.detachControl = function () {
  14075. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14076. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14077. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14078. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14079. // Wheel
  14080. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14081. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14082. BABYLON.Tools.UnregisterTopRootEvents([
  14083. { name: "keydown", handler: this._onKeyDown },
  14084. { name: "keyup", handler: this._onKeyUp }
  14085. ]);
  14086. };
  14087. // Ready
  14088. Scene.prototype.isReady = function () {
  14089. if (this._pendingData.length > 0) {
  14090. return false;
  14091. }
  14092. var index;
  14093. for (index = 0; index < this._geometries.length; index++) {
  14094. var geometry = this._geometries[index];
  14095. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14096. return false;
  14097. }
  14098. }
  14099. for (index = 0; index < this.meshes.length; index++) {
  14100. var mesh = this.meshes[index];
  14101. if (!mesh.isReady()) {
  14102. return false;
  14103. }
  14104. var mat = mesh.material;
  14105. if (mat) {
  14106. if (!mat.isReady(mesh)) {
  14107. return false;
  14108. }
  14109. }
  14110. }
  14111. return true;
  14112. };
  14113. Scene.prototype.resetCachedMaterial = function () {
  14114. this._cachedMaterial = null;
  14115. };
  14116. Scene.prototype.registerBeforeRender = function (func) {
  14117. this._onBeforeRenderCallbacks.push(func);
  14118. };
  14119. Scene.prototype.unregisterBeforeRender = function (func) {
  14120. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14121. if (index > -1) {
  14122. this._onBeforeRenderCallbacks.splice(index, 1);
  14123. }
  14124. };
  14125. Scene.prototype.registerAfterRender = function (func) {
  14126. this._onAfterRenderCallbacks.push(func);
  14127. };
  14128. Scene.prototype.unregisterAfterRender = function (func) {
  14129. var index = this._onAfterRenderCallbacks.indexOf(func);
  14130. if (index > -1) {
  14131. this._onAfterRenderCallbacks.splice(index, 1);
  14132. }
  14133. };
  14134. Scene.prototype._addPendingData = function (data) {
  14135. this._pendingData.push(data);
  14136. };
  14137. Scene.prototype._removePendingData = function (data) {
  14138. var index = this._pendingData.indexOf(data);
  14139. if (index !== -1) {
  14140. this._pendingData.splice(index, 1);
  14141. }
  14142. };
  14143. Scene.prototype.getWaitingItemsCount = function () {
  14144. return this._pendingData.length;
  14145. };
  14146. /**
  14147. * Registers a function to be executed when the scene is ready.
  14148. * @param {Function} func - the function to be executed.
  14149. */
  14150. Scene.prototype.executeWhenReady = function (func) {
  14151. var _this = this;
  14152. this._onReadyCallbacks.push(func);
  14153. if (this._executeWhenReadyTimeoutId !== -1) {
  14154. return;
  14155. }
  14156. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14157. _this._checkIsReady();
  14158. }, 150);
  14159. };
  14160. Scene.prototype._checkIsReady = function () {
  14161. var _this = this;
  14162. if (this.isReady()) {
  14163. this._onReadyCallbacks.forEach(function (func) {
  14164. func();
  14165. });
  14166. this._onReadyCallbacks = [];
  14167. this._executeWhenReadyTimeoutId = -1;
  14168. return;
  14169. }
  14170. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14171. _this._checkIsReady();
  14172. }, 150);
  14173. };
  14174. // Animations
  14175. /**
  14176. * Will start the animation sequence of a given target
  14177. * @param target - the target
  14178. * @param {number} from - from which frame should animation start
  14179. * @param {number} to - till which frame should animation run.
  14180. * @param {boolean} [loop] - should the animation loop
  14181. * @param {number} [speedRatio] - the speed in which to run the animation
  14182. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14183. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14184. * @return {BABYLON.Animatable} the animatable object created for this animation
  14185. * @see BABYLON.Animatable
  14186. * @see http://doc.babylonjs.com/page.php?p=22081
  14187. */
  14188. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14189. if (speedRatio === void 0) { speedRatio = 1.0; }
  14190. this.stopAnimation(target);
  14191. if (!animatable) {
  14192. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14193. }
  14194. // Local animations
  14195. if (target.animations) {
  14196. animatable.appendAnimations(target, target.animations);
  14197. }
  14198. // Children animations
  14199. if (target.getAnimatables) {
  14200. var animatables = target.getAnimatables();
  14201. for (var index = 0; index < animatables.length; index++) {
  14202. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14203. }
  14204. }
  14205. animatable.reset();
  14206. return animatable;
  14207. };
  14208. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14209. if (speedRatio === undefined) {
  14210. speedRatio = 1.0;
  14211. }
  14212. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14213. return animatable;
  14214. };
  14215. Scene.prototype.getAnimatableByTarget = function (target) {
  14216. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14217. if (this._activeAnimatables[index].target === target) {
  14218. return this._activeAnimatables[index];
  14219. }
  14220. }
  14221. return null;
  14222. };
  14223. Object.defineProperty(Scene.prototype, "Animatables", {
  14224. get: function () {
  14225. return this._activeAnimatables;
  14226. },
  14227. enumerable: true,
  14228. configurable: true
  14229. });
  14230. /**
  14231. * Will stop the animation of the given target
  14232. * @param target - the target
  14233. * @see beginAnimation
  14234. */
  14235. Scene.prototype.stopAnimation = function (target) {
  14236. var animatable = this.getAnimatableByTarget(target);
  14237. if (animatable) {
  14238. animatable.stop();
  14239. }
  14240. };
  14241. Scene.prototype._animate = function () {
  14242. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14243. return;
  14244. }
  14245. if (!this._animationStartDate) {
  14246. if (this._pendingData.length > 0) {
  14247. return;
  14248. }
  14249. this._animationStartDate = BABYLON.Tools.Now;
  14250. }
  14251. // Getting time
  14252. var now = BABYLON.Tools.Now;
  14253. var delay = now - this._animationStartDate;
  14254. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14255. this._activeAnimatables[index]._animate(delay);
  14256. }
  14257. };
  14258. // Matrix
  14259. Scene.prototype.getViewMatrix = function () {
  14260. return this._viewMatrix;
  14261. };
  14262. Scene.prototype.getProjectionMatrix = function () {
  14263. return this._projectionMatrix;
  14264. };
  14265. Scene.prototype.getTransformMatrix = function () {
  14266. return this._transformMatrix;
  14267. };
  14268. Scene.prototype.setTransformMatrix = function (view, projection) {
  14269. this._viewMatrix = view;
  14270. this._projectionMatrix = projection;
  14271. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14272. };
  14273. // Methods
  14274. Scene.prototype.addMesh = function (newMesh) {
  14275. newMesh.uniqueId = this._uniqueIdCounter++;
  14276. var position = this.meshes.push(newMesh);
  14277. //notify the collision coordinator
  14278. this.collisionCoordinator.onMeshAdded(newMesh);
  14279. if (this.onNewMeshAdded) {
  14280. this.onNewMeshAdded(newMesh, position, this);
  14281. }
  14282. };
  14283. Scene.prototype.removeMesh = function (toRemove) {
  14284. var index = this.meshes.indexOf(toRemove);
  14285. if (index !== -1) {
  14286. // Remove from the scene if mesh found
  14287. this.meshes.splice(index, 1);
  14288. }
  14289. //notify the collision coordinator
  14290. this.collisionCoordinator.onMeshRemoved(toRemove);
  14291. if (this.onMeshRemoved) {
  14292. this.onMeshRemoved(toRemove);
  14293. }
  14294. return index;
  14295. };
  14296. Scene.prototype.removeSkeleton = function (toRemove) {
  14297. var index = this.skeletons.indexOf(toRemove);
  14298. if (index !== -1) {
  14299. // Remove from the scene if mesh found
  14300. this.skeletons.splice(index, 1);
  14301. }
  14302. return index;
  14303. };
  14304. Scene.prototype.removeLight = function (toRemove) {
  14305. var index = this.lights.indexOf(toRemove);
  14306. if (index !== -1) {
  14307. // Remove from the scene if mesh found
  14308. this.lights.splice(index, 1);
  14309. }
  14310. if (this.onLightRemoved) {
  14311. this.onLightRemoved(toRemove);
  14312. }
  14313. return index;
  14314. };
  14315. Scene.prototype.removeCamera = function (toRemove) {
  14316. var index = this.cameras.indexOf(toRemove);
  14317. if (index !== -1) {
  14318. // Remove from the scene if mesh found
  14319. this.cameras.splice(index, 1);
  14320. }
  14321. // Remove from activeCameras
  14322. var index2 = this.activeCameras.indexOf(toRemove);
  14323. if (index2 !== -1) {
  14324. // Remove from the scene if mesh found
  14325. this.activeCameras.splice(index2, 1);
  14326. }
  14327. // Reset the activeCamera
  14328. if (this.activeCamera === toRemove) {
  14329. if (this.cameras.length > 0) {
  14330. this.activeCamera = this.cameras[0];
  14331. }
  14332. else {
  14333. this.activeCamera = null;
  14334. }
  14335. }
  14336. if (this.onCameraRemoved) {
  14337. this.onCameraRemoved(toRemove);
  14338. }
  14339. return index;
  14340. };
  14341. Scene.prototype.addLight = function (newLight) {
  14342. newLight.uniqueId = this._uniqueIdCounter++;
  14343. var position = this.lights.push(newLight);
  14344. if (this.onNewLightAdded) {
  14345. this.onNewLightAdded(newLight, position, this);
  14346. }
  14347. };
  14348. Scene.prototype.addCamera = function (newCamera) {
  14349. newCamera.uniqueId = this._uniqueIdCounter++;
  14350. var position = this.cameras.push(newCamera);
  14351. if (this.onNewCameraAdded) {
  14352. this.onNewCameraAdded(newCamera, position, this);
  14353. }
  14354. };
  14355. /**
  14356. * Switch active camera
  14357. * @param {Camera} newCamera - new active camera
  14358. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14359. */
  14360. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14361. if (attachControl === void 0) { attachControl = true; }
  14362. var canvas = this._engine.getRenderingCanvas();
  14363. this.activeCamera.detachControl(canvas);
  14364. this.activeCamera = newCamera;
  14365. if (attachControl) {
  14366. newCamera.attachControl(canvas);
  14367. }
  14368. };
  14369. /**
  14370. * sets the active camera of the scene using its ID
  14371. * @param {string} id - the camera's ID
  14372. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14373. * @see activeCamera
  14374. */
  14375. Scene.prototype.setActiveCameraByID = function (id) {
  14376. var camera = this.getCameraByID(id);
  14377. if (camera) {
  14378. this.activeCamera = camera;
  14379. return camera;
  14380. }
  14381. return null;
  14382. };
  14383. /**
  14384. * sets the active camera of the scene using its name
  14385. * @param {string} name - the camera's name
  14386. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14387. * @see activeCamera
  14388. */
  14389. Scene.prototype.setActiveCameraByName = function (name) {
  14390. var camera = this.getCameraByName(name);
  14391. if (camera) {
  14392. this.activeCamera = camera;
  14393. return camera;
  14394. }
  14395. return null;
  14396. };
  14397. /**
  14398. * get a material using its id
  14399. * @param {string} the material's ID
  14400. * @return {BABYLON.Material|null} the material or null if none found.
  14401. */
  14402. Scene.prototype.getMaterialByID = function (id) {
  14403. for (var index = 0; index < this.materials.length; index++) {
  14404. if (this.materials[index].id === id) {
  14405. return this.materials[index];
  14406. }
  14407. }
  14408. return null;
  14409. };
  14410. /**
  14411. * get a material using its name
  14412. * @param {string} the material's name
  14413. * @return {BABYLON.Material|null} the material or null if none found.
  14414. */
  14415. Scene.prototype.getMaterialByName = function (name) {
  14416. for (var index = 0; index < this.materials.length; index++) {
  14417. if (this.materials[index].name === name) {
  14418. return this.materials[index];
  14419. }
  14420. }
  14421. return null;
  14422. };
  14423. Scene.prototype.getLensFlareSystemByName = function (name) {
  14424. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  14425. if (this.lensFlareSystems[index].name === name) {
  14426. return this.lensFlareSystems[index];
  14427. }
  14428. }
  14429. return null;
  14430. };
  14431. Scene.prototype.getCameraByID = function (id) {
  14432. for (var index = 0; index < this.cameras.length; index++) {
  14433. if (this.cameras[index].id === id) {
  14434. return this.cameras[index];
  14435. }
  14436. }
  14437. return null;
  14438. };
  14439. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  14440. for (var index = 0; index < this.cameras.length; index++) {
  14441. if (this.cameras[index].uniqueId === uniqueId) {
  14442. return this.cameras[index];
  14443. }
  14444. }
  14445. return null;
  14446. };
  14447. /**
  14448. * get a camera using its name
  14449. * @param {string} the camera's name
  14450. * @return {BABYLON.Camera|null} the camera or null if none found.
  14451. */
  14452. Scene.prototype.getCameraByName = function (name) {
  14453. for (var index = 0; index < this.cameras.length; index++) {
  14454. if (this.cameras[index].name === name) {
  14455. return this.cameras[index];
  14456. }
  14457. }
  14458. return null;
  14459. };
  14460. /**
  14461. * get a bone using its id
  14462. * @param {string} the bone's id
  14463. * @return {BABYLON.Bone|null} the bone or null if not found
  14464. */
  14465. Scene.prototype.getBoneByID = function (id) {
  14466. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14467. var skeleton = this.skeletons[skeletonIndex];
  14468. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14469. if (skeleton.bones[boneIndex].id === id) {
  14470. return skeleton.bones[boneIndex];
  14471. }
  14472. }
  14473. }
  14474. return null;
  14475. };
  14476. /**
  14477. * get a bone using its id
  14478. * @param {string} the bone's name
  14479. * @return {BABYLON.Bone|null} the bone or null if not found
  14480. */
  14481. Scene.prototype.getBoneByName = function (name) {
  14482. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14483. var skeleton = this.skeletons[skeletonIndex];
  14484. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14485. if (skeleton.bones[boneIndex].name === name) {
  14486. return skeleton.bones[boneIndex];
  14487. }
  14488. }
  14489. }
  14490. return null;
  14491. };
  14492. /**
  14493. * get a light node using its name
  14494. * @param {string} the light's name
  14495. * @return {BABYLON.Light|null} the light or null if none found.
  14496. */
  14497. Scene.prototype.getLightByName = function (name) {
  14498. for (var index = 0; index < this.lights.length; index++) {
  14499. if (this.lights[index].name === name) {
  14500. return this.lights[index];
  14501. }
  14502. }
  14503. return null;
  14504. };
  14505. /**
  14506. * get a light node using its ID
  14507. * @param {string} the light's id
  14508. * @return {BABYLON.Light|null} the light or null if none found.
  14509. */
  14510. Scene.prototype.getLightByID = function (id) {
  14511. for (var index = 0; index < this.lights.length; index++) {
  14512. if (this.lights[index].id === id) {
  14513. return this.lights[index];
  14514. }
  14515. }
  14516. return null;
  14517. };
  14518. /**
  14519. * get a light node using its scene-generated unique ID
  14520. * @param {number} the light's unique id
  14521. * @return {BABYLON.Light|null} the light or null if none found.
  14522. */
  14523. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  14524. for (var index = 0; index < this.lights.length; index++) {
  14525. if (this.lights[index].uniqueId === uniqueId) {
  14526. return this.lights[index];
  14527. }
  14528. }
  14529. return null;
  14530. };
  14531. /**
  14532. * get a particle system by id
  14533. * @param id {number} the particle system id
  14534. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  14535. */
  14536. Scene.prototype.getParticleSystemByID = function (id) {
  14537. for (var index = 0; index < this.particleSystems.length; index++) {
  14538. if (this.particleSystems[index].id === id) {
  14539. return this.particleSystems[index];
  14540. }
  14541. }
  14542. return null;
  14543. };
  14544. /**
  14545. * get a geometry using its ID
  14546. * @param {string} the geometry's id
  14547. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  14548. */
  14549. Scene.prototype.getGeometryByID = function (id) {
  14550. for (var index = 0; index < this._geometries.length; index++) {
  14551. if (this._geometries[index].id === id) {
  14552. return this._geometries[index];
  14553. }
  14554. }
  14555. return null;
  14556. };
  14557. /**
  14558. * add a new geometry to this scene.
  14559. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  14560. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  14561. * @return {boolean} was the geometry added or not
  14562. */
  14563. Scene.prototype.pushGeometry = function (geometry, force) {
  14564. if (!force && this.getGeometryByID(geometry.id)) {
  14565. return false;
  14566. }
  14567. this._geometries.push(geometry);
  14568. //notify the collision coordinator
  14569. this.collisionCoordinator.onGeometryAdded(geometry);
  14570. if (this.onGeometryAdded) {
  14571. this.onGeometryAdded(geometry);
  14572. }
  14573. return true;
  14574. };
  14575. /**
  14576. * Removes an existing geometry
  14577. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  14578. * @return {boolean} was the geometry removed or not
  14579. */
  14580. Scene.prototype.removeGeometry = function (geometry) {
  14581. var index = this._geometries.indexOf(geometry);
  14582. if (index > -1) {
  14583. this._geometries.splice(index, 1);
  14584. //notify the collision coordinator
  14585. this.collisionCoordinator.onGeometryDeleted(geometry);
  14586. if (this.onGeometryRemoved) {
  14587. this.onGeometryRemoved(geometry);
  14588. }
  14589. return true;
  14590. }
  14591. return false;
  14592. };
  14593. Scene.prototype.getGeometries = function () {
  14594. return this._geometries;
  14595. };
  14596. /**
  14597. * Get the first added mesh found of a given ID
  14598. * @param {string} id - the id to search for
  14599. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14600. */
  14601. Scene.prototype.getMeshByID = function (id) {
  14602. for (var index = 0; index < this.meshes.length; index++) {
  14603. if (this.meshes[index].id === id) {
  14604. return this.meshes[index];
  14605. }
  14606. }
  14607. return null;
  14608. };
  14609. /**
  14610. * Get a mesh with its auto-generated unique id
  14611. * @param {number} uniqueId - the unique id to search for
  14612. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14613. */
  14614. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  14615. for (var index = 0; index < this.meshes.length; index++) {
  14616. if (this.meshes[index].uniqueId === uniqueId) {
  14617. return this.meshes[index];
  14618. }
  14619. }
  14620. return null;
  14621. };
  14622. /**
  14623. * Get a the last added mesh found of a given ID
  14624. * @param {string} id - the id to search for
  14625. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14626. */
  14627. Scene.prototype.getLastMeshByID = function (id) {
  14628. for (var index = this.meshes.length - 1; index >= 0; index--) {
  14629. if (this.meshes[index].id === id) {
  14630. return this.meshes[index];
  14631. }
  14632. }
  14633. return null;
  14634. };
  14635. /**
  14636. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  14637. * @param {string} id - the id to search for
  14638. * @return {BABYLON.Node|null} the node found or null if not found at all.
  14639. */
  14640. Scene.prototype.getLastEntryByID = function (id) {
  14641. var index;
  14642. for (index = this.meshes.length - 1; index >= 0; index--) {
  14643. if (this.meshes[index].id === id) {
  14644. return this.meshes[index];
  14645. }
  14646. }
  14647. for (index = this.cameras.length - 1; index >= 0; index--) {
  14648. if (this.cameras[index].id === id) {
  14649. return this.cameras[index];
  14650. }
  14651. }
  14652. for (index = this.lights.length - 1; index >= 0; index--) {
  14653. if (this.lights[index].id === id) {
  14654. return this.lights[index];
  14655. }
  14656. }
  14657. return null;
  14658. };
  14659. Scene.prototype.getNodeByID = function (id) {
  14660. var mesh = this.getMeshByID(id);
  14661. if (mesh) {
  14662. return mesh;
  14663. }
  14664. var light = this.getLightByID(id);
  14665. if (light) {
  14666. return light;
  14667. }
  14668. var camera = this.getCameraByID(id);
  14669. if (camera) {
  14670. return camera;
  14671. }
  14672. var bone = this.getBoneByID(id);
  14673. return bone;
  14674. };
  14675. Scene.prototype.getNodeByName = function (name) {
  14676. var mesh = this.getMeshByName(name);
  14677. if (mesh) {
  14678. return mesh;
  14679. }
  14680. var light = this.getLightByName(name);
  14681. if (light) {
  14682. return light;
  14683. }
  14684. var camera = this.getCameraByName(name);
  14685. if (camera) {
  14686. return camera;
  14687. }
  14688. var bone = this.getBoneByName(name);
  14689. return bone;
  14690. };
  14691. Scene.prototype.getMeshByName = function (name) {
  14692. for (var index = 0; index < this.meshes.length; index++) {
  14693. if (this.meshes[index].name === name) {
  14694. return this.meshes[index];
  14695. }
  14696. }
  14697. return null;
  14698. };
  14699. Scene.prototype.getSoundByName = function (name) {
  14700. var index;
  14701. if (BABYLON.AudioEngine) {
  14702. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  14703. if (this.mainSoundTrack.soundCollection[index].name === name) {
  14704. return this.mainSoundTrack.soundCollection[index];
  14705. }
  14706. }
  14707. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  14708. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  14709. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  14710. return this.soundTracks[sdIndex].soundCollection[index];
  14711. }
  14712. }
  14713. }
  14714. }
  14715. return null;
  14716. };
  14717. Scene.prototype.getLastSkeletonByID = function (id) {
  14718. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  14719. if (this.skeletons[index].id === id) {
  14720. return this.skeletons[index];
  14721. }
  14722. }
  14723. return null;
  14724. };
  14725. Scene.prototype.getSkeletonById = function (id) {
  14726. for (var index = 0; index < this.skeletons.length; index++) {
  14727. if (this.skeletons[index].id === id) {
  14728. return this.skeletons[index];
  14729. }
  14730. }
  14731. return null;
  14732. };
  14733. Scene.prototype.getSkeletonByName = function (name) {
  14734. for (var index = 0; index < this.skeletons.length; index++) {
  14735. if (this.skeletons[index].name === name) {
  14736. return this.skeletons[index];
  14737. }
  14738. }
  14739. return null;
  14740. };
  14741. Scene.prototype.isActiveMesh = function (mesh) {
  14742. return (this._activeMeshes.indexOf(mesh) !== -1);
  14743. };
  14744. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  14745. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  14746. var material = subMesh.getMaterial();
  14747. if (mesh.showSubMeshesBoundingBox) {
  14748. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  14749. }
  14750. if (material) {
  14751. // Render targets
  14752. if (material.getRenderTargetTextures) {
  14753. if (this._processedMaterials.indexOf(material) === -1) {
  14754. this._processedMaterials.push(material);
  14755. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  14756. }
  14757. }
  14758. // Dispatch
  14759. this._activeIndices += subMesh.indexCount;
  14760. this._renderingManager.dispatch(subMesh);
  14761. }
  14762. }
  14763. };
  14764. Scene.prototype._evaluateActiveMeshes = function () {
  14765. this.activeCamera._activeMeshes.reset();
  14766. this._activeMeshes.reset();
  14767. this._renderingManager.reset();
  14768. this._processedMaterials.reset();
  14769. this._activeParticleSystems.reset();
  14770. this._activeSkeletons.reset();
  14771. this._softwareSkinnedMeshes.reset();
  14772. this._boundingBoxRenderer.reset();
  14773. this._edgesRenderers.reset();
  14774. if (!this._frustumPlanes) {
  14775. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14776. }
  14777. else {
  14778. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14779. }
  14780. // Meshes
  14781. var meshes;
  14782. var len;
  14783. if (this._selectionOctree) {
  14784. var selection = this._selectionOctree.select(this._frustumPlanes);
  14785. meshes = selection.data;
  14786. len = selection.length;
  14787. }
  14788. else {
  14789. len = this.meshes.length;
  14790. meshes = this.meshes;
  14791. }
  14792. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  14793. var mesh = meshes[meshIndex];
  14794. if (mesh.isBlocked) {
  14795. continue;
  14796. }
  14797. this._totalVertices += mesh.getTotalVertices();
  14798. if (!mesh.isReady() || !mesh.isEnabled()) {
  14799. continue;
  14800. }
  14801. mesh.computeWorldMatrix();
  14802. // Intersections
  14803. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  14804. this._meshesForIntersections.pushNoDuplicate(mesh);
  14805. }
  14806. // Switch to current LOD
  14807. var meshLOD = mesh.getLOD(this.activeCamera);
  14808. if (!meshLOD) {
  14809. continue;
  14810. }
  14811. mesh._preActivate();
  14812. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  14813. this._activeMeshes.push(mesh);
  14814. this.activeCamera._activeMeshes.push(mesh);
  14815. mesh._activate(this._renderId);
  14816. this._activeMesh(meshLOD);
  14817. }
  14818. }
  14819. // Particle systems
  14820. var beforeParticlesDate = BABYLON.Tools.Now;
  14821. if (this.particlesEnabled) {
  14822. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  14823. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  14824. var particleSystem = this.particleSystems[particleIndex];
  14825. if (!particleSystem.isStarted()) {
  14826. continue;
  14827. }
  14828. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  14829. this._activeParticleSystems.push(particleSystem);
  14830. particleSystem.animate();
  14831. }
  14832. }
  14833. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  14834. }
  14835. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14836. };
  14837. Scene.prototype._activeMesh = function (mesh) {
  14838. if (mesh.skeleton && this.skeletonsEnabled) {
  14839. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  14840. if (!mesh.computeBonesUsingShaders) {
  14841. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  14842. }
  14843. }
  14844. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  14845. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  14846. }
  14847. if (mesh._edgesRenderer) {
  14848. this._edgesRenderers.push(mesh._edgesRenderer);
  14849. }
  14850. if (mesh && mesh.subMeshes) {
  14851. // Submeshes Octrees
  14852. var len;
  14853. var subMeshes;
  14854. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  14855. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  14856. len = intersections.length;
  14857. subMeshes = intersections.data;
  14858. }
  14859. else {
  14860. subMeshes = mesh.subMeshes;
  14861. len = subMeshes.length;
  14862. }
  14863. for (var subIndex = 0; subIndex < len; subIndex++) {
  14864. var subMesh = subMeshes[subIndex];
  14865. this._evaluateSubMesh(subMesh, mesh);
  14866. }
  14867. }
  14868. };
  14869. Scene.prototype.updateTransformMatrix = function (force) {
  14870. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  14871. };
  14872. Scene.prototype._renderForCamera = function (camera) {
  14873. var engine = this._engine;
  14874. this.activeCamera = camera;
  14875. if (!this.activeCamera)
  14876. throw new Error("Active camera not set");
  14877. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14878. // Viewport
  14879. engine.setViewport(this.activeCamera.viewport);
  14880. // Camera
  14881. this.resetCachedMaterial();
  14882. this._renderId++;
  14883. this.updateTransformMatrix();
  14884. if (this.beforeCameraRender) {
  14885. this.beforeCameraRender(this.activeCamera);
  14886. }
  14887. // Meshes
  14888. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  14889. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  14890. this._evaluateActiveMeshes();
  14891. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  14892. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  14893. // Skeletons
  14894. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  14895. var skeleton = this._activeSkeletons.data[skeletonIndex];
  14896. skeleton.prepare();
  14897. }
  14898. // Software skinning
  14899. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  14900. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  14901. mesh.applySkeleton(mesh.skeleton);
  14902. }
  14903. // Render targets
  14904. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14905. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  14906. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  14907. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  14908. var renderTarget = this._renderTargets.data[renderIndex];
  14909. if (renderTarget._shouldRender()) {
  14910. this._renderId++;
  14911. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  14912. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  14913. }
  14914. }
  14915. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  14916. this._renderId++;
  14917. engine.restoreDefaultFramebuffer(); // Restore back buffer
  14918. }
  14919. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14920. // Prepare Frame
  14921. this.postProcessManager._prepareFrame();
  14922. var beforeRenderDate = BABYLON.Tools.Now;
  14923. // Backgrounds
  14924. var layerIndex;
  14925. var layer;
  14926. if (this.layers.length) {
  14927. engine.setDepthBuffer(false);
  14928. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14929. layer = this.layers[layerIndex];
  14930. if (layer.isBackground) {
  14931. layer.render();
  14932. }
  14933. }
  14934. engine.setDepthBuffer(true);
  14935. }
  14936. // Render
  14937. BABYLON.Tools.StartPerformanceCounter("Main render");
  14938. this._renderingManager.render(null, null, true, true);
  14939. BABYLON.Tools.EndPerformanceCounter("Main render");
  14940. // Bounding boxes
  14941. this._boundingBoxRenderer.render();
  14942. // Edges
  14943. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14944. this._edgesRenderers.data[edgesRendererIndex].render();
  14945. }
  14946. // Lens flares
  14947. if (this.lensFlaresEnabled) {
  14948. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14949. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  14950. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  14951. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  14952. lensFlareSystem.render();
  14953. }
  14954. }
  14955. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14956. }
  14957. // Foregrounds
  14958. if (this.layers.length) {
  14959. engine.setDepthBuffer(false);
  14960. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14961. layer = this.layers[layerIndex];
  14962. if (!layer.isBackground) {
  14963. layer.render();
  14964. }
  14965. }
  14966. engine.setDepthBuffer(true);
  14967. }
  14968. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  14969. // Finalize frame
  14970. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  14971. // Update camera
  14972. this.activeCamera._updateFromScene();
  14973. // Reset some special arrays
  14974. this._renderTargets.reset();
  14975. if (this.afterCameraRender) {
  14976. this.afterCameraRender(this.activeCamera);
  14977. }
  14978. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14979. };
  14980. Scene.prototype._processSubCameras = function (camera) {
  14981. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  14982. this._renderForCamera(camera);
  14983. return;
  14984. }
  14985. // rig cameras
  14986. for (var index = 0; index < camera._rigCameras.length; index++) {
  14987. this._renderForCamera(camera._rigCameras[index]);
  14988. }
  14989. this.activeCamera = camera;
  14990. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  14991. // Update camera
  14992. this.activeCamera._updateFromScene();
  14993. };
  14994. Scene.prototype._checkIntersections = function () {
  14995. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14996. var sourceMesh = this._meshesForIntersections.data[index];
  14997. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14998. var action = sourceMesh.actionManager.actions[actionIndex];
  14999. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15000. var parameters = action.getTriggerParameter();
  15001. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15002. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15003. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15004. if (areIntersecting && currentIntersectionInProgress === -1) {
  15005. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15006. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15007. sourceMesh._intersectionsInProgress.push(otherMesh);
  15008. }
  15009. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15010. sourceMesh._intersectionsInProgress.push(otherMesh);
  15011. }
  15012. }
  15013. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15014. //They intersected, and now they don't.
  15015. //is this trigger an exit trigger? execute an event.
  15016. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15017. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15018. }
  15019. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15020. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15021. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15022. }
  15023. }
  15024. }
  15025. }
  15026. }
  15027. };
  15028. Scene.prototype.render = function () {
  15029. var startDate = BABYLON.Tools.Now;
  15030. this._particlesDuration = 0;
  15031. this._spritesDuration = 0;
  15032. this._activeParticles = 0;
  15033. this._renderDuration = 0;
  15034. this._renderTargetsDuration = 0;
  15035. this._evaluateActiveMeshesDuration = 0;
  15036. this._totalVertices = 0;
  15037. this._activeIndices = 0;
  15038. this._activeBones = 0;
  15039. this.getEngine().resetDrawCalls();
  15040. this._meshesForIntersections.reset();
  15041. this.resetCachedMaterial();
  15042. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15043. // Actions
  15044. if (this.actionManager) {
  15045. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15046. }
  15047. //Simplification Queue
  15048. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15049. this.simplificationQueue.executeNext();
  15050. }
  15051. // Animations
  15052. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15053. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15054. this._animate();
  15055. // Physics
  15056. if (this._physicsEngine) {
  15057. BABYLON.Tools.StartPerformanceCounter("Physics");
  15058. this._physicsEngine._step(deltaTime / 1000.0);
  15059. BABYLON.Tools.EndPerformanceCounter("Physics");
  15060. }
  15061. // Before render
  15062. if (this.beforeRender) {
  15063. this.beforeRender();
  15064. }
  15065. var callbackIndex;
  15066. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15067. this._onBeforeRenderCallbacks[callbackIndex]();
  15068. }
  15069. // Customs render targets
  15070. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15071. var engine = this.getEngine();
  15072. var currentActiveCamera = this.activeCamera;
  15073. if (this.renderTargetsEnabled) {
  15074. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15075. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15076. var renderTarget = this.customRenderTargets[customIndex];
  15077. if (renderTarget._shouldRender()) {
  15078. this._renderId++;
  15079. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15080. if (!this.activeCamera)
  15081. throw new Error("Active camera not set");
  15082. // Viewport
  15083. engine.setViewport(this.activeCamera.viewport);
  15084. // Camera
  15085. this.updateTransformMatrix();
  15086. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15087. }
  15088. }
  15089. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15090. this._renderId++;
  15091. }
  15092. if (this.customRenderTargets.length > 0) {
  15093. engine.restoreDefaultFramebuffer();
  15094. }
  15095. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15096. this.activeCamera = currentActiveCamera;
  15097. // Procedural textures
  15098. if (this.proceduralTexturesEnabled) {
  15099. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15100. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15101. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15102. if (proceduralTexture._shouldRender()) {
  15103. proceduralTexture.render();
  15104. }
  15105. }
  15106. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15107. }
  15108. // Clear
  15109. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15110. // Shadows
  15111. if (this.shadowsEnabled) {
  15112. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15113. var light = this.lights[lightIndex];
  15114. var shadowGenerator = light.getShadowGenerator();
  15115. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15116. this._renderTargets.push(shadowGenerator.getShadowMap());
  15117. }
  15118. }
  15119. }
  15120. // Depth renderer
  15121. if (this._depthRenderer) {
  15122. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15123. }
  15124. // RenderPipeline
  15125. this.postProcessRenderPipelineManager.update();
  15126. // Multi-cameras?
  15127. if (this.activeCameras.length > 0) {
  15128. var currentRenderId = this._renderId;
  15129. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15130. this._renderId = currentRenderId;
  15131. if (cameraIndex > 0) {
  15132. this._engine.clear(0, false, true);
  15133. }
  15134. this._processSubCameras(this.activeCameras[cameraIndex]);
  15135. }
  15136. }
  15137. else {
  15138. if (!this.activeCamera) {
  15139. throw new Error("No camera defined");
  15140. }
  15141. this._processSubCameras(this.activeCamera);
  15142. }
  15143. // Intersection checks
  15144. this._checkIntersections();
  15145. // Update the audio listener attached to the camera
  15146. if (BABYLON.AudioEngine) {
  15147. this._updateAudioParameters();
  15148. }
  15149. // After render
  15150. if (this.afterRender) {
  15151. this.afterRender();
  15152. }
  15153. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15154. this._onAfterRenderCallbacks[callbackIndex]();
  15155. }
  15156. // Cleaning
  15157. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15158. this._toBeDisposed.data[index].dispose();
  15159. this._toBeDisposed[index] = null;
  15160. }
  15161. this._toBeDisposed.reset();
  15162. if (this.dumpNextRenderTargets) {
  15163. this.dumpNextRenderTargets = false;
  15164. }
  15165. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15166. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15167. };
  15168. Scene.prototype._updateAudioParameters = function () {
  15169. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15170. return;
  15171. }
  15172. var listeningCamera;
  15173. var audioEngine = BABYLON.Engine.audioEngine;
  15174. if (this.activeCameras.length > 0) {
  15175. listeningCamera = this.activeCameras[0];
  15176. }
  15177. else {
  15178. listeningCamera = this.activeCamera;
  15179. }
  15180. if (listeningCamera && audioEngine.canUseWebAudio) {
  15181. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15182. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15183. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15184. cameraDirection.normalize();
  15185. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15186. var i;
  15187. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15188. var sound = this.mainSoundTrack.soundCollection[i];
  15189. if (sound.useCustomAttenuation) {
  15190. sound.updateDistanceFromListener();
  15191. }
  15192. }
  15193. for (i = 0; i < this.soundTracks.length; i++) {
  15194. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15195. sound = this.soundTracks[i].soundCollection[j];
  15196. if (sound.useCustomAttenuation) {
  15197. sound.updateDistanceFromListener();
  15198. }
  15199. }
  15200. }
  15201. }
  15202. };
  15203. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15204. // Audio
  15205. get: function () {
  15206. return this._audioEnabled;
  15207. },
  15208. set: function (value) {
  15209. this._audioEnabled = value;
  15210. if (BABYLON.AudioEngine) {
  15211. if (this._audioEnabled) {
  15212. this._enableAudio();
  15213. }
  15214. else {
  15215. this._disableAudio();
  15216. }
  15217. }
  15218. },
  15219. enumerable: true,
  15220. configurable: true
  15221. });
  15222. Scene.prototype._disableAudio = function () {
  15223. var i;
  15224. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15225. this.mainSoundTrack.soundCollection[i].pause();
  15226. }
  15227. for (i = 0; i < this.soundTracks.length; i++) {
  15228. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15229. this.soundTracks[i].soundCollection[j].pause();
  15230. }
  15231. }
  15232. };
  15233. Scene.prototype._enableAudio = function () {
  15234. var i;
  15235. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15236. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15237. this.mainSoundTrack.soundCollection[i].play();
  15238. }
  15239. }
  15240. for (i = 0; i < this.soundTracks.length; i++) {
  15241. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15242. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15243. this.soundTracks[i].soundCollection[j].play();
  15244. }
  15245. }
  15246. }
  15247. };
  15248. Object.defineProperty(Scene.prototype, "headphone", {
  15249. get: function () {
  15250. return this._headphone;
  15251. },
  15252. set: function (value) {
  15253. this._headphone = value;
  15254. if (BABYLON.AudioEngine) {
  15255. if (this._headphone) {
  15256. this._switchAudioModeForHeadphones();
  15257. }
  15258. else {
  15259. this._switchAudioModeForNormalSpeakers();
  15260. }
  15261. }
  15262. },
  15263. enumerable: true,
  15264. configurable: true
  15265. });
  15266. Scene.prototype._switchAudioModeForHeadphones = function () {
  15267. this.mainSoundTrack.switchPanningModelToHRTF();
  15268. for (var i = 0; i < this.soundTracks.length; i++) {
  15269. this.soundTracks[i].switchPanningModelToHRTF();
  15270. }
  15271. };
  15272. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15273. this.mainSoundTrack.switchPanningModelToEqualPower();
  15274. for (var i = 0; i < this.soundTracks.length; i++) {
  15275. this.soundTracks[i].switchPanningModelToEqualPower();
  15276. }
  15277. };
  15278. Scene.prototype.enableDepthRenderer = function () {
  15279. if (this._depthRenderer) {
  15280. return this._depthRenderer;
  15281. }
  15282. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15283. return this._depthRenderer;
  15284. };
  15285. Scene.prototype.disableDepthRenderer = function () {
  15286. if (!this._depthRenderer) {
  15287. return;
  15288. }
  15289. this._depthRenderer.dispose();
  15290. this._depthRenderer = null;
  15291. };
  15292. Scene.prototype.freezeMaterials = function () {
  15293. for (var i = 0; i < this.materials.length; i++) {
  15294. this.materials[i].freeze();
  15295. }
  15296. };
  15297. Scene.prototype.unfreezeMaterials = function () {
  15298. for (var i = 0; i < this.materials.length; i++) {
  15299. this.materials[i].unfreeze();
  15300. }
  15301. };
  15302. Scene.prototype.dispose = function () {
  15303. this.beforeRender = null;
  15304. this.afterRender = null;
  15305. this.skeletons = [];
  15306. this._boundingBoxRenderer.dispose();
  15307. if (this._depthRenderer) {
  15308. this._depthRenderer.dispose();
  15309. }
  15310. // Debug layer
  15311. this.debugLayer.hide();
  15312. // Events
  15313. if (this.onDispose) {
  15314. this.onDispose();
  15315. }
  15316. this._onBeforeRenderCallbacks = [];
  15317. this._onAfterRenderCallbacks = [];
  15318. this.detachControl();
  15319. // Release sounds & sounds tracks
  15320. if (BABYLON.AudioEngine) {
  15321. this.disposeSounds();
  15322. }
  15323. // Detach cameras
  15324. var canvas = this._engine.getRenderingCanvas();
  15325. var index;
  15326. for (index = 0; index < this.cameras.length; index++) {
  15327. this.cameras[index].detachControl(canvas);
  15328. }
  15329. // Release lights
  15330. while (this.lights.length) {
  15331. this.lights[0].dispose();
  15332. }
  15333. // Release meshes
  15334. while (this.meshes.length) {
  15335. this.meshes[0].dispose(true);
  15336. }
  15337. // Release cameras
  15338. while (this.cameras.length) {
  15339. this.cameras[0].dispose();
  15340. }
  15341. // Release materials
  15342. while (this.materials.length) {
  15343. this.materials[0].dispose();
  15344. }
  15345. // Release particles
  15346. while (this.particleSystems.length) {
  15347. this.particleSystems[0].dispose();
  15348. }
  15349. // Release sprites
  15350. while (this.spriteManagers.length) {
  15351. this.spriteManagers[0].dispose();
  15352. }
  15353. // Release layers
  15354. while (this.layers.length) {
  15355. this.layers[0].dispose();
  15356. }
  15357. // Release textures
  15358. while (this.textures.length) {
  15359. this.textures[0].dispose();
  15360. }
  15361. // Post-processes
  15362. this.postProcessManager.dispose();
  15363. // Physics
  15364. if (this._physicsEngine) {
  15365. this.disablePhysicsEngine();
  15366. }
  15367. // Remove from engine
  15368. index = this._engine.scenes.indexOf(this);
  15369. if (index > -1) {
  15370. this._engine.scenes.splice(index, 1);
  15371. }
  15372. this._engine.wipeCaches();
  15373. };
  15374. // Release sounds & sounds tracks
  15375. Scene.prototype.disposeSounds = function () {
  15376. this.mainSoundTrack.dispose();
  15377. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15378. this.soundTracks[scIndex].dispose();
  15379. }
  15380. };
  15381. // Octrees
  15382. Scene.prototype.getWorldExtends = function () {
  15383. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15384. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15385. for (var index = 0; index < this.meshes.length; index++) {
  15386. var mesh = this.meshes[index];
  15387. mesh.computeWorldMatrix(true);
  15388. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  15389. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  15390. BABYLON.Tools.CheckExtends(minBox, min, max);
  15391. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15392. }
  15393. return {
  15394. min: min,
  15395. max: max
  15396. };
  15397. };
  15398. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  15399. if (maxCapacity === void 0) { maxCapacity = 64; }
  15400. if (maxDepth === void 0) { maxDepth = 2; }
  15401. if (!this._selectionOctree) {
  15402. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  15403. }
  15404. var worldExtends = this.getWorldExtends();
  15405. // Update octree
  15406. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  15407. return this._selectionOctree;
  15408. };
  15409. // Picking
  15410. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  15411. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  15412. var engine = this._engine;
  15413. if (!camera) {
  15414. if (!this.activeCamera)
  15415. throw new Error("Active camera not set");
  15416. camera = this.activeCamera;
  15417. }
  15418. var cameraViewport = camera.viewport;
  15419. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15420. // Moving coordinates to local viewport world
  15421. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15422. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15423. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  15424. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  15425. };
  15426. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  15427. var engine = this._engine;
  15428. if (!camera) {
  15429. if (!this.activeCamera)
  15430. throw new Error("Active camera not set");
  15431. camera = this.activeCamera;
  15432. }
  15433. var cameraViewport = camera.viewport;
  15434. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15435. var identity = BABYLON.Matrix.Identity();
  15436. // Moving coordinates to local viewport world
  15437. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15438. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15439. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  15440. };
  15441. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  15442. var pickingInfo = null;
  15443. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  15444. var mesh = this.meshes[meshIndex];
  15445. if (predicate) {
  15446. if (!predicate(mesh)) {
  15447. continue;
  15448. }
  15449. }
  15450. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  15451. continue;
  15452. }
  15453. var world = mesh.getWorldMatrix();
  15454. var ray = rayFunction(world);
  15455. var result = mesh.intersects(ray, fastCheck);
  15456. if (!result || !result.hit)
  15457. continue;
  15458. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15459. continue;
  15460. pickingInfo = result;
  15461. if (fastCheck) {
  15462. break;
  15463. }
  15464. }
  15465. return pickingInfo || new BABYLON.PickingInfo();
  15466. };
  15467. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  15468. var pickingInfo = null;
  15469. camera = camera || this.activeCamera;
  15470. if (this.spriteManagers.length > 0) {
  15471. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  15472. var spriteManager = this.spriteManagers[spriteIndex];
  15473. if (!spriteManager.isPickable) {
  15474. continue;
  15475. }
  15476. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  15477. if (!result || !result.hit)
  15478. continue;
  15479. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15480. continue;
  15481. pickingInfo = result;
  15482. if (fastCheck) {
  15483. break;
  15484. }
  15485. }
  15486. }
  15487. return pickingInfo || new BABYLON.PickingInfo();
  15488. };
  15489. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  15490. var _this = this;
  15491. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15492. /// <param name="x">X position on screen</param>
  15493. /// <param name="y">Y position on screen</param>
  15494. /// <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>
  15495. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15496. /// <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>
  15497. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  15498. };
  15499. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  15500. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15501. /// <param name="x">X position on screen</param>
  15502. /// <param name="y">Y position on screen</param>
  15503. /// <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>
  15504. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15505. /// <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>
  15506. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  15507. };
  15508. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  15509. var _this = this;
  15510. return this._internalPick(function (world) {
  15511. if (!_this._pickWithRayInverseMatrix) {
  15512. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  15513. }
  15514. world.invertToRef(_this._pickWithRayInverseMatrix);
  15515. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  15516. }, predicate, fastCheck);
  15517. };
  15518. Scene.prototype.setPointerOverMesh = function (mesh) {
  15519. if (this._pointerOverMesh === mesh) {
  15520. return;
  15521. }
  15522. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15523. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15524. }
  15525. this._pointerOverMesh = mesh;
  15526. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15527. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15528. }
  15529. };
  15530. Scene.prototype.getPointerOverMesh = function () {
  15531. return this._pointerOverMesh;
  15532. };
  15533. Scene.prototype.setPointerOverSprite = function (sprite) {
  15534. if (this._pointerOverSprite === sprite) {
  15535. return;
  15536. }
  15537. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15538. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15539. }
  15540. this._pointerOverSprite = sprite;
  15541. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15542. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15543. }
  15544. };
  15545. Scene.prototype.getPointerOverSprite = function () {
  15546. return this._pointerOverSprite;
  15547. };
  15548. // Physics
  15549. Scene.prototype.getPhysicsEngine = function () {
  15550. return this._physicsEngine;
  15551. };
  15552. /**
  15553. * Enables physics to the current scene
  15554. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  15555. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  15556. * @return {boolean} was the physics engine initialized
  15557. */
  15558. Scene.prototype.enablePhysics = function (gravity, plugin) {
  15559. if (this._physicsEngine) {
  15560. return true;
  15561. }
  15562. try {
  15563. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  15564. return true;
  15565. }
  15566. catch (e) {
  15567. BABYLON.Tools.Error(e.message);
  15568. return false;
  15569. }
  15570. };
  15571. Scene.prototype.disablePhysicsEngine = function () {
  15572. if (!this._physicsEngine) {
  15573. return;
  15574. }
  15575. this._physicsEngine.dispose();
  15576. this._physicsEngine = undefined;
  15577. };
  15578. Scene.prototype.isPhysicsEnabled = function () {
  15579. return this._physicsEngine !== undefined;
  15580. };
  15581. /**
  15582. *
  15583. * Sets the gravity of the physics engine (and NOT of the scene)
  15584. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  15585. */
  15586. Scene.prototype.setGravity = function (gravity) {
  15587. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  15588. if (!this._physicsEngine) {
  15589. return;
  15590. }
  15591. this._physicsEngine.setGravity(gravity);
  15592. };
  15593. /**
  15594. * Legacy support, using the new API
  15595. * @Deprecated
  15596. */
  15597. Scene.prototype.createCompoundImpostor = function (parts, options) {
  15598. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  15599. if (parts.parts) {
  15600. options = parts;
  15601. parts = parts.parts;
  15602. }
  15603. var mainMesh = parts[0].mesh;
  15604. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  15605. for (var index = 1; index < parts.length; index++) {
  15606. var mesh = parts[index].mesh;
  15607. if (mesh.parent !== mainMesh) {
  15608. mesh.position = mesh.position.subtract(mainMesh.position);
  15609. mesh.parent = mainMesh;
  15610. }
  15611. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  15612. }
  15613. mainMesh.physicsImpostor.forceUpdate();
  15614. };
  15615. Scene.prototype.deleteCompoundImpostor = function (compound) {
  15616. var mesh = compound.parts[0].mesh;
  15617. mesh.physicsImpostor.dispose(true);
  15618. mesh.physicsImpostor = null;
  15619. };
  15620. // Misc.
  15621. Scene.prototype.createDefaultCameraOrLight = function () {
  15622. // Light
  15623. if (this.lights.length === 0) {
  15624. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  15625. }
  15626. // Camera
  15627. if (!this.activeCamera) {
  15628. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  15629. // Compute position
  15630. var worldExtends = this.getWorldExtends();
  15631. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  15632. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  15633. camera.setTarget(worldCenter);
  15634. this.activeCamera = camera;
  15635. }
  15636. };
  15637. // Tags
  15638. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  15639. if (tagsQuery === undefined) {
  15640. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  15641. return list;
  15642. }
  15643. var listByTags = [];
  15644. forEach = forEach || (function (item) { return; });
  15645. for (var i in list) {
  15646. var item = list[i];
  15647. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  15648. listByTags.push(item);
  15649. forEach(item);
  15650. }
  15651. }
  15652. return listByTags;
  15653. };
  15654. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  15655. return this._getByTags(this.meshes, tagsQuery, forEach);
  15656. };
  15657. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  15658. return this._getByTags(this.cameras, tagsQuery, forEach);
  15659. };
  15660. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  15661. return this._getByTags(this.lights, tagsQuery, forEach);
  15662. };
  15663. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  15664. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  15665. };
  15666. // Statics
  15667. Scene._FOGMODE_NONE = 0;
  15668. Scene._FOGMODE_EXP = 1;
  15669. Scene._FOGMODE_EXP2 = 2;
  15670. Scene._FOGMODE_LINEAR = 3;
  15671. Scene.MinDeltaTime = 1.0;
  15672. Scene.MaxDeltaTime = 1000.0;
  15673. return Scene;
  15674. })();
  15675. BABYLON.Scene = Scene;
  15676. })(BABYLON || (BABYLON = {}));
  15677. var BABYLON;
  15678. (function (BABYLON) {
  15679. var VertexBuffer = (function () {
  15680. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  15681. if (engine instanceof BABYLON.Mesh) {
  15682. this._engine = engine.getScene().getEngine();
  15683. }
  15684. else {
  15685. this._engine = engine;
  15686. }
  15687. this._updatable = updatable;
  15688. this._data = data;
  15689. if (!postponeInternalCreation) {
  15690. this.create();
  15691. }
  15692. this._kind = kind;
  15693. if (stride) {
  15694. this._strideSize = stride;
  15695. return;
  15696. }
  15697. // Deduce stride from kind
  15698. switch (kind) {
  15699. case VertexBuffer.PositionKind:
  15700. this._strideSize = 3;
  15701. break;
  15702. case VertexBuffer.NormalKind:
  15703. this._strideSize = 3;
  15704. break;
  15705. case VertexBuffer.UVKind:
  15706. case VertexBuffer.UV2Kind:
  15707. case VertexBuffer.UV3Kind:
  15708. case VertexBuffer.UV4Kind:
  15709. case VertexBuffer.UV5Kind:
  15710. case VertexBuffer.UV6Kind:
  15711. this._strideSize = 2;
  15712. break;
  15713. case VertexBuffer.ColorKind:
  15714. this._strideSize = 4;
  15715. break;
  15716. case VertexBuffer.MatricesIndicesKind:
  15717. case VertexBuffer.MatricesIndicesExtraKind:
  15718. this._strideSize = 4;
  15719. break;
  15720. case VertexBuffer.MatricesWeightsKind:
  15721. case VertexBuffer.MatricesWeightsExtraKind:
  15722. this._strideSize = 4;
  15723. break;
  15724. }
  15725. }
  15726. // Properties
  15727. VertexBuffer.prototype.isUpdatable = function () {
  15728. return this._updatable;
  15729. };
  15730. VertexBuffer.prototype.getData = function () {
  15731. return this._data;
  15732. };
  15733. VertexBuffer.prototype.getBuffer = function () {
  15734. return this._buffer;
  15735. };
  15736. VertexBuffer.prototype.getStrideSize = function () {
  15737. return this._strideSize;
  15738. };
  15739. // Methods
  15740. VertexBuffer.prototype.create = function (data) {
  15741. if (!data && this._buffer) {
  15742. return; // nothing to do
  15743. }
  15744. data = data || this._data;
  15745. if (!this._buffer) {
  15746. if (this._updatable) {
  15747. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  15748. }
  15749. else {
  15750. this._buffer = this._engine.createVertexBuffer(data);
  15751. }
  15752. }
  15753. if (this._updatable) {
  15754. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  15755. this._data = data;
  15756. }
  15757. };
  15758. VertexBuffer.prototype.update = function (data) {
  15759. this.create(data);
  15760. };
  15761. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  15762. if (!this._buffer) {
  15763. return;
  15764. }
  15765. if (this._updatable) {
  15766. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  15767. this._data = null;
  15768. }
  15769. };
  15770. VertexBuffer.prototype.dispose = function () {
  15771. if (!this._buffer) {
  15772. return;
  15773. }
  15774. if (this._engine._releaseBuffer(this._buffer)) {
  15775. this._buffer = null;
  15776. }
  15777. };
  15778. Object.defineProperty(VertexBuffer, "PositionKind", {
  15779. get: function () {
  15780. return VertexBuffer._PositionKind;
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(VertexBuffer, "NormalKind", {
  15786. get: function () {
  15787. return VertexBuffer._NormalKind;
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. Object.defineProperty(VertexBuffer, "UVKind", {
  15793. get: function () {
  15794. return VertexBuffer._UVKind;
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. Object.defineProperty(VertexBuffer, "UV2Kind", {
  15800. get: function () {
  15801. return VertexBuffer._UV2Kind;
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(VertexBuffer, "UV3Kind", {
  15807. get: function () {
  15808. return VertexBuffer._UV3Kind;
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. Object.defineProperty(VertexBuffer, "UV4Kind", {
  15814. get: function () {
  15815. return VertexBuffer._UV4Kind;
  15816. },
  15817. enumerable: true,
  15818. configurable: true
  15819. });
  15820. Object.defineProperty(VertexBuffer, "UV5Kind", {
  15821. get: function () {
  15822. return VertexBuffer._UV5Kind;
  15823. },
  15824. enumerable: true,
  15825. configurable: true
  15826. });
  15827. Object.defineProperty(VertexBuffer, "UV6Kind", {
  15828. get: function () {
  15829. return VertexBuffer._UV6Kind;
  15830. },
  15831. enumerable: true,
  15832. configurable: true
  15833. });
  15834. Object.defineProperty(VertexBuffer, "ColorKind", {
  15835. get: function () {
  15836. return VertexBuffer._ColorKind;
  15837. },
  15838. enumerable: true,
  15839. configurable: true
  15840. });
  15841. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  15842. get: function () {
  15843. return VertexBuffer._MatricesIndicesKind;
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  15849. get: function () {
  15850. return VertexBuffer._MatricesWeightsKind;
  15851. },
  15852. enumerable: true,
  15853. configurable: true
  15854. });
  15855. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  15856. get: function () {
  15857. return VertexBuffer._MatricesIndicesExtraKind;
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  15863. get: function () {
  15864. return VertexBuffer._MatricesWeightsExtraKind;
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. // Enums
  15870. VertexBuffer._PositionKind = "position";
  15871. VertexBuffer._NormalKind = "normal";
  15872. VertexBuffer._UVKind = "uv";
  15873. VertexBuffer._UV2Kind = "uv2";
  15874. VertexBuffer._UV3Kind = "uv3";
  15875. VertexBuffer._UV4Kind = "uv4";
  15876. VertexBuffer._UV5Kind = "uv5";
  15877. VertexBuffer._UV6Kind = "uv6";
  15878. VertexBuffer._ColorKind = "color";
  15879. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  15880. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  15881. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  15882. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  15883. return VertexBuffer;
  15884. })();
  15885. BABYLON.VertexBuffer = VertexBuffer;
  15886. })(BABYLON || (BABYLON = {}));
  15887. var BABYLON;
  15888. (function (BABYLON) {
  15889. /**
  15890. * Creates an instance based on a source mesh.
  15891. */
  15892. var InstancedMesh = (function (_super) {
  15893. __extends(InstancedMesh, _super);
  15894. function InstancedMesh(name, source) {
  15895. _super.call(this, name, source.getScene());
  15896. source.instances.push(this);
  15897. this._sourceMesh = source;
  15898. this.position.copyFrom(source.position);
  15899. this.rotation.copyFrom(source.rotation);
  15900. this.scaling.copyFrom(source.scaling);
  15901. if (source.rotationQuaternion) {
  15902. this.rotationQuaternion = source.rotationQuaternion.clone();
  15903. }
  15904. this.infiniteDistance = source.infiniteDistance;
  15905. this.setPivotMatrix(source.getPivotMatrix());
  15906. this.refreshBoundingInfo();
  15907. this._syncSubMeshes();
  15908. }
  15909. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  15910. // Methods
  15911. get: function () {
  15912. return this._sourceMesh.receiveShadows;
  15913. },
  15914. enumerable: true,
  15915. configurable: true
  15916. });
  15917. Object.defineProperty(InstancedMesh.prototype, "material", {
  15918. get: function () {
  15919. return this._sourceMesh.material;
  15920. },
  15921. enumerable: true,
  15922. configurable: true
  15923. });
  15924. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  15925. get: function () {
  15926. return this._sourceMesh.visibility;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  15932. get: function () {
  15933. return this._sourceMesh.skeleton;
  15934. },
  15935. enumerable: true,
  15936. configurable: true
  15937. });
  15938. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  15939. get: function () {
  15940. return this._sourceMesh.renderingGroupId;
  15941. },
  15942. enumerable: true,
  15943. configurable: true
  15944. });
  15945. InstancedMesh.prototype.getTotalVertices = function () {
  15946. return this._sourceMesh.getTotalVertices();
  15947. };
  15948. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  15949. get: function () {
  15950. return this._sourceMesh;
  15951. },
  15952. enumerable: true,
  15953. configurable: true
  15954. });
  15955. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15956. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  15957. };
  15958. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  15959. return this._sourceMesh.isVerticesDataPresent(kind);
  15960. };
  15961. InstancedMesh.prototype.getIndices = function () {
  15962. return this._sourceMesh.getIndices();
  15963. };
  15964. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  15965. get: function () {
  15966. return this._sourceMesh._positions;
  15967. },
  15968. enumerable: true,
  15969. configurable: true
  15970. });
  15971. InstancedMesh.prototype.refreshBoundingInfo = function () {
  15972. var meshBB = this._sourceMesh.getBoundingInfo();
  15973. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  15974. this._updateBoundingInfo();
  15975. };
  15976. InstancedMesh.prototype._preActivate = function () {
  15977. if (this._currentLOD) {
  15978. this._currentLOD._preActivate();
  15979. }
  15980. };
  15981. InstancedMesh.prototype._activate = function (renderId) {
  15982. if (this._currentLOD) {
  15983. this._currentLOD._registerInstanceForRenderId(this, renderId);
  15984. }
  15985. };
  15986. InstancedMesh.prototype.getLOD = function (camera) {
  15987. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  15988. if (this._currentLOD === this.sourceMesh) {
  15989. return this;
  15990. }
  15991. return this._currentLOD;
  15992. };
  15993. InstancedMesh.prototype._syncSubMeshes = function () {
  15994. this.releaseSubMeshes();
  15995. if (this._sourceMesh.subMeshes) {
  15996. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15997. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15998. }
  15999. }
  16000. };
  16001. InstancedMesh.prototype._generatePointsArray = function () {
  16002. return this._sourceMesh._generatePointsArray();
  16003. };
  16004. // Clone
  16005. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16006. var result = this._sourceMesh.createInstance(name);
  16007. // Deep copy
  16008. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16009. // Bounding info
  16010. this.refreshBoundingInfo();
  16011. // Parent
  16012. if (newParent) {
  16013. result.parent = newParent;
  16014. }
  16015. if (!doNotCloneChildren) {
  16016. // Children
  16017. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16018. var mesh = this.getScene().meshes[index];
  16019. if (mesh.parent === this) {
  16020. mesh.clone(mesh.name, result);
  16021. }
  16022. }
  16023. }
  16024. result.computeWorldMatrix(true);
  16025. return result;
  16026. };
  16027. // Dispoe
  16028. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16029. // Remove from mesh
  16030. var index = this._sourceMesh.instances.indexOf(this);
  16031. this._sourceMesh.instances.splice(index, 1);
  16032. _super.prototype.dispose.call(this, doNotRecurse);
  16033. };
  16034. return InstancedMesh;
  16035. })(BABYLON.AbstractMesh);
  16036. BABYLON.InstancedMesh = InstancedMesh;
  16037. })(BABYLON || (BABYLON = {}));
  16038. var BABYLON;
  16039. (function (BABYLON) {
  16040. var _InstancesBatch = (function () {
  16041. function _InstancesBatch() {
  16042. this.mustReturn = false;
  16043. this.visibleInstances = new Array();
  16044. this.renderSelf = new Array();
  16045. }
  16046. return _InstancesBatch;
  16047. })();
  16048. BABYLON._InstancesBatch = _InstancesBatch;
  16049. var Mesh = (function (_super) {
  16050. __extends(Mesh, _super);
  16051. /**
  16052. * @constructor
  16053. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16054. * @param {Scene} scene - The scene to add this mesh to.
  16055. * @param {Node} parent - The parent of this mesh, if it has one
  16056. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16057. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16058. * When false, achieved by calling a clone(), also passing False.
  16059. * This will make creation of children, recursive.
  16060. */
  16061. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  16062. if (parent === void 0) { parent = null; }
  16063. _super.call(this, name, scene);
  16064. // Members
  16065. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16066. this.instances = new Array();
  16067. this._LODLevels = new Array();
  16068. this._onBeforeRenderCallbacks = new Array();
  16069. this._onAfterRenderCallbacks = new Array();
  16070. this._visibleInstances = {};
  16071. this._renderIdForInstances = new Array();
  16072. this._batchCache = new _InstancesBatch();
  16073. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16074. this._sideOrientation = Mesh._DEFAULTSIDE;
  16075. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16076. if (source) {
  16077. // Geometry
  16078. if (source._geometry) {
  16079. source._geometry.applyToMesh(this);
  16080. }
  16081. // Deep copy
  16082. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16083. // Pivot
  16084. this.setPivotMatrix(source.getPivotMatrix());
  16085. this.id = name + "." + source.id;
  16086. // Material
  16087. this.material = source.material;
  16088. var index;
  16089. if (!doNotCloneChildren) {
  16090. // Children
  16091. for (index = 0; index < scene.meshes.length; index++) {
  16092. var mesh = scene.meshes[index];
  16093. if (mesh.parent === source) {
  16094. // doNotCloneChildren is always going to be False
  16095. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16096. }
  16097. }
  16098. }
  16099. // Particles
  16100. for (index = 0; index < scene.particleSystems.length; index++) {
  16101. var system = scene.particleSystems[index];
  16102. if (system.emitter === source) {
  16103. system.clone(system.name, this);
  16104. }
  16105. }
  16106. this.computeWorldMatrix(true);
  16107. }
  16108. // Parent
  16109. if (parent !== null) {
  16110. this.parent = parent;
  16111. }
  16112. }
  16113. Object.defineProperty(Mesh, "FRONTSIDE", {
  16114. get: function () {
  16115. return Mesh._FRONTSIDE;
  16116. },
  16117. enumerable: true,
  16118. configurable: true
  16119. });
  16120. Object.defineProperty(Mesh, "BACKSIDE", {
  16121. get: function () {
  16122. return Mesh._BACKSIDE;
  16123. },
  16124. enumerable: true,
  16125. configurable: true
  16126. });
  16127. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16128. get: function () {
  16129. return Mesh._DOUBLESIDE;
  16130. },
  16131. enumerable: true,
  16132. configurable: true
  16133. });
  16134. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16135. get: function () {
  16136. return Mesh._DEFAULTSIDE;
  16137. },
  16138. enumerable: true,
  16139. configurable: true
  16140. });
  16141. Object.defineProperty(Mesh, "NO_CAP", {
  16142. get: function () {
  16143. return Mesh._NO_CAP;
  16144. },
  16145. enumerable: true,
  16146. configurable: true
  16147. });
  16148. Object.defineProperty(Mesh, "CAP_START", {
  16149. get: function () {
  16150. return Mesh._CAP_START;
  16151. },
  16152. enumerable: true,
  16153. configurable: true
  16154. });
  16155. Object.defineProperty(Mesh, "CAP_END", {
  16156. get: function () {
  16157. return Mesh._CAP_END;
  16158. },
  16159. enumerable: true,
  16160. configurable: true
  16161. });
  16162. Object.defineProperty(Mesh, "CAP_ALL", {
  16163. get: function () {
  16164. return Mesh._CAP_ALL;
  16165. },
  16166. enumerable: true,
  16167. configurable: true
  16168. });
  16169. // Methods
  16170. /**
  16171. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16172. */
  16173. Mesh.prototype.toString = function (fullDetails) {
  16174. var ret = _super.prototype.toString.call(this, fullDetails);
  16175. ret += ", n vertices: " + this.getTotalVertices();
  16176. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16177. if (this.animations) {
  16178. for (var i = 0; i < this.animations.length; i++) {
  16179. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16180. }
  16181. }
  16182. if (fullDetails) {
  16183. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16184. }
  16185. return ret;
  16186. };
  16187. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16188. get: function () {
  16189. return this._LODLevels.length > 0;
  16190. },
  16191. enumerable: true,
  16192. configurable: true
  16193. });
  16194. Mesh.prototype._sortLODLevels = function () {
  16195. this._LODLevels.sort(function (a, b) {
  16196. if (a.distance < b.distance) {
  16197. return 1;
  16198. }
  16199. if (a.distance > b.distance) {
  16200. return -1;
  16201. }
  16202. return 0;
  16203. });
  16204. };
  16205. /**
  16206. * Add a mesh as LOD level triggered at the given distance.
  16207. * @param {number} distance - the distance from the center of the object to show this level
  16208. * @param {Mesh} mesh - the mesh to be added as LOD level
  16209. * @return {Mesh} this mesh (for chaining)
  16210. */
  16211. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16212. if (mesh && mesh._masterMesh) {
  16213. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16214. return this;
  16215. }
  16216. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16217. this._LODLevels.push(level);
  16218. if (mesh) {
  16219. mesh._masterMesh = this;
  16220. }
  16221. this._sortLODLevels();
  16222. return this;
  16223. };
  16224. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16225. for (var index = 0; index < this._LODLevels.length; index++) {
  16226. var level = this._LODLevels[index];
  16227. if (level.distance === distance) {
  16228. return level.mesh;
  16229. }
  16230. }
  16231. return null;
  16232. };
  16233. /**
  16234. * Remove a mesh from the LOD array
  16235. * @param {Mesh} mesh - the mesh to be removed.
  16236. * @return {Mesh} this mesh (for chaining)
  16237. */
  16238. Mesh.prototype.removeLODLevel = function (mesh) {
  16239. for (var index = 0; index < this._LODLevels.length; index++) {
  16240. if (this._LODLevels[index].mesh === mesh) {
  16241. this._LODLevels.splice(index, 1);
  16242. if (mesh) {
  16243. mesh._masterMesh = null;
  16244. }
  16245. }
  16246. }
  16247. this._sortLODLevels();
  16248. return this;
  16249. };
  16250. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16251. if (!this._LODLevels || this._LODLevels.length === 0) {
  16252. return this;
  16253. }
  16254. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  16255. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16256. if (this.onLODLevelSelection) {
  16257. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16258. }
  16259. return this;
  16260. }
  16261. for (var index = 0; index < this._LODLevels.length; index++) {
  16262. var level = this._LODLevels[index];
  16263. if (level.distance < distanceToCamera) {
  16264. if (level.mesh) {
  16265. level.mesh._preActivate();
  16266. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16267. }
  16268. if (this.onLODLevelSelection) {
  16269. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16270. }
  16271. return level.mesh;
  16272. }
  16273. }
  16274. if (this.onLODLevelSelection) {
  16275. this.onLODLevelSelection(distanceToCamera, this, this);
  16276. }
  16277. return this;
  16278. };
  16279. Object.defineProperty(Mesh.prototype, "geometry", {
  16280. get: function () {
  16281. return this._geometry;
  16282. },
  16283. enumerable: true,
  16284. configurable: true
  16285. });
  16286. Mesh.prototype.getTotalVertices = function () {
  16287. if (!this._geometry) {
  16288. return 0;
  16289. }
  16290. return this._geometry.getTotalVertices();
  16291. };
  16292. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16293. if (!this._geometry) {
  16294. return null;
  16295. }
  16296. return this._geometry.getVerticesData(kind, copyWhenShared);
  16297. };
  16298. Mesh.prototype.getVertexBuffer = function (kind) {
  16299. if (!this._geometry) {
  16300. return undefined;
  16301. }
  16302. return this._geometry.getVertexBuffer(kind);
  16303. };
  16304. Mesh.prototype.isVerticesDataPresent = function (kind) {
  16305. if (!this._geometry) {
  16306. if (this._delayInfo) {
  16307. return this._delayInfo.indexOf(kind) !== -1;
  16308. }
  16309. return false;
  16310. }
  16311. return this._geometry.isVerticesDataPresent(kind);
  16312. };
  16313. Mesh.prototype.getVerticesDataKinds = function () {
  16314. if (!this._geometry) {
  16315. var result = [];
  16316. if (this._delayInfo) {
  16317. for (var kind in this._delayInfo) {
  16318. result.push(kind);
  16319. }
  16320. }
  16321. return result;
  16322. }
  16323. return this._geometry.getVerticesDataKinds();
  16324. };
  16325. Mesh.prototype.getTotalIndices = function () {
  16326. if (!this._geometry) {
  16327. return 0;
  16328. }
  16329. return this._geometry.getTotalIndices();
  16330. };
  16331. Mesh.prototype.getIndices = function (copyWhenShared) {
  16332. if (!this._geometry) {
  16333. return [];
  16334. }
  16335. return this._geometry.getIndices(copyWhenShared);
  16336. };
  16337. Object.defineProperty(Mesh.prototype, "isBlocked", {
  16338. get: function () {
  16339. return this._masterMesh !== null && this._masterMesh !== undefined;
  16340. },
  16341. enumerable: true,
  16342. configurable: true
  16343. });
  16344. Mesh.prototype.isReady = function () {
  16345. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16346. return false;
  16347. }
  16348. return _super.prototype.isReady.call(this);
  16349. };
  16350. Mesh.prototype.isDisposed = function () {
  16351. return this._isDisposed;
  16352. };
  16353. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  16354. get: function () {
  16355. return this._sideOrientation;
  16356. },
  16357. set: function (sideO) {
  16358. this._sideOrientation = sideO;
  16359. },
  16360. enumerable: true,
  16361. configurable: true
  16362. });
  16363. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  16364. get: function () {
  16365. return this._areNormalsFrozen;
  16366. },
  16367. enumerable: true,
  16368. configurable: true
  16369. });
  16370. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  16371. Mesh.prototype.freezeNormals = function () {
  16372. this._areNormalsFrozen = true;
  16373. };
  16374. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  16375. Mesh.prototype.unfreezeNormals = function () {
  16376. this._areNormalsFrozen = false;
  16377. };
  16378. // Methods
  16379. Mesh.prototype._preActivate = function () {
  16380. var sceneRenderId = this.getScene().getRenderId();
  16381. if (this._preActivateId === sceneRenderId) {
  16382. return;
  16383. }
  16384. this._preActivateId = sceneRenderId;
  16385. this._visibleInstances = null;
  16386. };
  16387. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  16388. if (!this._visibleInstances) {
  16389. this._visibleInstances = {};
  16390. this._visibleInstances.defaultRenderId = renderId;
  16391. this._visibleInstances.selfDefaultRenderId = this._renderId;
  16392. }
  16393. if (!this._visibleInstances[renderId]) {
  16394. this._visibleInstances[renderId] = new Array();
  16395. }
  16396. this._visibleInstances[renderId].push(instance);
  16397. };
  16398. Mesh.prototype.refreshBoundingInfo = function () {
  16399. if (this._boundingInfo.isLocked) {
  16400. return;
  16401. }
  16402. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16403. if (data) {
  16404. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  16405. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16406. }
  16407. if (this.subMeshes) {
  16408. for (var index = 0; index < this.subMeshes.length; index++) {
  16409. this.subMeshes[index].refreshBoundingInfo();
  16410. }
  16411. }
  16412. this._updateBoundingInfo();
  16413. };
  16414. Mesh.prototype._createGlobalSubMesh = function () {
  16415. var totalVertices = this.getTotalVertices();
  16416. if (!totalVertices || !this.getIndices()) {
  16417. return null;
  16418. }
  16419. this.releaseSubMeshes();
  16420. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  16421. };
  16422. Mesh.prototype.subdivide = function (count) {
  16423. if (count < 1) {
  16424. return;
  16425. }
  16426. var totalIndices = this.getTotalIndices();
  16427. var subdivisionSize = (totalIndices / count) | 0;
  16428. var offset = 0;
  16429. // Ensure that subdivisionSize is a multiple of 3
  16430. while (subdivisionSize % 3 !== 0) {
  16431. subdivisionSize++;
  16432. }
  16433. this.releaseSubMeshes();
  16434. for (var index = 0; index < count; index++) {
  16435. if (offset >= totalIndices) {
  16436. break;
  16437. }
  16438. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  16439. offset += subdivisionSize;
  16440. }
  16441. this.synchronizeInstances();
  16442. };
  16443. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16444. if (!this._geometry) {
  16445. var vertexData = new BABYLON.VertexData();
  16446. vertexData.set(data, kind);
  16447. var scene = this.getScene();
  16448. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  16449. }
  16450. else {
  16451. this._geometry.setVerticesData(kind, data, updatable, stride);
  16452. }
  16453. };
  16454. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16455. if (!this._geometry) {
  16456. return;
  16457. }
  16458. if (!makeItUnique) {
  16459. this._geometry.updateVerticesData(kind, data, updateExtends);
  16460. }
  16461. else {
  16462. this.makeGeometryUnique();
  16463. this.updateVerticesData(kind, data, updateExtends, false);
  16464. }
  16465. };
  16466. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  16467. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  16468. if (!this._geometry) {
  16469. return;
  16470. }
  16471. if (!makeItUnique) {
  16472. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  16473. }
  16474. else {
  16475. this.makeGeometryUnique();
  16476. this.updateVerticesDataDirectly(kind, data, offset, false);
  16477. }
  16478. };
  16479. // Mesh positions update function :
  16480. // updates the mesh positions according to the positionFunction returned values.
  16481. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  16482. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  16483. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  16484. if (computeNormals === void 0) { computeNormals = true; }
  16485. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16486. positionFunction(positions);
  16487. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16488. if (computeNormals) {
  16489. var indices = this.getIndices();
  16490. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16491. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16492. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16493. }
  16494. };
  16495. Mesh.prototype.makeGeometryUnique = function () {
  16496. if (!this._geometry) {
  16497. return;
  16498. }
  16499. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  16500. geometry.applyToMesh(this);
  16501. };
  16502. Mesh.prototype.setIndices = function (indices, totalVertices) {
  16503. if (!this._geometry) {
  16504. var vertexData = new BABYLON.VertexData();
  16505. vertexData.indices = indices;
  16506. var scene = this.getScene();
  16507. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  16508. }
  16509. else {
  16510. this._geometry.setIndices(indices, totalVertices);
  16511. }
  16512. };
  16513. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  16514. var engine = this.getScene().getEngine();
  16515. // Wireframe
  16516. var indexToBind;
  16517. if (this._unIndexed) {
  16518. indexToBind = null;
  16519. }
  16520. else {
  16521. switch (fillMode) {
  16522. case BABYLON.Material.PointFillMode:
  16523. indexToBind = null;
  16524. break;
  16525. case BABYLON.Material.WireFrameFillMode:
  16526. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  16527. break;
  16528. default:
  16529. case BABYLON.Material.TriangleFillMode:
  16530. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  16531. break;
  16532. }
  16533. }
  16534. // VBOs
  16535. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  16536. };
  16537. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  16538. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16539. return;
  16540. }
  16541. if (this.onBeforeDraw) {
  16542. this.onBeforeDraw();
  16543. }
  16544. var engine = this.getScene().getEngine();
  16545. // Draw order
  16546. switch (fillMode) {
  16547. case BABYLON.Material.PointFillMode:
  16548. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16549. break;
  16550. case BABYLON.Material.WireFrameFillMode:
  16551. if (this._unIndexed) {
  16552. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16553. }
  16554. else {
  16555. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  16556. }
  16557. break;
  16558. default:
  16559. if (this._unIndexed) {
  16560. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16561. }
  16562. else {
  16563. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  16564. }
  16565. }
  16566. };
  16567. Mesh.prototype.registerBeforeRender = function (func) {
  16568. this._onBeforeRenderCallbacks.push(func);
  16569. };
  16570. Mesh.prototype.unregisterBeforeRender = function (func) {
  16571. var index = this._onBeforeRenderCallbacks.indexOf(func);
  16572. if (index > -1) {
  16573. this._onBeforeRenderCallbacks.splice(index, 1);
  16574. }
  16575. };
  16576. Mesh.prototype.registerAfterRender = function (func) {
  16577. this._onAfterRenderCallbacks.push(func);
  16578. };
  16579. Mesh.prototype.unregisterAfterRender = function (func) {
  16580. var index = this._onAfterRenderCallbacks.indexOf(func);
  16581. if (index > -1) {
  16582. this._onAfterRenderCallbacks.splice(index, 1);
  16583. }
  16584. };
  16585. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  16586. var scene = this.getScene();
  16587. this._batchCache.mustReturn = false;
  16588. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  16589. this._batchCache.visibleInstances[subMeshId] = null;
  16590. if (this._visibleInstances) {
  16591. var currentRenderId = scene.getRenderId();
  16592. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  16593. var selfRenderId = this._renderId;
  16594. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  16595. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  16596. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  16597. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  16598. }
  16599. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  16600. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  16601. this._batchCache.mustReturn = true;
  16602. return this._batchCache;
  16603. }
  16604. if (currentRenderId !== selfRenderId) {
  16605. this._batchCache.renderSelf[subMeshId] = false;
  16606. }
  16607. }
  16608. this._renderIdForInstances[subMeshId] = currentRenderId;
  16609. }
  16610. return this._batchCache;
  16611. };
  16612. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  16613. var visibleInstances = batch.visibleInstances[subMesh._id];
  16614. var matricesCount = visibleInstances.length + 1;
  16615. var bufferSize = matricesCount * 16 * 4;
  16616. while (this._instancesBufferSize < bufferSize) {
  16617. this._instancesBufferSize *= 2;
  16618. }
  16619. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  16620. if (this._worldMatricesInstancesBuffer) {
  16621. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  16622. }
  16623. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  16624. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  16625. }
  16626. var offset = 0;
  16627. var instancesCount = 0;
  16628. var world = this.getWorldMatrix();
  16629. if (batch.renderSelf[subMesh._id]) {
  16630. world.copyToArray(this._worldMatricesInstancesArray, offset);
  16631. offset += 16;
  16632. instancesCount++;
  16633. }
  16634. if (visibleInstances) {
  16635. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  16636. var instance = visibleInstances[instanceIndex];
  16637. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  16638. offset += 16;
  16639. instancesCount++;
  16640. }
  16641. }
  16642. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  16643. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  16644. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  16645. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  16646. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  16647. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  16648. this._draw(subMesh, fillMode, instancesCount);
  16649. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  16650. };
  16651. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  16652. var scene = this.getScene();
  16653. var engine = scene.getEngine();
  16654. if (hardwareInstancedRendering) {
  16655. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  16656. }
  16657. else {
  16658. if (batch.renderSelf[subMesh._id]) {
  16659. // Draw
  16660. if (onBeforeDraw) {
  16661. onBeforeDraw(false, this.getWorldMatrix());
  16662. }
  16663. this._draw(subMesh, fillMode);
  16664. }
  16665. if (batch.visibleInstances[subMesh._id]) {
  16666. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  16667. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  16668. // World
  16669. var world = instance.getWorldMatrix();
  16670. if (onBeforeDraw) {
  16671. onBeforeDraw(true, world);
  16672. }
  16673. // Draw
  16674. this._draw(subMesh, fillMode);
  16675. }
  16676. }
  16677. }
  16678. };
  16679. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  16680. var scene = this.getScene();
  16681. // Managing instances
  16682. var batch = this._getInstancesRenderList(subMesh._id);
  16683. if (batch.mustReturn) {
  16684. return;
  16685. }
  16686. // Checking geometry state
  16687. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16688. return;
  16689. }
  16690. var callbackIndex;
  16691. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  16692. this._onBeforeRenderCallbacks[callbackIndex](this);
  16693. }
  16694. var engine = scene.getEngine();
  16695. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  16696. // Material
  16697. var effectiveMaterial = subMesh.getMaterial();
  16698. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  16699. return;
  16700. }
  16701. // Outline - step 1
  16702. var savedDepthWrite = engine.getDepthWrite();
  16703. if (this.renderOutline) {
  16704. engine.setDepthWrite(false);
  16705. scene.getOutlineRenderer().render(subMesh, batch);
  16706. engine.setDepthWrite(savedDepthWrite);
  16707. }
  16708. effectiveMaterial._preBind();
  16709. var effect = effectiveMaterial.getEffect();
  16710. // Bind
  16711. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  16712. this._bind(subMesh, effect, fillMode);
  16713. var world = this.getWorldMatrix();
  16714. effectiveMaterial.bind(world, this);
  16715. // Alpha mode
  16716. if (enableAlphaMode) {
  16717. engine.setAlphaMode(effectiveMaterial.alphaMode);
  16718. }
  16719. // Draw
  16720. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  16721. if (isInstance) {
  16722. effectiveMaterial.bindOnlyWorldMatrix(world);
  16723. }
  16724. });
  16725. // Unbind
  16726. effectiveMaterial.unbind();
  16727. // Outline - step 2
  16728. if (this.renderOutline && savedDepthWrite) {
  16729. engine.setDepthWrite(true);
  16730. engine.setColorWrite(false);
  16731. scene.getOutlineRenderer().render(subMesh, batch);
  16732. engine.setColorWrite(true);
  16733. }
  16734. // Overlay
  16735. if (this.renderOverlay) {
  16736. var currentMode = engine.getAlphaMode();
  16737. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16738. scene.getOutlineRenderer().render(subMesh, batch, true);
  16739. engine.setAlphaMode(currentMode);
  16740. }
  16741. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  16742. this._onAfterRenderCallbacks[callbackIndex](this);
  16743. }
  16744. };
  16745. Mesh.prototype.getEmittedParticleSystems = function () {
  16746. var results = new Array();
  16747. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  16748. var particleSystem = this.getScene().particleSystems[index];
  16749. if (particleSystem.emitter === this) {
  16750. results.push(particleSystem);
  16751. }
  16752. }
  16753. return results;
  16754. };
  16755. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  16756. var results = new Array();
  16757. var descendants = this.getDescendants();
  16758. descendants.push(this);
  16759. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  16760. var particleSystem = this.getScene().particleSystems[index];
  16761. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  16762. results.push(particleSystem);
  16763. }
  16764. }
  16765. return results;
  16766. };
  16767. Mesh.prototype._checkDelayState = function () {
  16768. var _this = this;
  16769. var that = this;
  16770. var scene = this.getScene();
  16771. if (this._geometry) {
  16772. this._geometry.load(scene);
  16773. }
  16774. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16775. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  16776. scene._addPendingData(that);
  16777. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  16778. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  16779. if (data instanceof ArrayBuffer) {
  16780. _this._delayLoadingFunction(data, _this);
  16781. }
  16782. else {
  16783. _this._delayLoadingFunction(JSON.parse(data), _this);
  16784. }
  16785. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16786. scene._removePendingData(_this);
  16787. }, function () { }, scene.database, getBinaryData);
  16788. }
  16789. };
  16790. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  16791. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16792. return false;
  16793. }
  16794. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  16795. return false;
  16796. }
  16797. this._checkDelayState();
  16798. return true;
  16799. };
  16800. Mesh.prototype.setMaterialByID = function (id) {
  16801. var materials = this.getScene().materials;
  16802. var index;
  16803. for (index = 0; index < materials.length; index++) {
  16804. if (materials[index].id === id) {
  16805. this.material = materials[index];
  16806. return;
  16807. }
  16808. }
  16809. // Multi
  16810. var multiMaterials = this.getScene().multiMaterials;
  16811. for (index = 0; index < multiMaterials.length; index++) {
  16812. if (multiMaterials[index].id === id) {
  16813. this.material = multiMaterials[index];
  16814. return;
  16815. }
  16816. }
  16817. };
  16818. Mesh.prototype.getAnimatables = function () {
  16819. var results = [];
  16820. if (this.material) {
  16821. results.push(this.material);
  16822. }
  16823. if (this.skeleton) {
  16824. results.push(this.skeleton);
  16825. }
  16826. return results;
  16827. };
  16828. // Geometry
  16829. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  16830. // Position
  16831. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16832. return;
  16833. }
  16834. this._resetPointsArrayCache();
  16835. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16836. var temp = [];
  16837. var index;
  16838. for (index = 0; index < data.length; index += 3) {
  16839. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  16840. }
  16841. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  16842. // Normals
  16843. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16844. return;
  16845. }
  16846. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16847. temp = [];
  16848. for (index = 0; index < data.length; index += 3) {
  16849. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  16850. }
  16851. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  16852. // flip faces?
  16853. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  16854. this.flipFaces();
  16855. }
  16856. };
  16857. // Will apply current transform to mesh and reset world matrix
  16858. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  16859. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  16860. this.scaling.copyFromFloats(1, 1, 1);
  16861. this.position.copyFromFloats(0, 0, 0);
  16862. this.rotation.copyFromFloats(0, 0, 0);
  16863. //only if quaternion is already set
  16864. if (this.rotationQuaternion) {
  16865. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  16866. }
  16867. this._worldMatrix = BABYLON.Matrix.Identity();
  16868. };
  16869. // Cache
  16870. Mesh.prototype._resetPointsArrayCache = function () {
  16871. this._positions = null;
  16872. };
  16873. Mesh.prototype._generatePointsArray = function () {
  16874. if (this._positions)
  16875. return true;
  16876. this._positions = [];
  16877. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16878. if (!data) {
  16879. return false;
  16880. }
  16881. for (var index = 0; index < data.length; index += 3) {
  16882. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  16883. }
  16884. return true;
  16885. };
  16886. // Clone
  16887. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16888. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  16889. };
  16890. // Dispose
  16891. Mesh.prototype.dispose = function (doNotRecurse) {
  16892. if (this._geometry) {
  16893. this._geometry.releaseForMesh(this, true);
  16894. }
  16895. // Instances
  16896. if (this._worldMatricesInstancesBuffer) {
  16897. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  16898. this._worldMatricesInstancesBuffer = null;
  16899. }
  16900. while (this.instances.length) {
  16901. this.instances[0].dispose();
  16902. }
  16903. _super.prototype.dispose.call(this, doNotRecurse);
  16904. };
  16905. // Geometric tools
  16906. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  16907. var _this = this;
  16908. var scene = this.getScene();
  16909. var onload = function (img) {
  16910. // Getting height map data
  16911. var canvas = document.createElement("canvas");
  16912. var context = canvas.getContext("2d");
  16913. var heightMapWidth = img.width;
  16914. var heightMapHeight = img.height;
  16915. canvas.width = heightMapWidth;
  16916. canvas.height = heightMapHeight;
  16917. context.drawImage(img, 0, 0);
  16918. // Create VertexData from map data
  16919. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16920. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  16921. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  16922. //execute success callback, if set
  16923. if (onSuccess) {
  16924. onSuccess(_this);
  16925. }
  16926. };
  16927. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16928. };
  16929. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  16930. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  16931. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  16932. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16933. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  16934. return;
  16935. }
  16936. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16937. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16938. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16939. var position = BABYLON.Vector3.Zero();
  16940. var normal = BABYLON.Vector3.Zero();
  16941. var uv = BABYLON.Vector2.Zero();
  16942. for (var index = 0; index < positions.length; index += 3) {
  16943. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  16944. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  16945. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  16946. // Compute height
  16947. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  16948. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  16949. var pos = (u + v * heightMapWidth) * 4;
  16950. var r = buffer[pos] / 255.0;
  16951. var g = buffer[pos + 1] / 255.0;
  16952. var b = buffer[pos + 2] / 255.0;
  16953. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16954. normal.normalize();
  16955. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  16956. position = position.add(normal);
  16957. position.toArray(positions, index);
  16958. }
  16959. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  16960. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  16961. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16962. };
  16963. Mesh.prototype.convertToFlatShadedMesh = function () {
  16964. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  16965. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16966. var kinds = this.getVerticesDataKinds();
  16967. var vbs = [];
  16968. var data = [];
  16969. var newdata = [];
  16970. var updatableNormals = false;
  16971. var kindIndex;
  16972. var kind;
  16973. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16974. kind = kinds[kindIndex];
  16975. var vertexBuffer = this.getVertexBuffer(kind);
  16976. if (kind === BABYLON.VertexBuffer.NormalKind) {
  16977. updatableNormals = vertexBuffer.isUpdatable();
  16978. kinds.splice(kindIndex, 1);
  16979. kindIndex--;
  16980. continue;
  16981. }
  16982. vbs[kind] = vertexBuffer;
  16983. data[kind] = vbs[kind].getData();
  16984. newdata[kind] = [];
  16985. }
  16986. // Save previous submeshes
  16987. var previousSubmeshes = this.subMeshes.slice(0);
  16988. var indices = this.getIndices();
  16989. var totalIndices = this.getTotalIndices();
  16990. // Generating unique vertices per face
  16991. var index;
  16992. for (index = 0; index < totalIndices; index++) {
  16993. var vertexIndex = indices[index];
  16994. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16995. kind = kinds[kindIndex];
  16996. var stride = vbs[kind].getStrideSize();
  16997. for (var offset = 0; offset < stride; offset++) {
  16998. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16999. }
  17000. }
  17001. }
  17002. // Updating faces & normal
  17003. var normals = [];
  17004. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17005. for (index = 0; index < totalIndices; index += 3) {
  17006. indices[index] = index;
  17007. indices[index + 1] = index + 1;
  17008. indices[index + 2] = index + 2;
  17009. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17010. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17011. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17012. var p1p2 = p1.subtract(p2);
  17013. var p3p2 = p3.subtract(p2);
  17014. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17015. // Store same normals for every vertex
  17016. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17017. normals.push(normal.x);
  17018. normals.push(normal.y);
  17019. normals.push(normal.z);
  17020. }
  17021. }
  17022. this.setIndices(indices);
  17023. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17024. // Updating vertex buffers
  17025. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17026. kind = kinds[kindIndex];
  17027. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17028. }
  17029. // Updating submeshes
  17030. this.releaseSubMeshes();
  17031. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17032. var previousOne = previousSubmeshes[submeshIndex];
  17033. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17034. }
  17035. this.synchronizeInstances();
  17036. };
  17037. Mesh.prototype.convertToUnIndexedMesh = function () {
  17038. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17039. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17040. var kinds = this.getVerticesDataKinds();
  17041. var vbs = [];
  17042. var data = [];
  17043. var newdata = [];
  17044. var updatableNormals = false;
  17045. var kindIndex;
  17046. var kind;
  17047. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17048. kind = kinds[kindIndex];
  17049. var vertexBuffer = this.getVertexBuffer(kind);
  17050. vbs[kind] = vertexBuffer;
  17051. data[kind] = vbs[kind].getData();
  17052. newdata[kind] = [];
  17053. }
  17054. // Save previous submeshes
  17055. var previousSubmeshes = this.subMeshes.slice(0);
  17056. var indices = this.getIndices();
  17057. var totalIndices = this.getTotalIndices();
  17058. // Generating unique vertices per face
  17059. var index;
  17060. for (index = 0; index < totalIndices; index++) {
  17061. var vertexIndex = indices[index];
  17062. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17063. kind = kinds[kindIndex];
  17064. var stride = vbs[kind].getStrideSize();
  17065. for (var offset = 0; offset < stride; offset++) {
  17066. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17067. }
  17068. }
  17069. }
  17070. // Updating indices
  17071. for (index = 0; index < totalIndices; index += 3) {
  17072. indices[index] = index;
  17073. indices[index + 1] = index + 1;
  17074. indices[index + 2] = index + 2;
  17075. }
  17076. this.setIndices(indices);
  17077. // Updating vertex buffers
  17078. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17079. kind = kinds[kindIndex];
  17080. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17081. }
  17082. // Updating submeshes
  17083. this.releaseSubMeshes();
  17084. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17085. var previousOne = previousSubmeshes[submeshIndex];
  17086. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17087. }
  17088. this._unIndexed = true;
  17089. this.synchronizeInstances();
  17090. };
  17091. // will inverse faces orientations, and invert normals too if specified
  17092. Mesh.prototype.flipFaces = function (flipNormals) {
  17093. if (flipNormals === void 0) { flipNormals = false; }
  17094. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17095. var i;
  17096. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17097. for (i = 0; i < vertex_data.normals.length; i++) {
  17098. vertex_data.normals[i] *= -1;
  17099. }
  17100. }
  17101. var temp;
  17102. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17103. // reassign indices
  17104. temp = vertex_data.indices[i + 1];
  17105. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17106. vertex_data.indices[i + 2] = temp;
  17107. }
  17108. vertex_data.applyToMesh(this);
  17109. };
  17110. // Instances
  17111. Mesh.prototype.createInstance = function (name) {
  17112. return new BABYLON.InstancedMesh(name, this);
  17113. };
  17114. Mesh.prototype.synchronizeInstances = function () {
  17115. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17116. var instance = this.instances[instanceIndex];
  17117. instance._syncSubMeshes();
  17118. }
  17119. };
  17120. /**
  17121. * Simplify the mesh according to the given array of settings.
  17122. * Function will return immediately and will simplify async.
  17123. * @param settings a collection of simplification settings.
  17124. * @param parallelProcessing should all levels calculate parallel or one after the other.
  17125. * @param type the type of simplification to run.
  17126. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  17127. */
  17128. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  17129. if (parallelProcessing === void 0) { parallelProcessing = true; }
  17130. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  17131. this.getScene().simplificationQueue.addTask({
  17132. settings: settings,
  17133. parallelProcessing: parallelProcessing,
  17134. mesh: this,
  17135. simplificationType: simplificationType,
  17136. successCallback: successCallback
  17137. });
  17138. };
  17139. /**
  17140. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  17141. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  17142. * This should be used together with the simplification to avoid disappearing triangles.
  17143. * @param successCallback an optional success callback to be called after the optimization finished.
  17144. */
  17145. Mesh.prototype.optimizeIndices = function (successCallback) {
  17146. var _this = this;
  17147. var indices = this.getIndices();
  17148. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17149. var vectorPositions = [];
  17150. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  17151. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  17152. }
  17153. var dupes = [];
  17154. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  17155. var realPos = vectorPositions.length - 1 - iteration;
  17156. var testedPosition = vectorPositions[realPos];
  17157. for (var j = 0; j < realPos; ++j) {
  17158. var againstPosition = vectorPositions[j];
  17159. if (testedPosition.equals(againstPosition)) {
  17160. dupes[realPos] = j;
  17161. break;
  17162. }
  17163. }
  17164. }, function () {
  17165. for (var i = 0; i < indices.length; ++i) {
  17166. indices[i] = dupes[indices[i]] || indices[i];
  17167. }
  17168. //indices are now reordered
  17169. var originalSubMeshes = _this.subMeshes.slice(0);
  17170. _this.setIndices(indices);
  17171. _this.subMeshes = originalSubMeshes;
  17172. if (successCallback) {
  17173. successCallback(_this);
  17174. }
  17175. });
  17176. };
  17177. // Statics
  17178. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  17179. var mesh = new Mesh(parsedMesh.name, scene);
  17180. mesh.id = parsedMesh.id;
  17181. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17182. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17183. if (parsedMesh.rotationQuaternion) {
  17184. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17185. }
  17186. else if (parsedMesh.rotation) {
  17187. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17188. }
  17189. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17190. if (parsedMesh.localMatrix) {
  17191. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17192. }
  17193. else if (parsedMesh.pivotMatrix) {
  17194. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17195. }
  17196. mesh.setEnabled(parsedMesh.isEnabled);
  17197. mesh.isVisible = parsedMesh.isVisible;
  17198. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17199. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17200. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17201. if (parsedMesh.applyFog !== undefined) {
  17202. mesh.applyFog = parsedMesh.applyFog;
  17203. }
  17204. if (parsedMesh.pickable !== undefined) {
  17205. mesh.isPickable = parsedMesh.pickable;
  17206. }
  17207. if (parsedMesh.alphaIndex !== undefined) {
  17208. mesh.alphaIndex = parsedMesh.alphaIndex;
  17209. }
  17210. mesh.receiveShadows = parsedMesh.receiveShadows;
  17211. mesh.billboardMode = parsedMesh.billboardMode;
  17212. if (parsedMesh.visibility !== undefined) {
  17213. mesh.visibility = parsedMesh.visibility;
  17214. }
  17215. mesh.checkCollisions = parsedMesh.checkCollisions;
  17216. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17217. // freezeWorldMatrix
  17218. if (parsedMesh.freezeWorldMatrix) {
  17219. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  17220. }
  17221. // Parent
  17222. if (parsedMesh.parentId) {
  17223. mesh._waitingParentId = parsedMesh.parentId;
  17224. }
  17225. // Actions
  17226. if (parsedMesh.actions !== undefined) {
  17227. mesh._waitingActions = parsedMesh.actions;
  17228. }
  17229. // Geometry
  17230. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17231. if (parsedMesh.delayLoadingFile) {
  17232. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17233. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17234. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17235. if (parsedMesh._binaryInfo) {
  17236. mesh._binaryInfo = parsedMesh._binaryInfo;
  17237. }
  17238. mesh._delayInfo = [];
  17239. if (parsedMesh.hasUVs) {
  17240. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17241. }
  17242. if (parsedMesh.hasUVs2) {
  17243. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17244. }
  17245. if (parsedMesh.hasUVs3) {
  17246. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  17247. }
  17248. if (parsedMesh.hasUVs4) {
  17249. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  17250. }
  17251. if (parsedMesh.hasUVs5) {
  17252. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  17253. }
  17254. if (parsedMesh.hasUVs6) {
  17255. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  17256. }
  17257. if (parsedMesh.hasColors) {
  17258. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17259. }
  17260. if (parsedMesh.hasMatricesIndices) {
  17261. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17262. }
  17263. if (parsedMesh.hasMatricesWeights) {
  17264. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17265. }
  17266. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  17267. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17268. mesh._checkDelayState();
  17269. }
  17270. }
  17271. else {
  17272. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  17273. }
  17274. // Material
  17275. if (parsedMesh.materialId) {
  17276. mesh.setMaterialByID(parsedMesh.materialId);
  17277. }
  17278. else {
  17279. mesh.material = null;
  17280. }
  17281. // Skeleton
  17282. if (parsedMesh.skeletonId > -1) {
  17283. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17284. if (parsedMesh.numBoneInfluencers) {
  17285. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  17286. }
  17287. }
  17288. // Animations
  17289. if (parsedMesh.animations) {
  17290. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17291. var parsedAnimation = parsedMesh.animations[animationIndex];
  17292. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17293. }
  17294. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  17295. }
  17296. if (parsedMesh.autoAnimate) {
  17297. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  17298. }
  17299. // Layer Mask
  17300. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17301. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17302. }
  17303. else {
  17304. mesh.layerMask = 0x0FFFFFFF;
  17305. }
  17306. // Instances
  17307. if (parsedMesh.instances) {
  17308. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17309. var parsedInstance = parsedMesh.instances[index];
  17310. var instance = mesh.createInstance(parsedInstance.name);
  17311. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17312. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17313. if (parsedInstance.rotationQuaternion) {
  17314. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17315. }
  17316. else if (parsedInstance.rotation) {
  17317. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17318. }
  17319. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17320. instance.checkCollisions = mesh.checkCollisions;
  17321. if (parsedMesh.animations) {
  17322. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17323. parsedAnimation = parsedMesh.animations[animationIndex];
  17324. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17325. }
  17326. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  17327. }
  17328. }
  17329. }
  17330. return mesh;
  17331. };
  17332. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  17333. return BABYLON.MeshBuilder.CreateRibbon(name, {
  17334. pathArray: pathArray,
  17335. closeArray: closeArray,
  17336. closePath: closePath,
  17337. offset: offset,
  17338. updatable: updatable,
  17339. sideOrientation: sideOrientation,
  17340. instance: instance
  17341. }, scene);
  17342. };
  17343. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  17344. var options = {
  17345. radius: radius,
  17346. tessellation: tessellation,
  17347. sideOrientation: sideOrientation,
  17348. updatable: updatable
  17349. };
  17350. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  17351. };
  17352. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  17353. var options = {
  17354. size: size,
  17355. sideOrientation: sideOrientation,
  17356. updatable: updatable
  17357. };
  17358. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  17359. };
  17360. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  17361. var options = {
  17362. segments: segments,
  17363. diameterX: diameter,
  17364. diameterY: diameter,
  17365. diameterZ: diameter,
  17366. sideOrientation: sideOrientation,
  17367. updatable: updatable
  17368. };
  17369. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  17370. };
  17371. // Cylinder and cone
  17372. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  17373. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  17374. if (scene !== undefined) {
  17375. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  17376. updatable = scene;
  17377. }
  17378. scene = subdivisions;
  17379. subdivisions = 1;
  17380. }
  17381. var options = {
  17382. height: height,
  17383. diameterTop: diameterTop,
  17384. diameterBottom: diameterBottom,
  17385. tessellation: tessellation,
  17386. subdivisions: subdivisions,
  17387. sideOrientation: sideOrientation,
  17388. updatable: updatable
  17389. };
  17390. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  17391. };
  17392. // Torus (Code from SharpDX.org)
  17393. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  17394. var options = {
  17395. diameter: diameter,
  17396. thickness: thickness,
  17397. tessellation: tessellation,
  17398. sideOrientation: sideOrientation,
  17399. updatable: updatable
  17400. };
  17401. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  17402. };
  17403. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  17404. var options = {
  17405. radius: radius,
  17406. tube: tube,
  17407. radialSegments: radialSegments,
  17408. tubularSegments: tubularSegments,
  17409. p: p,
  17410. q: q,
  17411. sideOrientation: sideOrientation,
  17412. updatable: updatable
  17413. };
  17414. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  17415. };
  17416. // Lines
  17417. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  17418. var options = {
  17419. points: points,
  17420. updatable: updatable,
  17421. instance: instance
  17422. };
  17423. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  17424. };
  17425. // Dashed Lines
  17426. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  17427. var options = {
  17428. points: points,
  17429. dashSize: dashSize,
  17430. gapSize: gapSize,
  17431. dashNb: dashNb,
  17432. updatable: updatable
  17433. };
  17434. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  17435. };
  17436. // Extrusion
  17437. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  17438. var options = {
  17439. shape: shape,
  17440. path: path,
  17441. scale: scale,
  17442. rotation: rotation,
  17443. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17444. sideOrientation: sideOrientation,
  17445. instance: instance,
  17446. updatable: updatable
  17447. };
  17448. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  17449. };
  17450. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  17451. var options = {
  17452. shape: shape,
  17453. path: path,
  17454. scaleFunction: scaleFunction,
  17455. rotationFunction: rotationFunction,
  17456. ribbonCloseArray: ribbonCloseArray,
  17457. ribbonClosePath: ribbonClosePath,
  17458. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17459. sideOrientation: sideOrientation,
  17460. instance: instance,
  17461. updatable: updatable
  17462. };
  17463. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  17464. };
  17465. // Lathe
  17466. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  17467. var options = {
  17468. shape: shape,
  17469. radius: radius,
  17470. tessellation: tessellation,
  17471. sideOrientation: sideOrientation,
  17472. updatable: updatable
  17473. };
  17474. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  17475. };
  17476. // Plane & ground
  17477. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  17478. var options = {
  17479. size: size,
  17480. width: size,
  17481. height: size,
  17482. sideOrientation: sideOrientation,
  17483. updatable: updatable
  17484. };
  17485. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  17486. };
  17487. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  17488. var options = {
  17489. width: width,
  17490. height: height,
  17491. subdivisions: subdivisions,
  17492. updatable: updatable
  17493. };
  17494. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  17495. };
  17496. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  17497. var options = {
  17498. xmin: xmin,
  17499. zmin: zmin,
  17500. xmax: xmax,
  17501. zmax: zmax,
  17502. subdivisions: subdivisions,
  17503. precision: precision,
  17504. updatable: updatable
  17505. };
  17506. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  17507. };
  17508. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  17509. var options = {
  17510. width: width,
  17511. height: height,
  17512. subdivisions: subdivisions,
  17513. minHeight: minHeight,
  17514. maxHeight: maxHeight,
  17515. updatable: updatable,
  17516. onReady: onReady
  17517. };
  17518. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  17519. };
  17520. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  17521. var options = {
  17522. path: path,
  17523. radius: radius,
  17524. tessellation: tessellation,
  17525. radiusFunction: radiusFunction,
  17526. arc: 1,
  17527. cap: cap,
  17528. updatable: updatable,
  17529. sideOrientation: sideOrientation,
  17530. instance: instance
  17531. };
  17532. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  17533. };
  17534. Mesh.CreatePolyhedron = function (name, options, scene) {
  17535. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  17536. };
  17537. Mesh.CreateIcoSphere = function (name, options, scene) {
  17538. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  17539. };
  17540. // Decals
  17541. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  17542. var options = {
  17543. position: position,
  17544. normal: normal,
  17545. size: size,
  17546. angle: angle
  17547. };
  17548. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  17549. };
  17550. // Skeletons
  17551. /**
  17552. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  17553. */
  17554. Mesh.prototype.setPositionsForCPUSkinning = function () {
  17555. var source;
  17556. if (!this._sourcePositions) {
  17557. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17558. this._sourcePositions = new Float32Array(source);
  17559. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  17560. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  17561. }
  17562. }
  17563. return this._sourcePositions;
  17564. };
  17565. /**
  17566. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  17567. */
  17568. Mesh.prototype.setNormalsForCPUSkinning = function () {
  17569. var source;
  17570. if (!this._sourceNormals) {
  17571. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17572. this._sourceNormals = new Float32Array(source);
  17573. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  17574. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  17575. }
  17576. }
  17577. return this._sourceNormals;
  17578. };
  17579. /**
  17580. * Update the vertex buffers by applying transformation from the bones
  17581. * @param {skeleton} skeleton to apply
  17582. */
  17583. Mesh.prototype.applySkeleton = function (skeleton) {
  17584. if (!this.geometry) {
  17585. return;
  17586. }
  17587. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  17588. return;
  17589. }
  17590. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  17591. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17592. return this;
  17593. }
  17594. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17595. return this;
  17596. }
  17597. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17598. return this;
  17599. }
  17600. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17601. return this;
  17602. }
  17603. if (!this._sourcePositions) {
  17604. this.setPositionsForCPUSkinning();
  17605. }
  17606. if (!this._sourceNormals) {
  17607. this.setNormalsForCPUSkinning();
  17608. }
  17609. // positionsData checks for not being Float32Array will only pass at most once
  17610. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17611. if (!(positionsData instanceof Float32Array)) {
  17612. positionsData = new Float32Array(positionsData);
  17613. }
  17614. // normalsData checks for not being Float32Array will only pass at most once
  17615. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17616. if (!(normalsData instanceof Float32Array)) {
  17617. normalsData = new Float32Array(normalsData);
  17618. }
  17619. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17620. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17621. var needExtras = this.numBoneInfluencers > 4;
  17622. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  17623. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  17624. var skeletonMatrices = skeleton.getTransformMatrices(this);
  17625. var tempVector3 = BABYLON.Vector3.Zero();
  17626. var finalMatrix = new BABYLON.Matrix();
  17627. var tempMatrix = new BABYLON.Matrix();
  17628. var matWeightIdx = 0;
  17629. var inf;
  17630. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  17631. var weight;
  17632. for (inf = 0; inf < 4; inf++) {
  17633. weight = matricesWeightsData[matWeightIdx + inf];
  17634. if (weight > 0) {
  17635. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  17636. finalMatrix.addToSelf(tempMatrix);
  17637. }
  17638. else
  17639. break;
  17640. }
  17641. if (needExtras) {
  17642. for (inf = 0; inf < 4; inf++) {
  17643. weight = matricesWeightsExtraData[matWeightIdx + inf];
  17644. if (weight > 0) {
  17645. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  17646. finalMatrix.addToSelf(tempMatrix);
  17647. }
  17648. else
  17649. break;
  17650. }
  17651. }
  17652. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  17653. tempVector3.toArray(positionsData, index);
  17654. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  17655. tempVector3.toArray(normalsData, index);
  17656. finalMatrix.reset();
  17657. }
  17658. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  17659. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  17660. return this;
  17661. };
  17662. // Tools
  17663. Mesh.MinMax = function (meshes) {
  17664. var minVector = null;
  17665. var maxVector = null;
  17666. for (var i in meshes) {
  17667. var mesh = meshes[i];
  17668. var boundingBox = mesh.getBoundingInfo().boundingBox;
  17669. if (!minVector) {
  17670. minVector = boundingBox.minimumWorld;
  17671. maxVector = boundingBox.maximumWorld;
  17672. continue;
  17673. }
  17674. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  17675. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  17676. }
  17677. return {
  17678. min: minVector,
  17679. max: maxVector
  17680. };
  17681. };
  17682. Mesh.Center = function (meshesOrMinMaxVector) {
  17683. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  17684. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  17685. };
  17686. /**
  17687. * Merge the array of meshes into a single mesh for performance reasons.
  17688. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  17689. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  17690. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  17691. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  17692. */
  17693. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  17694. if (disposeSource === void 0) { disposeSource = true; }
  17695. var index;
  17696. if (!allow32BitsIndices) {
  17697. var totalVertices = 0;
  17698. // Counting vertices
  17699. for (index = 0; index < meshes.length; index++) {
  17700. if (meshes[index]) {
  17701. totalVertices += meshes[index].getTotalVertices();
  17702. if (totalVertices > 65536) {
  17703. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  17704. return null;
  17705. }
  17706. }
  17707. }
  17708. }
  17709. // Merge
  17710. var vertexData;
  17711. var otherVertexData;
  17712. var source;
  17713. for (index = 0; index < meshes.length; index++) {
  17714. if (meshes[index]) {
  17715. meshes[index].computeWorldMatrix(true);
  17716. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  17717. otherVertexData.transform(meshes[index].getWorldMatrix());
  17718. if (vertexData) {
  17719. vertexData.merge(otherVertexData);
  17720. }
  17721. else {
  17722. vertexData = otherVertexData;
  17723. source = meshes[index];
  17724. }
  17725. }
  17726. }
  17727. if (!meshSubclass) {
  17728. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  17729. }
  17730. vertexData.applyToMesh(meshSubclass);
  17731. // Setting properties
  17732. meshSubclass.material = source.material;
  17733. meshSubclass.checkCollisions = source.checkCollisions;
  17734. // Cleaning
  17735. if (disposeSource) {
  17736. for (index = 0; index < meshes.length; index++) {
  17737. if (meshes[index]) {
  17738. meshes[index].dispose();
  17739. }
  17740. }
  17741. }
  17742. return meshSubclass;
  17743. };
  17744. // Consts
  17745. Mesh._FRONTSIDE = 0;
  17746. Mesh._BACKSIDE = 1;
  17747. Mesh._DOUBLESIDE = 2;
  17748. Mesh._DEFAULTSIDE = 0;
  17749. Mesh._NO_CAP = 0;
  17750. Mesh._CAP_START = 1;
  17751. Mesh._CAP_END = 2;
  17752. Mesh._CAP_ALL = 3;
  17753. return Mesh;
  17754. })(BABYLON.AbstractMesh);
  17755. BABYLON.Mesh = Mesh;
  17756. })(BABYLON || (BABYLON = {}));
  17757. var BABYLON;
  17758. (function (BABYLON) {
  17759. var SubMesh = (function () {
  17760. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  17761. if (createBoundingBox === void 0) { createBoundingBox = true; }
  17762. this.materialIndex = materialIndex;
  17763. this.verticesStart = verticesStart;
  17764. this.verticesCount = verticesCount;
  17765. this.indexStart = indexStart;
  17766. this.indexCount = indexCount;
  17767. this._renderId = 0;
  17768. this._mesh = mesh;
  17769. this._renderingMesh = renderingMesh || mesh;
  17770. mesh.subMeshes.push(this);
  17771. this._trianglePlanes = [];
  17772. this._id = mesh.subMeshes.length - 1;
  17773. if (createBoundingBox) {
  17774. this.refreshBoundingInfo();
  17775. mesh.computeWorldMatrix(true);
  17776. }
  17777. }
  17778. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  17779. get: function () {
  17780. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  17781. },
  17782. enumerable: true,
  17783. configurable: true
  17784. });
  17785. SubMesh.prototype.getBoundingInfo = function () {
  17786. if (this.IsGlobal) {
  17787. return this._mesh.getBoundingInfo();
  17788. }
  17789. return this._boundingInfo;
  17790. };
  17791. SubMesh.prototype.getMesh = function () {
  17792. return this._mesh;
  17793. };
  17794. SubMesh.prototype.getRenderingMesh = function () {
  17795. return this._renderingMesh;
  17796. };
  17797. SubMesh.prototype.getMaterial = function () {
  17798. var rootMaterial = this._renderingMesh.material;
  17799. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  17800. var multiMaterial = rootMaterial;
  17801. return multiMaterial.getSubMaterial(this.materialIndex);
  17802. }
  17803. if (!rootMaterial) {
  17804. return this._mesh.getScene().defaultMaterial;
  17805. }
  17806. return rootMaterial;
  17807. };
  17808. // Methods
  17809. SubMesh.prototype.refreshBoundingInfo = function () {
  17810. this._lastColliderWorldVertices = null;
  17811. if (this.IsGlobal) {
  17812. return;
  17813. }
  17814. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17815. if (!data) {
  17816. this._boundingInfo = this._mesh._boundingInfo;
  17817. return;
  17818. }
  17819. var indices = this._renderingMesh.getIndices();
  17820. var extend;
  17821. //is this the only submesh?
  17822. if (this.indexStart === 0 && this.indexCount === indices.length) {
  17823. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  17824. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  17825. }
  17826. else {
  17827. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  17828. }
  17829. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17830. };
  17831. SubMesh.prototype._checkCollision = function (collider) {
  17832. return this.getBoundingInfo()._checkCollision(collider);
  17833. };
  17834. SubMesh.prototype.updateBoundingInfo = function (world) {
  17835. if (!this.getBoundingInfo()) {
  17836. this.refreshBoundingInfo();
  17837. }
  17838. this.getBoundingInfo().update(world);
  17839. };
  17840. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  17841. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  17842. };
  17843. SubMesh.prototype.render = function (enableAlphaMode) {
  17844. this._renderingMesh.render(this, enableAlphaMode);
  17845. };
  17846. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  17847. if (!this._linesIndexBuffer) {
  17848. var linesIndices = [];
  17849. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  17850. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  17851. }
  17852. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  17853. this.linesIndexCount = linesIndices.length;
  17854. }
  17855. return this._linesIndexBuffer;
  17856. };
  17857. SubMesh.prototype.canIntersects = function (ray) {
  17858. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  17859. };
  17860. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  17861. var intersectInfo = null;
  17862. // Triangles test
  17863. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  17864. var p0 = positions[indices[index]];
  17865. var p1 = positions[indices[index + 1]];
  17866. var p2 = positions[indices[index + 2]];
  17867. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  17868. if (currentIntersectInfo) {
  17869. if (currentIntersectInfo.distance < 0) {
  17870. continue;
  17871. }
  17872. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17873. intersectInfo = currentIntersectInfo;
  17874. intersectInfo.faceId = index / 3;
  17875. if (fastCheck) {
  17876. break;
  17877. }
  17878. }
  17879. }
  17880. }
  17881. return intersectInfo;
  17882. };
  17883. // Clone
  17884. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  17885. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  17886. if (!this.IsGlobal) {
  17887. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  17888. }
  17889. return result;
  17890. };
  17891. // Dispose
  17892. SubMesh.prototype.dispose = function () {
  17893. if (this._linesIndexBuffer) {
  17894. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  17895. this._linesIndexBuffer = null;
  17896. }
  17897. // Remove from mesh
  17898. var index = this._mesh.subMeshes.indexOf(this);
  17899. this._mesh.subMeshes.splice(index, 1);
  17900. };
  17901. // Statics
  17902. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  17903. var minVertexIndex = Number.MAX_VALUE;
  17904. var maxVertexIndex = -Number.MAX_VALUE;
  17905. renderingMesh = renderingMesh || mesh;
  17906. var indices = renderingMesh.getIndices();
  17907. for (var index = startIndex; index < startIndex + indexCount; index++) {
  17908. var vertexIndex = indices[index];
  17909. if (vertexIndex < minVertexIndex)
  17910. minVertexIndex = vertexIndex;
  17911. if (vertexIndex > maxVertexIndex)
  17912. maxVertexIndex = vertexIndex;
  17913. }
  17914. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  17915. };
  17916. return SubMesh;
  17917. })();
  17918. BABYLON.SubMesh = SubMesh;
  17919. })(BABYLON || (BABYLON = {}));
  17920. var BABYLON;
  17921. (function (BABYLON) {
  17922. var MeshBuilder = (function () {
  17923. function MeshBuilder() {
  17924. }
  17925. /**
  17926. * Creates a box mesh.
  17927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  17928. * The parameter `size` sets the size (float) of each box side (default 1).
  17929. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  17930. * 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).
  17931. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  17932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17935. */
  17936. MeshBuilder.CreateBox = function (name, options, scene) {
  17937. var box = new BABYLON.Mesh(name, scene);
  17938. var vertexData = BABYLON.VertexData.CreateBox(options);
  17939. vertexData.applyToMesh(box, options.updatable);
  17940. return box;
  17941. };
  17942. /**
  17943. * Creates a sphere mesh.
  17944. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  17945. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  17946. * 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`).
  17947. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  17948. * 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
  17949. * 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).
  17950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17951. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17953. */
  17954. MeshBuilder.CreateSphere = function (name, options, scene) {
  17955. var sphere = new BABYLON.Mesh(name, scene);
  17956. var vertexData = BABYLON.VertexData.CreateSphere(options);
  17957. vertexData.applyToMesh(sphere, options.updatable);
  17958. return sphere;
  17959. };
  17960. /**
  17961. * Creates a plane polygonal mesh. By default, this is a disc.
  17962. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  17963. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  17964. * 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.
  17965. * 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
  17966. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17967. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17969. */
  17970. MeshBuilder.CreateDisc = function (name, options, scene) {
  17971. var disc = new BABYLON.Mesh(name, scene);
  17972. var vertexData = BABYLON.VertexData.CreateDisc(options);
  17973. vertexData.applyToMesh(disc, options.updatable);
  17974. return disc;
  17975. };
  17976. /**
  17977. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  17978. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  17979. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  17980. * 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`).
  17981. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  17982. * 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.
  17983. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17984. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17986. */
  17987. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  17988. var sphere = new BABYLON.Mesh(name, scene);
  17989. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  17990. vertexData.applyToMesh(sphere, options.updatable);
  17991. return sphere;
  17992. };
  17993. ;
  17994. /**
  17995. * Creates a ribbon mesh.
  17996. * 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.
  17997. *
  17998. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  17999. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18000. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18001. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18002. * 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
  18003. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18004. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18006. */
  18007. MeshBuilder.CreateRibbon = function (name, options, scene) {
  18008. var pathArray = options.pathArray;
  18009. var closeArray = options.closeArray;
  18010. var closePath = options.closePath;
  18011. var offset = options.offset;
  18012. var sideOrientation = options.sideOrientation;
  18013. var instance = options.instance;
  18014. var updatable = options.updatable;
  18015. if (instance) {
  18016. // positionFunction : ribbon case
  18017. // only pathArray and sideOrientation parameters are taken into account for positions update
  18018. var positionFunction = function (positions) {
  18019. var minlg = pathArray[0].length;
  18020. var i = 0;
  18021. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  18022. for (var si = 1; si <= ns; si++) {
  18023. for (var p = 0; p < pathArray.length; p++) {
  18024. var path = pathArray[p];
  18025. var l = path.length;
  18026. minlg = (minlg < l) ? minlg : l;
  18027. var j = 0;
  18028. while (j < minlg) {
  18029. positions[i] = path[j].x;
  18030. positions[i + 1] = path[j].y;
  18031. positions[i + 2] = path[j].z;
  18032. j++;
  18033. i += 3;
  18034. }
  18035. if (instance._closePath) {
  18036. positions[i] = path[0].x;
  18037. positions[i + 1] = path[0].y;
  18038. positions[i + 2] = path[0].z;
  18039. i += 3;
  18040. }
  18041. }
  18042. }
  18043. };
  18044. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18045. positionFunction(positions);
  18046. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18047. if (!(instance.areNormalsFrozen)) {
  18048. var indices = instance.getIndices();
  18049. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18050. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18051. if (instance._closePath) {
  18052. var indexFirst = 0;
  18053. var indexLast = 0;
  18054. for (var p = 0; p < pathArray.length; p++) {
  18055. indexFirst = instance._idx[p] * 3;
  18056. if (p + 1 < pathArray.length) {
  18057. indexLast = (instance._idx[p + 1] - 1) * 3;
  18058. }
  18059. else {
  18060. indexLast = normals.length - 3;
  18061. }
  18062. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  18063. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  18064. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  18065. normals[indexLast] = normals[indexFirst];
  18066. normals[indexLast + 1] = normals[indexFirst + 1];
  18067. normals[indexLast + 2] = normals[indexFirst + 2];
  18068. }
  18069. }
  18070. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18071. }
  18072. return instance;
  18073. }
  18074. else {
  18075. var ribbon = new BABYLON.Mesh(name, scene);
  18076. ribbon.sideOrientation = sideOrientation;
  18077. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  18078. if (closePath) {
  18079. ribbon._idx = vertexData._idx;
  18080. }
  18081. ribbon._closePath = closePath;
  18082. ribbon._closeArray = closeArray;
  18083. vertexData.applyToMesh(ribbon, updatable);
  18084. return ribbon;
  18085. }
  18086. };
  18087. /**
  18088. * Creates a cylinder or a cone mesh.
  18089. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  18090. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18091. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18092. * 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.
  18093. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18094. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18095. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  18096. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  18097. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  18098. * 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).
  18099. * 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
  18100. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  18101. * 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
  18102. * 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.
  18103. * If `enclose` is false, a ring surface is one element.
  18104. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  18105. * 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
  18106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18109. */
  18110. MeshBuilder.CreateCylinder = function (name, options, scene) {
  18111. var cylinder = new BABYLON.Mesh(name, scene);
  18112. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  18113. vertexData.applyToMesh(cylinder, options.updatable);
  18114. return cylinder;
  18115. };
  18116. /**
  18117. * Creates a torus mesh.
  18118. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  18119. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18120. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18121. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18123. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18125. */
  18126. MeshBuilder.CreateTorus = function (name, options, scene) {
  18127. var torus = new BABYLON.Mesh(name, scene);
  18128. var vertexData = BABYLON.VertexData.CreateTorus(options);
  18129. vertexData.applyToMesh(torus, options.updatable);
  18130. return torus;
  18131. };
  18132. /**
  18133. * Creates a torus knot mesh.
  18134. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  18135. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18136. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18137. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18138. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18139. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18140. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18141. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18142. */
  18143. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  18144. var torusKnot = new BABYLON.Mesh(name, scene);
  18145. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  18146. vertexData.applyToMesh(torusKnot, options.updatable);
  18147. return torusKnot;
  18148. };
  18149. /**
  18150. * Creates a line system mesh.
  18151. * A line system is a pool of many lines gathered in a single mesh.
  18152. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  18153. * 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.
  18154. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  18155. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  18156. * 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
  18157. * 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
  18158. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  18159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18160. */
  18161. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  18162. var instance = options.instance;
  18163. var lines = options.lines;
  18164. if (instance) {
  18165. var positionFunction = function (positions) {
  18166. var i = 0;
  18167. for (var l = 0; l < lines.length; l++) {
  18168. var points = lines[l];
  18169. for (var p = 0; p < points.length; p++) {
  18170. positions[i] = points[p].x;
  18171. positions[i + 1] = points[p].y;
  18172. positions[i + 2] = points[p].z;
  18173. i += 3;
  18174. }
  18175. }
  18176. };
  18177. instance.updateMeshPositions(positionFunction, false);
  18178. return instance;
  18179. }
  18180. // line system creation
  18181. var lineSystem = new BABYLON.LinesMesh(name, scene);
  18182. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  18183. vertexData.applyToMesh(lineSystem, options.updatable);
  18184. return lineSystem;
  18185. };
  18186. /**
  18187. * Creates a line mesh.
  18188. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  18189. * 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.
  18190. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18191. * The parameter `points` is an array successive Vector3.
  18192. * 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
  18193. * When updating an instance, remember that only point positions can change, not the number of points.
  18194. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18195. */
  18196. MeshBuilder.CreateLines = function (name, options, scene) {
  18197. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  18198. return lines;
  18199. };
  18200. /**
  18201. * Creates a dashed line mesh.
  18202. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  18203. * 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.
  18204. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18205. * The parameter `points` is an array successive Vector3.
  18206. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18207. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18208. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18209. * 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
  18210. * When updating an instance, remember that only point positions can change, not the number of points.
  18211. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18212. */
  18213. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  18214. var points = options.points;
  18215. var instance = options.instance;
  18216. var gapSize = options.gapSize;
  18217. var dashNb = options.dashNb;
  18218. var dashSize = options.dashSize;
  18219. if (instance) {
  18220. var positionFunction = function (positions) {
  18221. var curvect = BABYLON.Vector3.Zero();
  18222. var nbSeg = positions.length / 6;
  18223. var lg = 0;
  18224. var nb = 0;
  18225. var shft = 0;
  18226. var dashshft = 0;
  18227. var curshft = 0;
  18228. var p = 0;
  18229. var i = 0;
  18230. var j = 0;
  18231. for (i = 0; i < points.length - 1; i++) {
  18232. points[i + 1].subtractToRef(points[i], curvect);
  18233. lg += curvect.length();
  18234. }
  18235. shft = lg / nbSeg;
  18236. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  18237. for (i = 0; i < points.length - 1; i++) {
  18238. points[i + 1].subtractToRef(points[i], curvect);
  18239. nb = Math.floor(curvect.length() / shft);
  18240. curvect.normalize();
  18241. j = 0;
  18242. while (j < nb && p < positions.length) {
  18243. curshft = shft * j;
  18244. positions[p] = points[i].x + curshft * curvect.x;
  18245. positions[p + 1] = points[i].y + curshft * curvect.y;
  18246. positions[p + 2] = points[i].z + curshft * curvect.z;
  18247. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  18248. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  18249. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  18250. p += 6;
  18251. j++;
  18252. }
  18253. }
  18254. while (p < positions.length) {
  18255. positions[p] = points[i].x;
  18256. positions[p + 1] = points[i].y;
  18257. positions[p + 2] = points[i].z;
  18258. p += 3;
  18259. }
  18260. };
  18261. instance.updateMeshPositions(positionFunction, false);
  18262. return instance;
  18263. }
  18264. // dashed lines creation
  18265. var dashedLines = new BABYLON.LinesMesh(name, scene);
  18266. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  18267. vertexData.applyToMesh(dashedLines, options.updatable);
  18268. dashedLines.dashSize = dashSize;
  18269. dashedLines.gapSize = gapSize;
  18270. return dashedLines;
  18271. };
  18272. /**
  18273. * Creates an extruded shape mesh.
  18274. * 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.
  18275. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  18276. *
  18277. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18278. * 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
  18279. * extruded along the Z axis.
  18280. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18281. * 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.
  18282. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18283. * 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
  18284. * 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
  18285. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18286. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18287. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18288. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18289. */
  18290. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  18291. var path = options.path;
  18292. var shape = options.shape;
  18293. var scale = options.scale || 1;
  18294. var rotation = options.rotation || 0;
  18295. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18296. var updatable = options.updatable;
  18297. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18298. var instance = options.instance;
  18299. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  18300. };
  18301. /**
  18302. * Creates an custom extruded shape mesh.
  18303. * 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.
  18304. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  18305. *
  18306. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18307. * 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
  18308. * extruded along the Z axis.
  18309. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18310. * 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
  18311. * and the distance of this point from the begining of the path :
  18312. * ```rotationFunction = function(i, distance) {
  18313. * // do things
  18314. * return rotationValue; }```
  18315. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18316. * 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
  18317. * and the distance of this point from the begining of the path :
  18318. * ````scaleFunction = function(i, distance) {
  18319. * // do things
  18320. * return scaleValue;}```
  18321. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18322. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18323. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18324. * 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
  18325. * 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
  18326. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18327. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18328. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18330. */
  18331. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  18332. var path = options.path;
  18333. var shape = options.shape;
  18334. var scaleFunction = options.scaleFunction || (function () { return 1; });
  18335. var rotationFunction = options.rotationFunction || (function () { return 0; });
  18336. var ribbonCloseArray = options.ribbonCloseArray || false;
  18337. var ribbonClosePath = options.ribbonClosePath || false;
  18338. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18339. var updatable = options.updatable;
  18340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18341. var instance = options.instance;
  18342. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  18343. };
  18344. /**
  18345. * Creates lathe mesh.
  18346. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18347. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  18348. *
  18349. * 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
  18350. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18351. * The parameter "radius" (positive float, default 1) is the radius value of the lathe.
  18352. * The parameter "tessellation" (positive integer, default 64) is the side number of the lathe.
  18353. * 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.
  18354. * The parameter "closed" (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  18355. * 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
  18356. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18358. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18359. */
  18360. MeshBuilder.CreateLathe = function (name, options, scene) {
  18361. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  18362. var closed = (options.closed === undefined) ? true : options.closed;
  18363. var shape = options.shape;
  18364. var radius = options.radius || 1;
  18365. var tessellation = options.tessellation || 64;
  18366. var updatable = options.updatable;
  18367. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18368. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  18369. var pi2 = Math.PI * 2;
  18370. var paths = new Array();
  18371. var i = 0;
  18372. var p = 0;
  18373. var step = pi2 / tessellation * arc;
  18374. var rotated;
  18375. var path = new Array();
  18376. ;
  18377. for (i = 0; i <= tessellation; i++) {
  18378. var path = [];
  18379. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  18380. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  18381. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  18382. }
  18383. for (p = 0; p < shape.length; p++) {
  18384. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  18385. path.push(rotated);
  18386. }
  18387. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  18388. 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));
  18389. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  18390. }
  18391. paths.push(path);
  18392. }
  18393. // lathe ribbon
  18394. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  18395. return lathe;
  18396. };
  18397. /**
  18398. * Creates a plane mesh.
  18399. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  18400. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18401. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  18402. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  18403. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18404. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18406. */
  18407. MeshBuilder.CreatePlane = function (name, options, scene) {
  18408. var plane = new BABYLON.Mesh(name, scene);
  18409. var vertexData = BABYLON.VertexData.CreatePlane(options);
  18410. vertexData.applyToMesh(plane, options.updatable);
  18411. if (options.sourcePlane) {
  18412. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  18413. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  18414. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  18415. plane.rotate(vectorProduct, product);
  18416. }
  18417. return plane;
  18418. };
  18419. /**
  18420. * Creates a ground mesh.
  18421. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  18422. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18423. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18425. */
  18426. MeshBuilder.CreateGround = function (name, options, scene) {
  18427. var ground = new BABYLON.GroundMesh(name, scene);
  18428. ground._setReady(false);
  18429. ground._subdivisions = options.subdivisions || 1;
  18430. ground._width = options.width || 1;
  18431. ground._height = options.height || 1;
  18432. ground._maxX = ground._width / 2;
  18433. ground._maxZ = ground._height / 2;
  18434. ground._minX = -ground._maxX;
  18435. ground._minZ = -ground._maxZ;
  18436. var vertexData = BABYLON.VertexData.CreateGround(options);
  18437. vertexData.applyToMesh(ground, options.updatable);
  18438. ground._setReady(true);
  18439. return ground;
  18440. };
  18441. /**
  18442. * Creates a tiled ground mesh.
  18443. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  18444. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18445. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18446. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18447. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18448. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18449. * numbers of subdivisions on the ground width and height of each tile.
  18450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18451. */
  18452. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  18453. var tiledGround = new BABYLON.Mesh(name, scene);
  18454. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  18455. vertexData.applyToMesh(tiledGround, options.updatable);
  18456. return tiledGround;
  18457. };
  18458. /**
  18459. * Creates a ground mesh from a height map.
  18460. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18461. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  18462. * The parameter `url` sets the URL of the height map image resource.
  18463. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18464. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18465. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18466. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18467. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  18468. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18469. * return; }```
  18470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18471. */
  18472. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  18473. var width = options.width || 10;
  18474. var height = options.height || 10;
  18475. var subdivisions = options.subdivisions || 1;
  18476. var minHeight = options.minHeight;
  18477. var maxHeight = options.maxHeight || 10;
  18478. var updatable = options.updatable;
  18479. var onReady = options.onReady;
  18480. var ground = new BABYLON.GroundMesh(name, scene);
  18481. ground._subdivisions = subdivisions;
  18482. ground._width = width;
  18483. ground._height = height;
  18484. ground._maxX = ground._width / 2;
  18485. ground._maxZ = ground._height / 2;
  18486. ground._minX = -ground._maxX;
  18487. ground._minZ = -ground._maxZ;
  18488. ground._setReady(false);
  18489. var onload = function (img) {
  18490. // Getting height map data
  18491. var canvas = document.createElement("canvas");
  18492. var context = canvas.getContext("2d");
  18493. var bufferWidth = img.width;
  18494. var bufferHeight = img.height;
  18495. canvas.width = bufferWidth;
  18496. canvas.height = bufferHeight;
  18497. context.drawImage(img, 0, 0);
  18498. // Create VertexData from map data
  18499. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18500. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  18501. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  18502. width: width, height: height,
  18503. subdivisions: subdivisions,
  18504. minHeight: minHeight, maxHeight: maxHeight,
  18505. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  18506. });
  18507. vertexData.applyToMesh(ground, updatable);
  18508. ground._setReady(true);
  18509. //execute ready callback, if set
  18510. if (onReady) {
  18511. onReady(ground);
  18512. }
  18513. };
  18514. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18515. return ground;
  18516. };
  18517. MeshBuilder.CreateTube = function (name, options, scene) {
  18518. var path = options.path;
  18519. var radius = options.radius || 1;
  18520. var tessellation = options.tessellation || 64;
  18521. var radiusFunction = options.radiusFunction;
  18522. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  18523. var updatable = options.updatable;
  18524. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18525. var instance = options.instance;
  18526. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  18527. // tube geometry
  18528. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  18529. var tangents = path3D.getTangents();
  18530. var normals = path3D.getNormals();
  18531. var distances = path3D.getDistances();
  18532. var pi2 = Math.PI * 2;
  18533. var step = pi2 / tessellation * arc;
  18534. var returnRadius = function () { return radius; };
  18535. var radiusFunctionFinal = radiusFunction || returnRadius;
  18536. var circlePath;
  18537. var rad;
  18538. var normal;
  18539. var rotated;
  18540. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  18541. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  18542. for (var i = 0; i < path.length; i++) {
  18543. rad = radiusFunctionFinal(i, distances[i]); // current radius
  18544. circlePath = Array(); // current circle array
  18545. normal = normals[i]; // current normal
  18546. for (var t = 0; t < tessellation; t++) {
  18547. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  18548. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  18549. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  18550. rotated.scaleInPlace(rad).addInPlace(path[i]);
  18551. circlePath[t] = rotated;
  18552. }
  18553. circlePaths[index] = circlePath;
  18554. index++;
  18555. }
  18556. // cap
  18557. var capPath = function (nbPoints, pathIndex) {
  18558. var pointCap = Array();
  18559. for (var i = 0; i < nbPoints; i++) {
  18560. pointCap.push(path[pathIndex]);
  18561. }
  18562. return pointCap;
  18563. };
  18564. switch (cap) {
  18565. case BABYLON.Mesh.NO_CAP:
  18566. break;
  18567. case BABYLON.Mesh.CAP_START:
  18568. circlePaths[0] = capPath(tessellation, 0);
  18569. circlePaths[1] = circlePaths[2].slice(0);
  18570. break;
  18571. case BABYLON.Mesh.CAP_END:
  18572. circlePaths[index] = circlePaths[index - 1].slice(0);
  18573. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  18574. break;
  18575. case BABYLON.Mesh.CAP_ALL:
  18576. circlePaths[0] = capPath(tessellation, 0);
  18577. circlePaths[1] = circlePaths[2].slice(0);
  18578. circlePaths[index] = circlePaths[index - 1].slice(0);
  18579. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  18580. break;
  18581. default:
  18582. break;
  18583. }
  18584. return circlePaths;
  18585. };
  18586. var path3D;
  18587. var pathArray;
  18588. if (instance) {
  18589. var arc = options.arc || instance.arc;
  18590. path3D = (instance.path3D).update(path);
  18591. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  18592. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  18593. instance.path3D = path3D;
  18594. instance.pathArray = pathArray;
  18595. instance.arc = arc;
  18596. return instance;
  18597. }
  18598. // tube creation
  18599. path3D = new BABYLON.Path3D(path);
  18600. var newPathArray = new Array();
  18601. cap = (cap < 0 || cap > 3) ? 0 : cap;
  18602. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  18603. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  18604. tube.pathArray = pathArray;
  18605. tube.path3D = path3D;
  18606. tube.tessellation = tessellation;
  18607. tube.cap = cap;
  18608. tube.arc = options.arc;
  18609. return tube;
  18610. };
  18611. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  18612. var polyhedron = new BABYLON.Mesh(name, scene);
  18613. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  18614. vertexData.applyToMesh(polyhedron, options.updatable);
  18615. return polyhedron;
  18616. };
  18617. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  18618. var indices = sourceMesh.getIndices();
  18619. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18620. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18621. var position = options.position || BABYLON.Vector3.Zero();
  18622. var normal = options.normal || BABYLON.Vector3.Up();
  18623. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  18624. var angle = options.angle || 0;
  18625. // Getting correct rotation
  18626. if (!normal) {
  18627. var target = new BABYLON.Vector3(0, 0, 1);
  18628. var camera = sourceMesh.getScene().activeCamera;
  18629. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  18630. normal = camera.globalPosition.subtract(cameraWorldTarget);
  18631. }
  18632. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  18633. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  18634. var pitch = Math.atan2(normal.y, len);
  18635. // Matrix
  18636. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  18637. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  18638. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  18639. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  18640. var vertexData = new BABYLON.VertexData();
  18641. vertexData.indices = [];
  18642. vertexData.positions = [];
  18643. vertexData.normals = [];
  18644. vertexData.uvs = [];
  18645. var currentVertexDataIndex = 0;
  18646. var extractDecalVector3 = function (indexId) {
  18647. var vertexId = indices[indexId];
  18648. var result = new BABYLON.PositionNormalVertex();
  18649. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  18650. // Send vector to decal local world
  18651. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  18652. // Get normal
  18653. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  18654. return result;
  18655. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  18656. var clip = function (vertices, axis) {
  18657. if (vertices.length === 0) {
  18658. return vertices;
  18659. }
  18660. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  18661. var clipVertices = function (v0, v1) {
  18662. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  18663. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  18664. };
  18665. var result = new Array();
  18666. for (var index = 0; index < vertices.length; index += 3) {
  18667. var v1Out;
  18668. var v2Out;
  18669. var v3Out;
  18670. var total = 0;
  18671. var nV1, nV2, nV3, nV4;
  18672. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  18673. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  18674. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  18675. v1Out = d1 > 0;
  18676. v2Out = d2 > 0;
  18677. v3Out = d3 > 0;
  18678. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  18679. switch (total) {
  18680. case 0:
  18681. result.push(vertices[index]);
  18682. result.push(vertices[index + 1]);
  18683. result.push(vertices[index + 2]);
  18684. break;
  18685. case 1:
  18686. if (v1Out) {
  18687. nV1 = vertices[index + 1];
  18688. nV2 = vertices[index + 2];
  18689. nV3 = clipVertices(vertices[index], nV1);
  18690. nV4 = clipVertices(vertices[index], nV2);
  18691. }
  18692. if (v2Out) {
  18693. nV1 = vertices[index];
  18694. nV2 = vertices[index + 2];
  18695. nV3 = clipVertices(vertices[index + 1], nV1);
  18696. nV4 = clipVertices(vertices[index + 1], nV2);
  18697. result.push(nV3);
  18698. result.push(nV2.clone());
  18699. result.push(nV1.clone());
  18700. result.push(nV2.clone());
  18701. result.push(nV3.clone());
  18702. result.push(nV4);
  18703. break;
  18704. }
  18705. if (v3Out) {
  18706. nV1 = vertices[index];
  18707. nV2 = vertices[index + 1];
  18708. nV3 = clipVertices(vertices[index + 2], nV1);
  18709. nV4 = clipVertices(vertices[index + 2], nV2);
  18710. }
  18711. result.push(nV1.clone());
  18712. result.push(nV2.clone());
  18713. result.push(nV3);
  18714. result.push(nV4);
  18715. result.push(nV3.clone());
  18716. result.push(nV2.clone());
  18717. break;
  18718. case 2:
  18719. if (!v1Out) {
  18720. nV1 = vertices[index].clone();
  18721. nV2 = clipVertices(nV1, vertices[index + 1]);
  18722. nV3 = clipVertices(nV1, vertices[index + 2]);
  18723. result.push(nV1);
  18724. result.push(nV2);
  18725. result.push(nV3);
  18726. }
  18727. if (!v2Out) {
  18728. nV1 = vertices[index + 1].clone();
  18729. nV2 = clipVertices(nV1, vertices[index + 2]);
  18730. nV3 = clipVertices(nV1, vertices[index]);
  18731. result.push(nV1);
  18732. result.push(nV2);
  18733. result.push(nV3);
  18734. }
  18735. if (!v3Out) {
  18736. nV1 = vertices[index + 2].clone();
  18737. nV2 = clipVertices(nV1, vertices[index]);
  18738. nV3 = clipVertices(nV1, vertices[index + 1]);
  18739. result.push(nV1);
  18740. result.push(nV2);
  18741. result.push(nV3);
  18742. }
  18743. break;
  18744. case 3:
  18745. break;
  18746. }
  18747. }
  18748. return result;
  18749. };
  18750. for (var index = 0; index < indices.length; index += 3) {
  18751. var faceVertices = new Array();
  18752. faceVertices.push(extractDecalVector3(index));
  18753. faceVertices.push(extractDecalVector3(index + 1));
  18754. faceVertices.push(extractDecalVector3(index + 2));
  18755. // Clip
  18756. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  18757. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  18758. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  18759. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  18760. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  18761. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  18762. if (faceVertices.length === 0) {
  18763. continue;
  18764. }
  18765. // Add UVs and get back to world
  18766. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  18767. var vertex = faceVertices[vIndex];
  18768. //TODO check for Int32Array
  18769. vertexData.indices.push(currentVertexDataIndex);
  18770. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  18771. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  18772. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  18773. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  18774. currentVertexDataIndex++;
  18775. }
  18776. }
  18777. // Return mesh
  18778. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  18779. vertexData.applyToMesh(decal);
  18780. decal.position = position.clone();
  18781. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  18782. return decal;
  18783. };
  18784. // Privates
  18785. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  18786. // extrusion geometry
  18787. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  18788. var tangents = path3D.getTangents();
  18789. var normals = path3D.getNormals();
  18790. var binormals = path3D.getBinormals();
  18791. var distances = path3D.getDistances();
  18792. var angle = 0;
  18793. var returnScale = function () { return scale; };
  18794. var returnRotation = function () { return rotation; };
  18795. var rotate = custom ? rotateFunction : returnRotation;
  18796. var scl = custom ? scaleFunction : returnScale;
  18797. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  18798. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  18799. for (var i = 0; i < curve.length; i++) {
  18800. var shapePath = new Array();
  18801. var angleStep = rotate(i, distances[i]);
  18802. var scaleRatio = scl(i, distances[i]);
  18803. for (var p = 0; p < shape.length; p++) {
  18804. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  18805. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  18806. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  18807. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  18808. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  18809. shapePath[p] = rotated;
  18810. }
  18811. shapePaths[index] = shapePath;
  18812. angle += angleStep;
  18813. index++;
  18814. }
  18815. // cap
  18816. var capPath = function (shapePath) {
  18817. var pointCap = Array();
  18818. var barycenter = BABYLON.Vector3.Zero();
  18819. var i;
  18820. for (i = 0; i < shapePath.length; i++) {
  18821. barycenter.addInPlace(shapePath[i]);
  18822. }
  18823. barycenter.scaleInPlace(1 / shapePath.length);
  18824. for (i = 0; i < shapePath.length; i++) {
  18825. pointCap.push(barycenter);
  18826. }
  18827. return pointCap;
  18828. };
  18829. switch (cap) {
  18830. case BABYLON.Mesh.NO_CAP:
  18831. break;
  18832. case BABYLON.Mesh.CAP_START:
  18833. shapePaths[0] = capPath(shapePaths[2]);
  18834. shapePaths[1] = shapePaths[2].slice(0);
  18835. break;
  18836. case BABYLON.Mesh.CAP_END:
  18837. shapePaths[index] = shapePaths[index - 1];
  18838. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  18839. break;
  18840. case BABYLON.Mesh.CAP_ALL:
  18841. shapePaths[0] = capPath(shapePaths[2]);
  18842. shapePaths[1] = shapePaths[2].slice(0);
  18843. shapePaths[index] = shapePaths[index - 1];
  18844. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  18845. break;
  18846. default:
  18847. break;
  18848. }
  18849. return shapePaths;
  18850. };
  18851. var path3D;
  18852. var pathArray;
  18853. if (instance) {
  18854. path3D = (instance.path3D).update(curve);
  18855. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  18856. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  18857. return instance;
  18858. }
  18859. // extruded shape creation
  18860. path3D = new BABYLON.Path3D(curve);
  18861. var newShapePaths = new Array();
  18862. cap = (cap < 0 || cap > 3) ? 0 : cap;
  18863. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  18864. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  18865. extrudedGeneric.pathArray = pathArray;
  18866. extrudedGeneric.path3D = path3D;
  18867. extrudedGeneric.cap = cap;
  18868. return extrudedGeneric;
  18869. };
  18870. return MeshBuilder;
  18871. })();
  18872. BABYLON.MeshBuilder = MeshBuilder;
  18873. })(BABYLON || (BABYLON = {}));
  18874. var BABYLON;
  18875. (function (BABYLON) {
  18876. var BaseTexture = (function () {
  18877. function BaseTexture(scene) {
  18878. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18879. this.hasAlpha = false;
  18880. this.getAlphaFromRGB = false;
  18881. this.level = 1;
  18882. this.isCube = false;
  18883. this.isRenderTarget = false;
  18884. this.animations = new Array();
  18885. this.coordinatesIndex = 0;
  18886. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18887. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18888. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18889. this.anisotropicFilteringLevel = 4;
  18890. this._scene = scene;
  18891. this._scene.textures.push(this);
  18892. }
  18893. BaseTexture.prototype.getScene = function () {
  18894. return this._scene;
  18895. };
  18896. BaseTexture.prototype.getTextureMatrix = function () {
  18897. return null;
  18898. };
  18899. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18900. return null;
  18901. };
  18902. BaseTexture.prototype.getInternalTexture = function () {
  18903. return this._texture;
  18904. };
  18905. BaseTexture.prototype.isReady = function () {
  18906. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18907. return true;
  18908. }
  18909. if (this._texture) {
  18910. return this._texture.isReady;
  18911. }
  18912. return false;
  18913. };
  18914. BaseTexture.prototype.getSize = function () {
  18915. if (this._texture._width) {
  18916. return { width: this._texture._width, height: this._texture._height };
  18917. }
  18918. if (this._texture._size) {
  18919. return { width: this._texture._size, height: this._texture._size };
  18920. }
  18921. return { width: 0, height: 0 };
  18922. };
  18923. BaseTexture.prototype.getBaseSize = function () {
  18924. if (!this.isReady())
  18925. return { width: 0, height: 0 };
  18926. if (this._texture._size) {
  18927. return { width: this._texture._size, height: this._texture._size };
  18928. }
  18929. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  18930. };
  18931. BaseTexture.prototype.scale = function (ratio) {
  18932. };
  18933. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18934. get: function () {
  18935. return false;
  18936. },
  18937. enumerable: true,
  18938. configurable: true
  18939. });
  18940. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18941. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18942. for (var index = 0; index < texturesCache.length; index++) {
  18943. var texturesCacheEntry = texturesCache[index];
  18944. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18945. texturesCache.splice(index, 1);
  18946. return;
  18947. }
  18948. }
  18949. };
  18950. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18951. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18952. for (var index = 0; index < texturesCache.length; index++) {
  18953. var texturesCacheEntry = texturesCache[index];
  18954. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18955. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18956. texturesCacheEntry.references++;
  18957. return texturesCacheEntry;
  18958. }
  18959. }
  18960. }
  18961. return null;
  18962. };
  18963. BaseTexture.prototype.delayLoad = function () {
  18964. };
  18965. BaseTexture.prototype.clone = function () {
  18966. return null;
  18967. };
  18968. BaseTexture.prototype.releaseInternalTexture = function () {
  18969. if (this._texture) {
  18970. this._scene.getEngine().releaseInternalTexture(this._texture);
  18971. delete this._texture;
  18972. }
  18973. };
  18974. BaseTexture.prototype.dispose = function () {
  18975. // Animations
  18976. this.getScene().stopAnimation(this);
  18977. // Remove from scene
  18978. var index = this._scene.textures.indexOf(this);
  18979. if (index >= 0) {
  18980. this._scene.textures.splice(index, 1);
  18981. }
  18982. if (this._texture === undefined) {
  18983. return;
  18984. }
  18985. // Release
  18986. this.releaseInternalTexture();
  18987. // Callback
  18988. if (this.onDispose) {
  18989. this.onDispose();
  18990. }
  18991. };
  18992. BaseTexture.prototype.serialize = function () {
  18993. var serializationObject = {};
  18994. if (!this.name) {
  18995. return null;
  18996. }
  18997. serializationObject.name = this.name;
  18998. serializationObject.hasAlpha = this.hasAlpha;
  18999. serializationObject.level = this.level;
  19000. serializationObject.coordinatesIndex = this.coordinatesIndex;
  19001. serializationObject.coordinatesMode = this.coordinatesMode;
  19002. serializationObject.wrapU = this.wrapU;
  19003. serializationObject.wrapV = this.wrapV;
  19004. // Animations
  19005. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19006. return serializationObject;
  19007. };
  19008. return BaseTexture;
  19009. })();
  19010. BABYLON.BaseTexture = BaseTexture;
  19011. })(BABYLON || (BABYLON = {}));
  19012. var BABYLON;
  19013. (function (BABYLON) {
  19014. var Texture = (function (_super) {
  19015. __extends(Texture, _super);
  19016. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  19017. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19018. if (onLoad === void 0) { onLoad = null; }
  19019. if (onError === void 0) { onError = null; }
  19020. if (buffer === void 0) { buffer = null; }
  19021. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19022. _super.call(this, scene);
  19023. this.uOffset = 0;
  19024. this.vOffset = 0;
  19025. this.uScale = 1.0;
  19026. this.vScale = 1.0;
  19027. this.uAng = 0;
  19028. this.vAng = 0;
  19029. this.wAng = 0;
  19030. this.name = url;
  19031. this.url = url;
  19032. this._noMipmap = noMipmap;
  19033. this._invertY = invertY;
  19034. this._samplingMode = samplingMode;
  19035. this._buffer = buffer;
  19036. this._deleteBuffer = deleteBuffer;
  19037. if (!url) {
  19038. return;
  19039. }
  19040. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  19041. if (!this._texture) {
  19042. if (!scene.useDelayedTextureLoading) {
  19043. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  19044. if (deleteBuffer) {
  19045. delete this._buffer;
  19046. }
  19047. }
  19048. else {
  19049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19050. this._delayedOnLoad = onLoad;
  19051. this._delayedOnError = onError;
  19052. }
  19053. }
  19054. else {
  19055. BABYLON.Tools.SetImmediate(function () {
  19056. if (onLoad) {
  19057. onLoad();
  19058. }
  19059. });
  19060. }
  19061. }
  19062. Texture.prototype.delayLoad = function () {
  19063. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19064. return;
  19065. }
  19066. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19067. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19068. if (!this._texture) {
  19069. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  19070. if (this._deleteBuffer) {
  19071. delete this._buffer;
  19072. }
  19073. }
  19074. };
  19075. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19076. if (!this._texture) {
  19077. return;
  19078. }
  19079. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19080. };
  19081. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19082. x *= this.uScale;
  19083. y *= this.vScale;
  19084. x -= 0.5 * this.uScale;
  19085. y -= 0.5 * this.vScale;
  19086. z -= 0.5;
  19087. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19088. t.x += 0.5 * this.uScale + this.uOffset;
  19089. t.y += 0.5 * this.vScale + this.vOffset;
  19090. t.z += 0.5;
  19091. };
  19092. Texture.prototype.getTextureMatrix = function () {
  19093. if (this.uOffset === this._cachedUOffset &&
  19094. this.vOffset === this._cachedVOffset &&
  19095. this.uScale === this._cachedUScale &&
  19096. this.vScale === this._cachedVScale &&
  19097. this.uAng === this._cachedUAng &&
  19098. this.vAng === this._cachedVAng &&
  19099. this.wAng === this._cachedWAng) {
  19100. return this._cachedTextureMatrix;
  19101. }
  19102. this._cachedUOffset = this.uOffset;
  19103. this._cachedVOffset = this.vOffset;
  19104. this._cachedUScale = this.uScale;
  19105. this._cachedVScale = this.vScale;
  19106. this._cachedUAng = this.uAng;
  19107. this._cachedVAng = this.vAng;
  19108. this._cachedWAng = this.wAng;
  19109. if (!this._cachedTextureMatrix) {
  19110. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19111. this._rowGenerationMatrix = new BABYLON.Matrix();
  19112. this._t0 = BABYLON.Vector3.Zero();
  19113. this._t1 = BABYLON.Vector3.Zero();
  19114. this._t2 = BABYLON.Vector3.Zero();
  19115. }
  19116. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19117. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19118. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19119. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19120. this._t1.subtractInPlace(this._t0);
  19121. this._t2.subtractInPlace(this._t0);
  19122. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19123. this._cachedTextureMatrix.m[0] = this._t1.x;
  19124. this._cachedTextureMatrix.m[1] = this._t1.y;
  19125. this._cachedTextureMatrix.m[2] = this._t1.z;
  19126. this._cachedTextureMatrix.m[4] = this._t2.x;
  19127. this._cachedTextureMatrix.m[5] = this._t2.y;
  19128. this._cachedTextureMatrix.m[6] = this._t2.z;
  19129. this._cachedTextureMatrix.m[8] = this._t0.x;
  19130. this._cachedTextureMatrix.m[9] = this._t0.y;
  19131. this._cachedTextureMatrix.m[10] = this._t0.z;
  19132. return this._cachedTextureMatrix;
  19133. };
  19134. Texture.prototype.getReflectionTextureMatrix = function () {
  19135. if (this.uOffset === this._cachedUOffset &&
  19136. this.vOffset === this._cachedVOffset &&
  19137. this.uScale === this._cachedUScale &&
  19138. this.vScale === this._cachedVScale &&
  19139. this.coordinatesMode === this._cachedCoordinatesMode) {
  19140. return this._cachedTextureMatrix;
  19141. }
  19142. if (!this._cachedTextureMatrix) {
  19143. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19144. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19145. }
  19146. this._cachedCoordinatesMode = this.coordinatesMode;
  19147. switch (this.coordinatesMode) {
  19148. case Texture.PLANAR_MODE:
  19149. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19150. this._cachedTextureMatrix[0] = this.uScale;
  19151. this._cachedTextureMatrix[5] = this.vScale;
  19152. this._cachedTextureMatrix[12] = this.uOffset;
  19153. this._cachedTextureMatrix[13] = this.vOffset;
  19154. break;
  19155. case Texture.PROJECTION_MODE:
  19156. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19157. this._projectionModeMatrix.m[0] = 0.5;
  19158. this._projectionModeMatrix.m[5] = -0.5;
  19159. this._projectionModeMatrix.m[10] = 0.0;
  19160. this._projectionModeMatrix.m[12] = 0.5;
  19161. this._projectionModeMatrix.m[13] = 0.5;
  19162. this._projectionModeMatrix.m[14] = 1.0;
  19163. this._projectionModeMatrix.m[15] = 1.0;
  19164. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19165. break;
  19166. default:
  19167. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19168. break;
  19169. }
  19170. return this._cachedTextureMatrix;
  19171. };
  19172. Texture.prototype.clone = function () {
  19173. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  19174. // Base texture
  19175. newTexture.hasAlpha = this.hasAlpha;
  19176. newTexture.level = this.level;
  19177. newTexture.wrapU = this.wrapU;
  19178. newTexture.wrapV = this.wrapV;
  19179. newTexture.coordinatesIndex = this.coordinatesIndex;
  19180. newTexture.coordinatesMode = this.coordinatesMode;
  19181. // Texture
  19182. newTexture.uOffset = this.uOffset;
  19183. newTexture.vOffset = this.vOffset;
  19184. newTexture.uScale = this.uScale;
  19185. newTexture.vScale = this.vScale;
  19186. newTexture.uAng = this.uAng;
  19187. newTexture.vAng = this.vAng;
  19188. newTexture.wAng = this.wAng;
  19189. return newTexture;
  19190. };
  19191. Texture.prototype.serialize = function () {
  19192. if (!this.name) {
  19193. return null;
  19194. }
  19195. var serializationObject = _super.prototype.serialize.call(this);
  19196. serializationObject.uOffset = this.uOffset;
  19197. serializationObject.vOffset = this.vOffset;
  19198. serializationObject.uScale = this.uScale;
  19199. serializationObject.vScale = this.vScale;
  19200. serializationObject.uAng = this.uAng;
  19201. serializationObject.vAng = this.vAng;
  19202. serializationObject.wAng = this.wAng;
  19203. return serializationObject;
  19204. };
  19205. // Statics
  19206. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  19207. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19208. if (onLoad === void 0) { onLoad = null; }
  19209. if (onError === void 0) { onError = null; }
  19210. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  19211. };
  19212. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19213. if (parsedTexture.isCube) {
  19214. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19215. }
  19216. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19217. return null;
  19218. }
  19219. var texture;
  19220. if (parsedTexture.mirrorPlane) {
  19221. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19222. texture._waitingRenderList = parsedTexture.renderList;
  19223. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19224. }
  19225. else if (parsedTexture.isRenderTarget) {
  19226. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19227. texture._waitingRenderList = parsedTexture.renderList;
  19228. }
  19229. else {
  19230. if (parsedTexture.base64String) {
  19231. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19232. }
  19233. else {
  19234. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19235. }
  19236. }
  19237. texture.name = parsedTexture.name;
  19238. texture.hasAlpha = parsedTexture.hasAlpha;
  19239. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19240. texture.level = parsedTexture.level;
  19241. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19242. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19243. texture.uOffset = parsedTexture.uOffset;
  19244. texture.vOffset = parsedTexture.vOffset;
  19245. texture.uScale = parsedTexture.uScale;
  19246. texture.vScale = parsedTexture.vScale;
  19247. texture.uAng = parsedTexture.uAng;
  19248. texture.vAng = parsedTexture.vAng;
  19249. texture.wAng = parsedTexture.wAng;
  19250. texture.wrapU = parsedTexture.wrapU;
  19251. texture.wrapV = parsedTexture.wrapV;
  19252. // Animations
  19253. if (parsedTexture.animations) {
  19254. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19255. var parsedAnimation = parsedTexture.animations[animationIndex];
  19256. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19257. }
  19258. }
  19259. return texture;
  19260. };
  19261. // Constants
  19262. Texture.NEAREST_SAMPLINGMODE = 1;
  19263. Texture.BILINEAR_SAMPLINGMODE = 2;
  19264. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19265. Texture.EXPLICIT_MODE = 0;
  19266. Texture.SPHERICAL_MODE = 1;
  19267. Texture.PLANAR_MODE = 2;
  19268. Texture.CUBIC_MODE = 3;
  19269. Texture.PROJECTION_MODE = 4;
  19270. Texture.SKYBOX_MODE = 5;
  19271. Texture.INVCUBIC_MODE = 6;
  19272. Texture.EQUIRECTANGULAR_MODE = 7;
  19273. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19274. Texture.CLAMP_ADDRESSMODE = 0;
  19275. Texture.WRAP_ADDRESSMODE = 1;
  19276. Texture.MIRROR_ADDRESSMODE = 2;
  19277. return Texture;
  19278. })(BABYLON.BaseTexture);
  19279. BABYLON.Texture = Texture;
  19280. })(BABYLON || (BABYLON = {}));
  19281. var BABYLON;
  19282. (function (BABYLON) {
  19283. var CubeTexture = (function (_super) {
  19284. __extends(CubeTexture, _super);
  19285. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  19286. _super.call(this, scene);
  19287. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  19288. this.name = rootUrl;
  19289. this.url = rootUrl;
  19290. this._noMipmap = noMipmap;
  19291. this.hasAlpha = false;
  19292. if (!rootUrl && !files) {
  19293. return;
  19294. }
  19295. this._texture = this._getFromCache(rootUrl, noMipmap);
  19296. if (!files) {
  19297. if (!extensions) {
  19298. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  19299. }
  19300. files = [];
  19301. for (var index = 0; index < extensions.length; index++) {
  19302. files.push(rootUrl + extensions[index]);
  19303. }
  19304. this._extensions = extensions;
  19305. }
  19306. this._files = files;
  19307. if (!this._texture) {
  19308. if (!scene.useDelayedTextureLoading) {
  19309. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  19310. }
  19311. else {
  19312. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19313. }
  19314. }
  19315. this.isCube = true;
  19316. this._textureMatrix = BABYLON.Matrix.Identity();
  19317. }
  19318. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  19319. return new CubeTexture("", scene, null, noMipmap, files);
  19320. };
  19321. CubeTexture.prototype.clone = function () {
  19322. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  19323. // Base texture
  19324. newTexture.level = this.level;
  19325. newTexture.wrapU = this.wrapU;
  19326. newTexture.wrapV = this.wrapV;
  19327. newTexture.coordinatesIndex = this.coordinatesIndex;
  19328. newTexture.coordinatesMode = this.coordinatesMode;
  19329. return newTexture;
  19330. };
  19331. // Methods
  19332. CubeTexture.prototype.delayLoad = function () {
  19333. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19334. return;
  19335. }
  19336. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19337. this._texture = this._getFromCache(this.url, this._noMipmap);
  19338. if (!this._texture) {
  19339. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  19340. }
  19341. };
  19342. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  19343. return this._textureMatrix;
  19344. };
  19345. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  19346. var texture = null;
  19347. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19348. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19349. texture.name = parsedTexture.name;
  19350. texture.hasAlpha = parsedTexture.hasAlpha;
  19351. texture.level = parsedTexture.level;
  19352. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19353. }
  19354. return texture;
  19355. };
  19356. CubeTexture.prototype.serialize = function () {
  19357. if (!this.name) {
  19358. return null;
  19359. }
  19360. var serializationObject = {};
  19361. serializationObject.name = this.name;
  19362. serializationObject.hasAlpha = this.hasAlpha;
  19363. serializationObject.isCube = true;
  19364. serializationObject.level = this.level;
  19365. serializationObject.coordinatesMode = this.coordinatesMode;
  19366. return serializationObject;
  19367. };
  19368. return CubeTexture;
  19369. })(BABYLON.BaseTexture);
  19370. BABYLON.CubeTexture = CubeTexture;
  19371. })(BABYLON || (BABYLON = {}));
  19372. var BABYLON;
  19373. (function (BABYLON) {
  19374. var RenderTargetTexture = (function (_super) {
  19375. __extends(RenderTargetTexture, _super);
  19376. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  19377. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  19378. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  19379. if (isCube === void 0) { isCube = false; }
  19380. _super.call(this, null, scene, !generateMipMaps);
  19381. this.isCube = isCube;
  19382. this.renderList = new Array();
  19383. this.renderParticles = true;
  19384. this.renderSprites = false;
  19385. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  19386. this._currentRefreshId = -1;
  19387. this._refreshRate = 1;
  19388. this.name = name;
  19389. this.isRenderTarget = true;
  19390. this._size = size;
  19391. this._generateMipMaps = generateMipMaps;
  19392. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  19393. if (isCube) {
  19394. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  19395. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  19396. this._textureMatrix = BABYLON.Matrix.Identity();
  19397. }
  19398. else {
  19399. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  19400. }
  19401. // Rendering groups
  19402. this._renderingManager = new BABYLON.RenderingManager(scene);
  19403. }
  19404. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  19405. get: function () {
  19406. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  19412. get: function () {
  19413. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  19414. },
  19415. enumerable: true,
  19416. configurable: true
  19417. });
  19418. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  19419. get: function () {
  19420. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  19421. },
  19422. enumerable: true,
  19423. configurable: true
  19424. });
  19425. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  19426. this._currentRefreshId = -1;
  19427. };
  19428. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  19429. get: function () {
  19430. return this._refreshRate;
  19431. },
  19432. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  19433. set: function (value) {
  19434. this._refreshRate = value;
  19435. this.resetRefreshCounter();
  19436. },
  19437. enumerable: true,
  19438. configurable: true
  19439. });
  19440. RenderTargetTexture.prototype._shouldRender = function () {
  19441. if (this._currentRefreshId === -1) {
  19442. this._currentRefreshId = 1;
  19443. return true;
  19444. }
  19445. if (this.refreshRate === this._currentRefreshId) {
  19446. this._currentRefreshId = 1;
  19447. return true;
  19448. }
  19449. this._currentRefreshId++;
  19450. return false;
  19451. };
  19452. RenderTargetTexture.prototype.isReady = function () {
  19453. if (!this.getScene().renderTargetsEnabled) {
  19454. return false;
  19455. }
  19456. return _super.prototype.isReady.call(this);
  19457. };
  19458. RenderTargetTexture.prototype.getRenderSize = function () {
  19459. return this._size;
  19460. };
  19461. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  19462. get: function () {
  19463. return true;
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. RenderTargetTexture.prototype.scale = function (ratio) {
  19469. var newSize = this._size * ratio;
  19470. this.resize(newSize, this._generateMipMaps);
  19471. };
  19472. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  19473. if (this.isCube) {
  19474. return this._textureMatrix;
  19475. }
  19476. return _super.prototype.getReflectionTextureMatrix.call(this);
  19477. };
  19478. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  19479. this.releaseInternalTexture();
  19480. if (this.isCube) {
  19481. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  19482. }
  19483. else {
  19484. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  19485. }
  19486. };
  19487. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  19488. var scene = this.getScene();
  19489. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  19490. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  19491. }
  19492. if (this._waitingRenderList) {
  19493. this.renderList = [];
  19494. for (var index = 0; index < this._waitingRenderList.length; index++) {
  19495. var id = this._waitingRenderList[index];
  19496. this.renderList.push(scene.getMeshByID(id));
  19497. }
  19498. delete this._waitingRenderList;
  19499. }
  19500. if (this.renderList && this.renderList.length === 0) {
  19501. return;
  19502. }
  19503. // Prepare renderingManager
  19504. this._renderingManager.reset();
  19505. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  19506. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  19507. var mesh = currentRenderList[meshIndex];
  19508. if (mesh) {
  19509. if (!mesh.isReady()) {
  19510. // Reset _currentRefreshId
  19511. this.resetRefreshCounter();
  19512. continue;
  19513. }
  19514. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  19515. mesh._activate(scene.getRenderId());
  19516. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19517. var subMesh = mesh.subMeshes[subIndex];
  19518. scene._activeIndices += subMesh.indexCount;
  19519. this._renderingManager.dispatch(subMesh);
  19520. }
  19521. }
  19522. }
  19523. }
  19524. if (this.isCube) {
  19525. for (var face = 0; face < 6; face++) {
  19526. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  19527. scene.incrementRenderId();
  19528. }
  19529. }
  19530. else {
  19531. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  19532. }
  19533. if (this.onAfterUnbind) {
  19534. this.onAfterUnbind();
  19535. }
  19536. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  19537. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  19538. }
  19539. scene.resetCachedMaterial();
  19540. };
  19541. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  19542. var scene = this.getScene();
  19543. var engine = scene.getEngine();
  19544. // Bind
  19545. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  19546. if (this.isCube) {
  19547. engine.bindFramebuffer(this._texture, faceIndex);
  19548. }
  19549. else {
  19550. engine.bindFramebuffer(this._texture);
  19551. }
  19552. }
  19553. if (this.onBeforeRender) {
  19554. this.onBeforeRender(faceIndex);
  19555. }
  19556. // Clear
  19557. if (this.onClear) {
  19558. this.onClear(engine);
  19559. }
  19560. else {
  19561. engine.clear(scene.clearColor, true, true);
  19562. }
  19563. if (!this._doNotChangeAspectRatio) {
  19564. scene.updateTransformMatrix(true);
  19565. }
  19566. // Render
  19567. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  19568. if (useCameraPostProcess) {
  19569. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  19570. }
  19571. if (!this._doNotChangeAspectRatio) {
  19572. scene.updateTransformMatrix(true);
  19573. }
  19574. if (this.onAfterRender) {
  19575. this.onAfterRender(faceIndex);
  19576. }
  19577. // Dump ?
  19578. if (dumpForDebug) {
  19579. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  19580. }
  19581. // Unbind
  19582. if (!this.isCube || faceIndex === 5) {
  19583. if (this.isCube) {
  19584. if (faceIndex === 5) {
  19585. engine.generateMipMapsForCubemap(this._texture);
  19586. }
  19587. }
  19588. engine.unBindFramebuffer(this._texture, this.isCube);
  19589. }
  19590. };
  19591. RenderTargetTexture.prototype.clone = function () {
  19592. var textureSize = this.getSize();
  19593. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19594. // Base texture
  19595. newTexture.hasAlpha = this.hasAlpha;
  19596. newTexture.level = this.level;
  19597. // RenderTarget Texture
  19598. newTexture.coordinatesMode = this.coordinatesMode;
  19599. newTexture.renderList = this.renderList.slice(0);
  19600. return newTexture;
  19601. };
  19602. RenderTargetTexture.prototype.serialize = function () {
  19603. if (!this.name) {
  19604. return null;
  19605. }
  19606. var serializationObject = _super.prototype.serialize.call(this);
  19607. serializationObject.renderTargetSize = this.getRenderSize();
  19608. serializationObject.renderList = [];
  19609. for (var index = 0; index < this.renderList.length; index++) {
  19610. serializationObject.renderList.push(this.renderList[index].id);
  19611. }
  19612. return serializationObject;
  19613. };
  19614. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  19615. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  19616. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  19617. return RenderTargetTexture;
  19618. })(BABYLON.Texture);
  19619. BABYLON.RenderTargetTexture = RenderTargetTexture;
  19620. })(BABYLON || (BABYLON = {}));
  19621. var BABYLON;
  19622. (function (BABYLON) {
  19623. var ProceduralTexture = (function (_super) {
  19624. __extends(ProceduralTexture, _super);
  19625. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  19626. if (generateMipMaps === void 0) { generateMipMaps = true; }
  19627. if (isCube === void 0) { isCube = false; }
  19628. _super.call(this, null, scene, !generateMipMaps);
  19629. this.isCube = isCube;
  19630. this.isEnabled = true;
  19631. this._currentRefreshId = -1;
  19632. this._refreshRate = 1;
  19633. this._vertexDeclaration = [2];
  19634. this._vertexStrideSize = 2 * 4;
  19635. this._uniforms = new Array();
  19636. this._samplers = new Array();
  19637. this._textures = new Array();
  19638. this._floats = new Array();
  19639. this._floatsArrays = {};
  19640. this._colors3 = new Array();
  19641. this._colors4 = new Array();
  19642. this._vectors2 = new Array();
  19643. this._vectors3 = new Array();
  19644. this._matrices = new Array();
  19645. this._fallbackTextureUsed = false;
  19646. scene._proceduralTextures.push(this);
  19647. this.name = name;
  19648. this.isRenderTarget = true;
  19649. this._size = size;
  19650. this._generateMipMaps = generateMipMaps;
  19651. this.setFragment(fragment);
  19652. this._fallbackTexture = fallbackTexture;
  19653. if (isCube) {
  19654. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  19655. this.setFloat("face", 0);
  19656. }
  19657. else {
  19658. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  19659. }
  19660. // VBO
  19661. var vertices = [];
  19662. vertices.push(1, 1);
  19663. vertices.push(-1, 1);
  19664. vertices.push(-1, -1);
  19665. vertices.push(1, -1);
  19666. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19667. // Indices
  19668. var indices = [];
  19669. indices.push(0);
  19670. indices.push(1);
  19671. indices.push(2);
  19672. indices.push(0);
  19673. indices.push(2);
  19674. indices.push(3);
  19675. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19676. }
  19677. ProceduralTexture.prototype.reset = function () {
  19678. if (this._effect === undefined) {
  19679. return;
  19680. }
  19681. var engine = this.getScene().getEngine();
  19682. engine._releaseEffect(this._effect);
  19683. };
  19684. ProceduralTexture.prototype.isReady = function () {
  19685. var _this = this;
  19686. var engine = this.getScene().getEngine();
  19687. var shaders;
  19688. if (!this._fragment) {
  19689. return false;
  19690. }
  19691. if (this._fallbackTextureUsed) {
  19692. return true;
  19693. }
  19694. if (this._fragment.fragmentElement !== undefined) {
  19695. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  19696. }
  19697. else {
  19698. shaders = { vertex: "procedural", fragment: this._fragment };
  19699. }
  19700. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  19701. _this.releaseInternalTexture();
  19702. if (_this._fallbackTexture) {
  19703. _this._texture = _this._fallbackTexture._texture;
  19704. _this._texture.references++;
  19705. }
  19706. _this._fallbackTextureUsed = true;
  19707. });
  19708. return this._effect.isReady();
  19709. };
  19710. ProceduralTexture.prototype.resetRefreshCounter = function () {
  19711. this._currentRefreshId = -1;
  19712. };
  19713. ProceduralTexture.prototype.setFragment = function (fragment) {
  19714. this._fragment = fragment;
  19715. };
  19716. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  19717. get: function () {
  19718. return this._refreshRate;
  19719. },
  19720. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  19721. set: function (value) {
  19722. this._refreshRate = value;
  19723. this.resetRefreshCounter();
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. ProceduralTexture.prototype._shouldRender = function () {
  19729. if (!this.isEnabled || !this.isReady() || !this._texture) {
  19730. return false;
  19731. }
  19732. if (this._fallbackTextureUsed) {
  19733. return false;
  19734. }
  19735. if (this._currentRefreshId === -1) {
  19736. this._currentRefreshId = 1;
  19737. return true;
  19738. }
  19739. if (this.refreshRate === this._currentRefreshId) {
  19740. this._currentRefreshId = 1;
  19741. return true;
  19742. }
  19743. this._currentRefreshId++;
  19744. return false;
  19745. };
  19746. ProceduralTexture.prototype.getRenderSize = function () {
  19747. return this._size;
  19748. };
  19749. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  19750. if (this._fallbackTextureUsed) {
  19751. return;
  19752. }
  19753. this.releaseInternalTexture();
  19754. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  19755. };
  19756. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  19757. if (this._uniforms.indexOf(uniformName) === -1) {
  19758. this._uniforms.push(uniformName);
  19759. }
  19760. };
  19761. ProceduralTexture.prototype.setTexture = function (name, texture) {
  19762. if (this._samplers.indexOf(name) === -1) {
  19763. this._samplers.push(name);
  19764. }
  19765. this._textures[name] = texture;
  19766. return this;
  19767. };
  19768. ProceduralTexture.prototype.setFloat = function (name, value) {
  19769. this._checkUniform(name);
  19770. this._floats[name] = value;
  19771. return this;
  19772. };
  19773. ProceduralTexture.prototype.setFloats = function (name, value) {
  19774. this._checkUniform(name);
  19775. this._floatsArrays[name] = value;
  19776. return this;
  19777. };
  19778. ProceduralTexture.prototype.setColor3 = function (name, value) {
  19779. this._checkUniform(name);
  19780. this._colors3[name] = value;
  19781. return this;
  19782. };
  19783. ProceduralTexture.prototype.setColor4 = function (name, value) {
  19784. this._checkUniform(name);
  19785. this._colors4[name] = value;
  19786. return this;
  19787. };
  19788. ProceduralTexture.prototype.setVector2 = function (name, value) {
  19789. this._checkUniform(name);
  19790. this._vectors2[name] = value;
  19791. return this;
  19792. };
  19793. ProceduralTexture.prototype.setVector3 = function (name, value) {
  19794. this._checkUniform(name);
  19795. this._vectors3[name] = value;
  19796. return this;
  19797. };
  19798. ProceduralTexture.prototype.setMatrix = function (name, value) {
  19799. this._checkUniform(name);
  19800. this._matrices[name] = value;
  19801. return this;
  19802. };
  19803. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  19804. var scene = this.getScene();
  19805. var engine = scene.getEngine();
  19806. // Render
  19807. engine.enableEffect(this._effect);
  19808. engine.setState(false);
  19809. // Texture
  19810. for (var name in this._textures) {
  19811. this._effect.setTexture(name, this._textures[name]);
  19812. }
  19813. // Float
  19814. for (name in this._floats) {
  19815. this._effect.setFloat(name, this._floats[name]);
  19816. }
  19817. // Floats
  19818. for (name in this._floatsArrays) {
  19819. this._effect.setArray(name, this._floatsArrays[name]);
  19820. }
  19821. // Color3
  19822. for (name in this._colors3) {
  19823. this._effect.setColor3(name, this._colors3[name]);
  19824. }
  19825. // Color4
  19826. for (name in this._colors4) {
  19827. var color = this._colors4[name];
  19828. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19829. }
  19830. // Vector2
  19831. for (name in this._vectors2) {
  19832. this._effect.setVector2(name, this._vectors2[name]);
  19833. }
  19834. // Vector3
  19835. for (name in this._vectors3) {
  19836. this._effect.setVector3(name, this._vectors3[name]);
  19837. }
  19838. // Matrix
  19839. for (name in this._matrices) {
  19840. this._effect.setMatrix(name, this._matrices[name]);
  19841. }
  19842. // VBOs
  19843. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19844. if (this.isCube) {
  19845. for (var face = 0; face < 6; face++) {
  19846. engine.bindFramebuffer(this._texture, face);
  19847. this._effect.setFloat("face", face);
  19848. // Clear
  19849. engine.clear(scene.clearColor, true, true);
  19850. // Draw order
  19851. engine.draw(true, 0, 6);
  19852. // Mipmaps
  19853. if (face === 5) {
  19854. engine.generateMipMapsForCubemap(this._texture);
  19855. }
  19856. }
  19857. }
  19858. else {
  19859. engine.bindFramebuffer(this._texture);
  19860. // Clear
  19861. engine.clear(scene.clearColor, true, true);
  19862. // Draw order
  19863. engine.draw(true, 0, 6);
  19864. }
  19865. // Unbind
  19866. engine.unBindFramebuffer(this._texture, this.isCube);
  19867. if (this.onGenerated) {
  19868. this.onGenerated();
  19869. }
  19870. };
  19871. ProceduralTexture.prototype.clone = function () {
  19872. var textureSize = this.getSize();
  19873. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  19874. // Base texture
  19875. newTexture.hasAlpha = this.hasAlpha;
  19876. newTexture.level = this.level;
  19877. // RenderTarget Texture
  19878. newTexture.coordinatesMode = this.coordinatesMode;
  19879. return newTexture;
  19880. };
  19881. ProceduralTexture.prototype.dispose = function () {
  19882. var index = this.getScene()._proceduralTextures.indexOf(this);
  19883. if (index >= 0) {
  19884. this.getScene()._proceduralTextures.splice(index, 1);
  19885. }
  19886. _super.prototype.dispose.call(this);
  19887. };
  19888. return ProceduralTexture;
  19889. })(BABYLON.Texture);
  19890. BABYLON.ProceduralTexture = ProceduralTexture;
  19891. })(BABYLON || (BABYLON = {}));
  19892. var BABYLON;
  19893. (function (BABYLON) {
  19894. var MirrorTexture = (function (_super) {
  19895. __extends(MirrorTexture, _super);
  19896. function MirrorTexture(name, size, scene, generateMipMaps) {
  19897. var _this = this;
  19898. _super.call(this, name, size, scene, generateMipMaps, true);
  19899. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  19900. this._transformMatrix = BABYLON.Matrix.Zero();
  19901. this._mirrorMatrix = BABYLON.Matrix.Zero();
  19902. this.onBeforeRender = function () {
  19903. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  19904. _this._savedViewMatrix = scene.getViewMatrix();
  19905. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  19906. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  19907. scene.clipPlane = _this.mirrorPlane;
  19908. scene.getEngine().cullBackFaces = false;
  19909. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  19910. };
  19911. this.onAfterRender = function () {
  19912. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  19913. scene.getEngine().cullBackFaces = true;
  19914. scene._mirroredCameraPosition = null;
  19915. delete scene.clipPlane;
  19916. };
  19917. }
  19918. MirrorTexture.prototype.clone = function () {
  19919. var textureSize = this.getSize();
  19920. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19921. // Base texture
  19922. newTexture.hasAlpha = this.hasAlpha;
  19923. newTexture.level = this.level;
  19924. // Mirror Texture
  19925. newTexture.mirrorPlane = this.mirrorPlane.clone();
  19926. newTexture.renderList = this.renderList.slice(0);
  19927. return newTexture;
  19928. };
  19929. MirrorTexture.prototype.serialize = function () {
  19930. if (!this.name) {
  19931. return null;
  19932. }
  19933. var serializationObject = _super.prototype.serialize.call(this);
  19934. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  19935. return serializationObject;
  19936. };
  19937. return MirrorTexture;
  19938. })(BABYLON.RenderTargetTexture);
  19939. BABYLON.MirrorTexture = MirrorTexture;
  19940. })(BABYLON || (BABYLON = {}));
  19941. var BABYLON;
  19942. (function (BABYLON) {
  19943. /**
  19944. * Creates a refraction texture used by refraction channel of the standard material.
  19945. * @param name the texture name
  19946. * @param size size of the underlying texture
  19947. * @param scene root scene
  19948. */
  19949. var RefractionTexture = (function (_super) {
  19950. __extends(RefractionTexture, _super);
  19951. function RefractionTexture(name, size, scene, generateMipMaps) {
  19952. var _this = this;
  19953. _super.call(this, name, size, scene, generateMipMaps, true);
  19954. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  19955. this.depth = 2.0;
  19956. this.onBeforeRender = function () {
  19957. scene.clipPlane = _this.refractionPlane;
  19958. };
  19959. this.onAfterRender = function () {
  19960. delete scene.clipPlane;
  19961. };
  19962. }
  19963. RefractionTexture.prototype.clone = function () {
  19964. var textureSize = this.getSize();
  19965. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19966. // Base texture
  19967. newTexture.hasAlpha = this.hasAlpha;
  19968. newTexture.level = this.level;
  19969. // Refraction Texture
  19970. newTexture.refractionPlane = this.refractionPlane.clone();
  19971. newTexture.renderList = this.renderList.slice(0);
  19972. newTexture.depth = this.depth;
  19973. return newTexture;
  19974. };
  19975. RefractionTexture.prototype.serialize = function () {
  19976. if (!this.name) {
  19977. return null;
  19978. }
  19979. var serializationObject = _super.prototype.serialize.call(this);
  19980. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  19981. serializationObject.depth = this.depth;
  19982. return serializationObject;
  19983. };
  19984. return RefractionTexture;
  19985. })(BABYLON.RenderTargetTexture);
  19986. BABYLON.RefractionTexture = RefractionTexture;
  19987. })(BABYLON || (BABYLON = {}));
  19988. var BABYLON;
  19989. (function (BABYLON) {
  19990. var DynamicTexture = (function (_super) {
  19991. __extends(DynamicTexture, _super);
  19992. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  19993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19994. _super.call(this, null, scene, !generateMipMaps);
  19995. this.name = name;
  19996. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19997. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19998. this._generateMipMaps = generateMipMaps;
  19999. if (options.getContext) {
  20000. this._canvas = options;
  20001. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  20002. }
  20003. else {
  20004. this._canvas = document.createElement("canvas");
  20005. if (options.width) {
  20006. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  20007. }
  20008. else {
  20009. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  20010. }
  20011. }
  20012. var textureSize = this.getSize();
  20013. this._canvas.width = textureSize.width;
  20014. this._canvas.height = textureSize.height;
  20015. this._context = this._canvas.getContext("2d");
  20016. }
  20017. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  20018. get: function () {
  20019. return true;
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. DynamicTexture.prototype.scale = function (ratio) {
  20025. var textureSize = this.getSize();
  20026. textureSize.width *= ratio;
  20027. textureSize.height *= ratio;
  20028. this._canvas.width = textureSize.width;
  20029. this._canvas.height = textureSize.height;
  20030. this.releaseInternalTexture();
  20031. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  20032. };
  20033. DynamicTexture.prototype.getContext = function () {
  20034. return this._context;
  20035. };
  20036. DynamicTexture.prototype.clear = function () {
  20037. var size = this.getSize();
  20038. this._context.fillRect(0, 0, size.width, size.height);
  20039. };
  20040. DynamicTexture.prototype.update = function (invertY) {
  20041. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  20042. };
  20043. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  20044. if (update === void 0) { update = true; }
  20045. var size = this.getSize();
  20046. if (clearColor) {
  20047. this._context.fillStyle = clearColor;
  20048. this._context.fillRect(0, 0, size.width, size.height);
  20049. }
  20050. this._context.font = font;
  20051. if (x === null) {
  20052. var textSize = this._context.measureText(text);
  20053. x = (size.width - textSize.width) / 2;
  20054. }
  20055. this._context.fillStyle = color;
  20056. this._context.fillText(text, x, y);
  20057. if (update) {
  20058. this.update(invertY);
  20059. }
  20060. };
  20061. DynamicTexture.prototype.clone = function () {
  20062. var textureSize = this.getSize();
  20063. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20064. // Base texture
  20065. newTexture.hasAlpha = this.hasAlpha;
  20066. newTexture.level = this.level;
  20067. // Dynamic Texture
  20068. newTexture.wrapU = this.wrapU;
  20069. newTexture.wrapV = this.wrapV;
  20070. return newTexture;
  20071. };
  20072. return DynamicTexture;
  20073. })(BABYLON.Texture);
  20074. BABYLON.DynamicTexture = DynamicTexture;
  20075. })(BABYLON || (BABYLON = {}));
  20076. var BABYLON;
  20077. (function (BABYLON) {
  20078. var VideoTexture = (function (_super) {
  20079. __extends(VideoTexture, _super);
  20080. /**
  20081. * Creates a video texture.
  20082. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  20083. * @param urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  20084. * @param scene is obviously the current scene.
  20085. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  20086. * @param invertY is false by default but can be used to invert video on Y axis
  20087. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  20088. */
  20089. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  20090. var _this = this;
  20091. if (generateMipMaps === void 0) { generateMipMaps = false; }
  20092. if (invertY === void 0) { invertY = false; }
  20093. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20094. _super.call(this, null, scene, !generateMipMaps, invertY);
  20095. this._autoLaunch = true;
  20096. var urls;
  20097. this.name = name;
  20098. if (urlsOrVideo instanceof HTMLVideoElement) {
  20099. this.video = urlsOrVideo;
  20100. }
  20101. else {
  20102. urls = urlsOrVideo;
  20103. this.video = document.createElement("video");
  20104. this.video.autoplay = false;
  20105. this.video.loop = true;
  20106. }
  20107. this.video.addEventListener("canplaythrough", function () {
  20108. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  20109. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20110. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20111. }
  20112. else {
  20113. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20114. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20115. generateMipMaps = false;
  20116. }
  20117. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  20118. _this._texture.isReady = true;
  20119. });
  20120. if (urls) {
  20121. urls.forEach(function (url) {
  20122. var source = document.createElement("source");
  20123. source.src = url;
  20124. _this.video.appendChild(source);
  20125. });
  20126. }
  20127. this._lastUpdate = BABYLON.Tools.Now;
  20128. }
  20129. VideoTexture.prototype.update = function () {
  20130. if (this._autoLaunch) {
  20131. this._autoLaunch = false;
  20132. this.video.play();
  20133. }
  20134. var now = BABYLON.Tools.Now;
  20135. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  20136. return false;
  20137. }
  20138. this._lastUpdate = now;
  20139. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  20140. return true;
  20141. };
  20142. return VideoTexture;
  20143. })(BABYLON.Texture);
  20144. BABYLON.VideoTexture = VideoTexture;
  20145. })(BABYLON || (BABYLON = {}));
  20146. var BABYLON;
  20147. (function (BABYLON) {
  20148. var CustomProceduralTexture = (function (_super) {
  20149. __extends(CustomProceduralTexture, _super);
  20150. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  20151. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  20152. this._animate = true;
  20153. this._time = 0;
  20154. this._texturePath = texturePath;
  20155. //Try to load json
  20156. this.loadJson(texturePath);
  20157. this.refreshRate = 1;
  20158. }
  20159. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  20160. var _this = this;
  20161. var that = this;
  20162. function noConfigFile() {
  20163. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  20164. try {
  20165. that.setFragment(that._texturePath);
  20166. }
  20167. catch (ex) {
  20168. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  20169. }
  20170. }
  20171. var configFileUrl = jsonUrl + "/config.json";
  20172. var xhr = new XMLHttpRequest();
  20173. xhr.open("GET", configFileUrl, true);
  20174. xhr.addEventListener("load", function () {
  20175. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  20176. try {
  20177. _this._config = JSON.parse(xhr.response);
  20178. _this.updateShaderUniforms();
  20179. _this.updateTextures();
  20180. _this.setFragment(_this._texturePath + "/custom");
  20181. _this._animate = _this._config.animate;
  20182. _this.refreshRate = _this._config.refreshrate;
  20183. }
  20184. catch (ex) {
  20185. noConfigFile();
  20186. }
  20187. }
  20188. else {
  20189. noConfigFile();
  20190. }
  20191. }, false);
  20192. xhr.addEventListener("error", function () {
  20193. noConfigFile();
  20194. }, false);
  20195. try {
  20196. xhr.send();
  20197. }
  20198. catch (ex) {
  20199. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  20200. }
  20201. };
  20202. CustomProceduralTexture.prototype.isReady = function () {
  20203. if (!_super.prototype.isReady.call(this)) {
  20204. return false;
  20205. }
  20206. for (var name in this._textures) {
  20207. var texture = this._textures[name];
  20208. if (!texture.isReady()) {
  20209. return false;
  20210. }
  20211. }
  20212. return true;
  20213. };
  20214. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  20215. if (this._animate) {
  20216. this._time += this.getScene().getAnimationRatio() * 0.03;
  20217. this.updateShaderUniforms();
  20218. }
  20219. _super.prototype.render.call(this, useCameraPostProcess);
  20220. };
  20221. CustomProceduralTexture.prototype.updateTextures = function () {
  20222. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  20223. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  20224. }
  20225. };
  20226. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  20227. if (this._config) {
  20228. for (var j = 0; j < this._config.uniforms.length; j++) {
  20229. var uniform = this._config.uniforms[j];
  20230. switch (uniform.type) {
  20231. case "float":
  20232. this.setFloat(uniform.name, uniform.value);
  20233. break;
  20234. case "color3":
  20235. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  20236. break;
  20237. case "color4":
  20238. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  20239. break;
  20240. case "vector2":
  20241. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  20242. break;
  20243. case "vector3":
  20244. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  20245. break;
  20246. }
  20247. }
  20248. }
  20249. this.setFloat("time", this._time);
  20250. };
  20251. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  20252. get: function () {
  20253. return this._animate;
  20254. },
  20255. set: function (value) {
  20256. this._animate = value;
  20257. },
  20258. enumerable: true,
  20259. configurable: true
  20260. });
  20261. return CustomProceduralTexture;
  20262. })(BABYLON.ProceduralTexture);
  20263. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  20264. })(BABYLON || (BABYLON = {}));
  20265. var BABYLON;
  20266. (function (BABYLON) {
  20267. var EffectFallbacks = (function () {
  20268. function EffectFallbacks() {
  20269. this._defines = {};
  20270. this._currentRank = 32;
  20271. this._maxRank = -1;
  20272. }
  20273. EffectFallbacks.prototype.addFallback = function (rank, define) {
  20274. if (!this._defines[rank]) {
  20275. if (rank < this._currentRank) {
  20276. this._currentRank = rank;
  20277. }
  20278. if (rank > this._maxRank) {
  20279. this._maxRank = rank;
  20280. }
  20281. this._defines[rank] = new Array();
  20282. }
  20283. this._defines[rank].push(define);
  20284. };
  20285. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  20286. this._meshRank = rank;
  20287. this._mesh = mesh;
  20288. if (rank > this._maxRank) {
  20289. this._maxRank = rank;
  20290. }
  20291. };
  20292. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  20293. get: function () {
  20294. return this._currentRank <= this._maxRank;
  20295. },
  20296. enumerable: true,
  20297. configurable: true
  20298. });
  20299. EffectFallbacks.prototype.reduce = function (currentDefines) {
  20300. var currentFallbacks = this._defines[this._currentRank];
  20301. for (var index = 0; index < currentFallbacks.length; index++) {
  20302. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  20303. }
  20304. if (this._mesh && this._currentRank === this._meshRank) {
  20305. this._mesh.computeBonesUsingShaders = false;
  20306. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  20307. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  20308. }
  20309. this._currentRank++;
  20310. return currentDefines;
  20311. };
  20312. return EffectFallbacks;
  20313. })();
  20314. BABYLON.EffectFallbacks = EffectFallbacks;
  20315. var Effect = (function () {
  20316. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  20317. var _this = this;
  20318. this._isReady = false;
  20319. this._compilationError = "";
  20320. this._valueCache = [];
  20321. this._engine = engine;
  20322. this.name = baseName;
  20323. this.defines = defines;
  20324. this._uniformsNames = uniformsNames.concat(samplers);
  20325. this._samplers = samplers;
  20326. this._attributesNames = attributesNames;
  20327. this.onError = onError;
  20328. this.onCompiled = onCompiled;
  20329. var vertexSource;
  20330. var fragmentSource;
  20331. if (baseName.vertexElement) {
  20332. vertexSource = document.getElementById(baseName.vertexElement);
  20333. if (!vertexSource) {
  20334. vertexSource = baseName.vertexElement;
  20335. }
  20336. }
  20337. else {
  20338. vertexSource = baseName.vertex || baseName;
  20339. }
  20340. if (baseName.fragmentElement) {
  20341. fragmentSource = document.getElementById(baseName.fragmentElement);
  20342. if (!fragmentSource) {
  20343. fragmentSource = baseName.fragmentElement;
  20344. }
  20345. }
  20346. else {
  20347. fragmentSource = baseName.fragment || baseName;
  20348. }
  20349. this._loadVertexShader(vertexSource, function (vertexCode) {
  20350. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  20351. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  20352. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  20353. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  20354. });
  20355. });
  20356. });
  20357. });
  20358. }
  20359. // Properties
  20360. Effect.prototype.isReady = function () {
  20361. return this._isReady;
  20362. };
  20363. Effect.prototype.getProgram = function () {
  20364. return this._program;
  20365. };
  20366. Effect.prototype.getAttributesNames = function () {
  20367. return this._attributesNames;
  20368. };
  20369. Effect.prototype.getAttributeLocation = function (index) {
  20370. return this._attributes[index];
  20371. };
  20372. Effect.prototype.getAttributeLocationByName = function (name) {
  20373. var index = this._attributesNames.indexOf(name);
  20374. return this._attributes[index];
  20375. };
  20376. Effect.prototype.getAttributesCount = function () {
  20377. return this._attributes.length;
  20378. };
  20379. Effect.prototype.getUniformIndex = function (uniformName) {
  20380. return this._uniformsNames.indexOf(uniformName);
  20381. };
  20382. Effect.prototype.getUniform = function (uniformName) {
  20383. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  20384. };
  20385. Effect.prototype.getSamplers = function () {
  20386. return this._samplers;
  20387. };
  20388. Effect.prototype.getCompilationError = function () {
  20389. return this._compilationError;
  20390. };
  20391. // Methods
  20392. Effect.prototype._loadVertexShader = function (vertex, callback) {
  20393. // DOM element ?
  20394. if (vertex instanceof HTMLElement) {
  20395. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  20396. callback(vertexCode);
  20397. return;
  20398. }
  20399. // Is in local store ?
  20400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  20401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  20402. return;
  20403. }
  20404. var vertexShaderUrl;
  20405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  20406. vertexShaderUrl = vertex;
  20407. }
  20408. else {
  20409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  20410. }
  20411. // Vertex shader
  20412. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  20413. };
  20414. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  20415. // DOM element ?
  20416. if (fragment instanceof HTMLElement) {
  20417. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  20418. callback(fragmentCode);
  20419. return;
  20420. }
  20421. // Is in local store ?
  20422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  20423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  20424. return;
  20425. }
  20426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  20427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  20428. return;
  20429. }
  20430. var fragmentShaderUrl;
  20431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  20432. fragmentShaderUrl = fragment;
  20433. }
  20434. else {
  20435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  20436. }
  20437. // Fragment shader
  20438. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  20439. };
  20440. Effect.prototype._dumpShadersName = function () {
  20441. if (this.name.vertexElement) {
  20442. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  20443. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  20444. }
  20445. else if (this.name.vertex) {
  20446. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  20447. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  20448. }
  20449. else {
  20450. BABYLON.Tools.Error("Vertex shader:" + this.name);
  20451. BABYLON.Tools.Error("Fragment shader:" + this.name);
  20452. }
  20453. };
  20454. Effect.prototype._processIncludes = function (sourceCode, callback) {
  20455. var _this = this;
  20456. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  20457. var match = regex.exec(sourceCode);
  20458. var returnValue = new String(sourceCode);
  20459. while (match != null) {
  20460. var includeFile = match[1];
  20461. if (Effect.IncludesShadersStore[includeFile]) {
  20462. // Substitution
  20463. var includeContent = Effect.IncludesShadersStore[includeFile];
  20464. if (match[2]) {
  20465. var splits = match[3].split(",");
  20466. for (var index = 0; index < splits.length; index += 2) {
  20467. var source = new RegExp(splits[index], "g");
  20468. var dest = splits[index + 1];
  20469. includeContent = includeContent.replace(source, dest);
  20470. }
  20471. }
  20472. if (match[4]) {
  20473. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  20474. }
  20475. // Replace
  20476. returnValue = returnValue.replace(match[0], includeContent);
  20477. }
  20478. else {
  20479. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  20480. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  20481. Effect.IncludesShadersStore[includeFile] = fileContent;
  20482. _this._processIncludes(returnValue, callback);
  20483. });
  20484. return;
  20485. }
  20486. match = regex.exec(sourceCode);
  20487. }
  20488. callback(returnValue);
  20489. };
  20490. Effect.prototype._processPrecision = function (source) {
  20491. if (source.indexOf("precision highp float") === -1) {
  20492. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  20493. source = "precision mediump float;\n" + source;
  20494. }
  20495. else {
  20496. source = "precision highp float;\n" + source;
  20497. }
  20498. }
  20499. else {
  20500. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  20501. source = source.replace("precision highp float", "precision mediump float");
  20502. }
  20503. }
  20504. return source;
  20505. };
  20506. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  20507. try {
  20508. var engine = this._engine;
  20509. // Precision
  20510. vertexSourceCode = this._processPrecision(vertexSourceCode);
  20511. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  20512. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  20513. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  20514. this._attributes = engine.getAttributes(this._program, attributesNames);
  20515. for (var index = 0; index < this._samplers.length; index++) {
  20516. var sampler = this.getUniform(this._samplers[index]);
  20517. if (sampler == null) {
  20518. this._samplers.splice(index, 1);
  20519. index--;
  20520. }
  20521. }
  20522. engine.bindSamplers(this);
  20523. this._isReady = true;
  20524. if (this.onCompiled) {
  20525. this.onCompiled(this);
  20526. }
  20527. }
  20528. catch (e) {
  20529. // Is it a problem with precision?
  20530. if (e.message.indexOf("highp") !== -1) {
  20531. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  20532. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  20533. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  20534. return;
  20535. }
  20536. // Let's go through fallbacks then
  20537. if (fallbacks && fallbacks.isMoreFallbacks) {
  20538. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  20539. this._dumpShadersName();
  20540. defines = fallbacks.reduce(defines);
  20541. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  20542. }
  20543. else {
  20544. BABYLON.Tools.Error("Unable to compile effect: ");
  20545. this._dumpShadersName();
  20546. BABYLON.Tools.Error("Defines: " + defines);
  20547. BABYLON.Tools.Error("Error: " + e.message);
  20548. this._compilationError = e.message;
  20549. if (this.onError) {
  20550. this.onError(this, this._compilationError);
  20551. }
  20552. }
  20553. }
  20554. };
  20555. Object.defineProperty(Effect.prototype, "isSupported", {
  20556. get: function () {
  20557. return this._compilationError === "";
  20558. },
  20559. enumerable: true,
  20560. configurable: true
  20561. });
  20562. Effect.prototype._bindTexture = function (channel, texture) {
  20563. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  20564. };
  20565. Effect.prototype.setTexture = function (channel, texture) {
  20566. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  20567. };
  20568. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  20569. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  20570. };
  20571. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  20572. if (!this._valueCache[uniformName]) {
  20573. this._valueCache[uniformName] = new BABYLON.Matrix();
  20574. }
  20575. for (var index = 0; index < 16; index++) {
  20576. this._valueCache[uniformName].m[index] = matrix.m[index];
  20577. }
  20578. };
  20579. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  20580. if (!this._valueCache[uniformName]) {
  20581. this._valueCache[uniformName] = [x, y];
  20582. return;
  20583. }
  20584. this._valueCache[uniformName][0] = x;
  20585. this._valueCache[uniformName][1] = y;
  20586. };
  20587. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  20588. if (!this._valueCache[uniformName]) {
  20589. this._valueCache[uniformName] = [x, y, z];
  20590. return;
  20591. }
  20592. this._valueCache[uniformName][0] = x;
  20593. this._valueCache[uniformName][1] = y;
  20594. this._valueCache[uniformName][2] = z;
  20595. };
  20596. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  20597. if (!this._valueCache[uniformName]) {
  20598. this._valueCache[uniformName] = [x, y, z, w];
  20599. return;
  20600. }
  20601. this._valueCache[uniformName][0] = x;
  20602. this._valueCache[uniformName][1] = y;
  20603. this._valueCache[uniformName][2] = z;
  20604. this._valueCache[uniformName][3] = w;
  20605. };
  20606. Effect.prototype.setArray = function (uniformName, array) {
  20607. this._engine.setArray(this.getUniform(uniformName), array);
  20608. return this;
  20609. };
  20610. Effect.prototype.setArray2 = function (uniformName, array) {
  20611. this._engine.setArray2(this.getUniform(uniformName), array);
  20612. return this;
  20613. };
  20614. Effect.prototype.setArray3 = function (uniformName, array) {
  20615. this._engine.setArray3(this.getUniform(uniformName), array);
  20616. return this;
  20617. };
  20618. Effect.prototype.setArray4 = function (uniformName, array) {
  20619. this._engine.setArray4(this.getUniform(uniformName), array);
  20620. return this;
  20621. };
  20622. Effect.prototype.setMatrices = function (uniformName, matrices) {
  20623. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  20624. return this;
  20625. };
  20626. Effect.prototype.setMatrix = function (uniformName, matrix) {
  20627. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  20628. // return this;
  20629. // this._cacheMatrix(uniformName, matrix);
  20630. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  20631. return this;
  20632. };
  20633. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  20634. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  20635. return this;
  20636. };
  20637. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  20638. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  20639. return this;
  20640. };
  20641. Effect.prototype.setFloat = function (uniformName, value) {
  20642. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  20643. return this;
  20644. this._valueCache[uniformName] = value;
  20645. this._engine.setFloat(this.getUniform(uniformName), value);
  20646. return this;
  20647. };
  20648. Effect.prototype.setBool = function (uniformName, bool) {
  20649. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  20650. return this;
  20651. this._valueCache[uniformName] = bool;
  20652. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  20653. return this;
  20654. };
  20655. Effect.prototype.setVector2 = function (uniformName, vector2) {
  20656. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  20657. return this;
  20658. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  20659. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  20660. return this;
  20661. };
  20662. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  20663. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  20664. return this;
  20665. this._cacheFloat2(uniformName, x, y);
  20666. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  20667. return this;
  20668. };
  20669. Effect.prototype.setVector3 = function (uniformName, vector3) {
  20670. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  20671. return this;
  20672. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  20673. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  20674. return this;
  20675. };
  20676. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  20677. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  20678. return this;
  20679. this._cacheFloat3(uniformName, x, y, z);
  20680. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  20681. return this;
  20682. };
  20683. Effect.prototype.setVector4 = function (uniformName, vector4) {
  20684. 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)
  20685. return this;
  20686. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  20687. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  20688. return this;
  20689. };
  20690. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  20691. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  20692. return this;
  20693. this._cacheFloat4(uniformName, x, y, z, w);
  20694. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  20695. return this;
  20696. };
  20697. Effect.prototype.setColor3 = function (uniformName, color3) {
  20698. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  20699. return this;
  20700. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  20701. this._engine.setColor3(this.getUniform(uniformName), color3);
  20702. return this;
  20703. };
  20704. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  20705. 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)
  20706. return this;
  20707. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  20708. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  20709. return this;
  20710. };
  20711. // Statics
  20712. Effect.ShadersStore = {};
  20713. Effect.IncludesShadersStore = {};
  20714. return Effect;
  20715. })();
  20716. BABYLON.Effect = Effect;
  20717. })(BABYLON || (BABYLON = {}));
  20718. var BABYLON;
  20719. (function (BABYLON) {
  20720. var maxSimultaneousLights = 4;
  20721. var MaterialHelper = (function () {
  20722. function MaterialHelper() {
  20723. }
  20724. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  20725. var lightIndex = 0;
  20726. var needNormals = false;
  20727. for (var index = 0; index < scene.lights.length; index++) {
  20728. var light = scene.lights[index];
  20729. if (!light.isEnabled()) {
  20730. continue;
  20731. }
  20732. // Excluded check
  20733. if (light._excludedMeshesIds.length > 0) {
  20734. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  20735. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  20736. if (excludedMesh) {
  20737. light.excludedMeshes.push(excludedMesh);
  20738. }
  20739. }
  20740. light._excludedMeshesIds = [];
  20741. }
  20742. // Included check
  20743. if (light._includedOnlyMeshesIds.length > 0) {
  20744. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  20745. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  20746. if (includedOnlyMesh) {
  20747. light.includedOnlyMeshes.push(includedOnlyMesh);
  20748. }
  20749. }
  20750. light._includedOnlyMeshesIds = [];
  20751. }
  20752. if (!light.canAffectMesh(mesh)) {
  20753. continue;
  20754. }
  20755. needNormals = true;
  20756. defines["LIGHT" + lightIndex] = true;
  20757. var type;
  20758. if (light instanceof BABYLON.SpotLight) {
  20759. type = "SPOTLIGHT" + lightIndex;
  20760. }
  20761. else if (light instanceof BABYLON.HemisphericLight) {
  20762. type = "HEMILIGHT" + lightIndex;
  20763. }
  20764. else if (light instanceof BABYLON.PointLight) {
  20765. type = "POINTLIGHT" + lightIndex;
  20766. }
  20767. else {
  20768. type = "DIRLIGHT" + lightIndex;
  20769. }
  20770. defines[type] = true;
  20771. // Specular
  20772. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  20773. defines["SPECULARTERM"] = true;
  20774. }
  20775. // Shadows
  20776. if (scene.shadowsEnabled) {
  20777. var shadowGenerator = light.getShadowGenerator();
  20778. if (mesh && mesh.receiveShadows && shadowGenerator) {
  20779. defines["SHADOW" + lightIndex] = true;
  20780. defines["SHADOWS"] = true;
  20781. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  20782. defines["SHADOWVSM" + lightIndex] = true;
  20783. }
  20784. if (shadowGenerator.usePoissonSampling) {
  20785. defines["SHADOWPCF" + lightIndex] = true;
  20786. }
  20787. }
  20788. }
  20789. lightIndex++;
  20790. if (lightIndex === maxSimultaneousLights)
  20791. break;
  20792. }
  20793. return needNormals;
  20794. };
  20795. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  20796. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  20797. if (!defines["LIGHT" + lightIndex]) {
  20798. continue;
  20799. }
  20800. if (lightIndex > 0) {
  20801. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  20802. }
  20803. if (defines["SHADOW" + lightIndex]) {
  20804. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  20805. }
  20806. if (defines["SHADOWPCF" + lightIndex]) {
  20807. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  20808. }
  20809. if (defines["SHADOWVSM" + lightIndex]) {
  20810. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  20811. }
  20812. }
  20813. };
  20814. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  20815. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  20816. fallbacks.addCPUSkinningFallback(0, mesh);
  20817. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20818. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20819. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  20820. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  20821. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  20822. }
  20823. }
  20824. };
  20825. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  20826. if (defines["INSTANCES"]) {
  20827. attribs.push("world0");
  20828. attribs.push("world1");
  20829. attribs.push("world2");
  20830. attribs.push("world3");
  20831. }
  20832. };
  20833. // Bindings
  20834. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  20835. var shadowGenerator = light.getShadowGenerator();
  20836. if (mesh.receiveShadows && shadowGenerator) {
  20837. if (!light.needCube()) {
  20838. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  20839. }
  20840. else {
  20841. if (!depthValuesAlreadySet) {
  20842. depthValuesAlreadySet = true;
  20843. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  20844. }
  20845. }
  20846. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  20847. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  20848. }
  20849. return depthValuesAlreadySet;
  20850. };
  20851. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  20852. if (light instanceof BABYLON.PointLight) {
  20853. // Point Light
  20854. light.transferToEffect(effect, "vLightData" + lightIndex);
  20855. }
  20856. else if (light instanceof BABYLON.DirectionalLight) {
  20857. // Directional Light
  20858. light.transferToEffect(effect, "vLightData" + lightIndex);
  20859. }
  20860. else if (light instanceof BABYLON.SpotLight) {
  20861. // Spot Light
  20862. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  20863. }
  20864. else if (light instanceof BABYLON.HemisphericLight) {
  20865. // Hemispheric Light
  20866. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  20867. }
  20868. };
  20869. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  20870. var lightIndex = 0;
  20871. var depthValuesAlreadySet = false;
  20872. for (var index = 0; index < scene.lights.length; index++) {
  20873. var light = scene.lights[index];
  20874. if (!light.isEnabled()) {
  20875. continue;
  20876. }
  20877. if (!light.canAffectMesh(mesh)) {
  20878. continue;
  20879. }
  20880. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  20881. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  20882. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  20883. if (defines["SPECULARTERM"]) {
  20884. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  20885. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  20886. }
  20887. // Shadows
  20888. if (scene.shadowsEnabled) {
  20889. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  20890. }
  20891. lightIndex++;
  20892. if (lightIndex === maxSimultaneousLights)
  20893. break;
  20894. }
  20895. };
  20896. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  20897. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  20898. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  20899. effect.setColor3("vFogColor", scene.fogColor);
  20900. }
  20901. };
  20902. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  20903. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  20904. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  20905. }
  20906. };
  20907. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  20908. if (defines["LOGARITHMICDEPTH"]) {
  20909. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  20910. }
  20911. };
  20912. MaterialHelper.BindClipPlane = function (effect, scene) {
  20913. if (scene.clipPlane) {
  20914. var clipPlane = scene.clipPlane;
  20915. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20916. }
  20917. };
  20918. return MaterialHelper;
  20919. })();
  20920. BABYLON.MaterialHelper = MaterialHelper;
  20921. })(BABYLON || (BABYLON = {}));
  20922. var BABYLON;
  20923. (function (BABYLON) {
  20924. var FresnelParameters = (function () {
  20925. function FresnelParameters() {
  20926. this.isEnabled = true;
  20927. this.leftColor = BABYLON.Color3.White();
  20928. this.rightColor = BABYLON.Color3.Black();
  20929. this.bias = 0;
  20930. this.power = 1;
  20931. }
  20932. FresnelParameters.prototype.clone = function () {
  20933. var newFresnelParameters = new FresnelParameters();
  20934. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  20935. return new FresnelParameters;
  20936. };
  20937. FresnelParameters.prototype.serialize = function () {
  20938. var serializationObject = {};
  20939. serializationObject.isEnabled = this.isEnabled;
  20940. serializationObject.leftColor = this.leftColor;
  20941. serializationObject.rightColor = this.rightColor;
  20942. serializationObject.bias = this.bias;
  20943. serializationObject.power = this.power;
  20944. return serializationObject;
  20945. };
  20946. FresnelParameters.Parse = function (parsedFresnelParameters) {
  20947. var fresnelParameters = new FresnelParameters();
  20948. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  20949. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  20950. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  20951. fresnelParameters.bias = parsedFresnelParameters.bias;
  20952. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  20953. return fresnelParameters;
  20954. };
  20955. return FresnelParameters;
  20956. })();
  20957. BABYLON.FresnelParameters = FresnelParameters;
  20958. })(BABYLON || (BABYLON = {}));
  20959. var BABYLON;
  20960. (function (BABYLON) {
  20961. var MaterialDefines = (function () {
  20962. function MaterialDefines() {
  20963. }
  20964. MaterialDefines.prototype.isEqual = function (other) {
  20965. for (var index = 0; index < this._keys.length; index++) {
  20966. var prop = this._keys[index];
  20967. if (this[prop] !== other[prop]) {
  20968. return false;
  20969. }
  20970. }
  20971. return true;
  20972. };
  20973. MaterialDefines.prototype.cloneTo = function (other) {
  20974. for (var index = 0; index < this._keys.length; index++) {
  20975. var prop = this._keys[index];
  20976. other[prop] = this[prop];
  20977. }
  20978. };
  20979. MaterialDefines.prototype.reset = function () {
  20980. for (var index = 0; index < this._keys.length; index++) {
  20981. var prop = this._keys[index];
  20982. if (typeof (this[prop]) === "number") {
  20983. this[prop] = 0;
  20984. }
  20985. else {
  20986. this[prop] = false;
  20987. }
  20988. }
  20989. };
  20990. MaterialDefines.prototype.toString = function () {
  20991. var result = "";
  20992. for (var index = 0; index < this._keys.length; index++) {
  20993. var prop = this._keys[index];
  20994. if (typeof (this[prop]) === "number") {
  20995. result += "#define " + prop + " " + this[prop] + "\n";
  20996. }
  20997. else if (this[prop]) {
  20998. result += "#define " + prop + "\n";
  20999. }
  21000. }
  21001. return result;
  21002. };
  21003. return MaterialDefines;
  21004. })();
  21005. BABYLON.MaterialDefines = MaterialDefines;
  21006. var Material = (function () {
  21007. function Material(name, scene, doNotAdd) {
  21008. this.name = name;
  21009. this.checkReadyOnEveryCall = false;
  21010. this.checkReadyOnlyOnce = false;
  21011. this.state = "";
  21012. this.alpha = 1.0;
  21013. this.backFaceCulling = true;
  21014. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  21015. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  21016. this.disableDepthWrite = false;
  21017. this.fogEnabled = true;
  21018. this.pointSize = 1.0;
  21019. this.zOffset = 0;
  21020. this._wasPreviouslyReady = false;
  21021. this._fillMode = Material.TriangleFillMode;
  21022. this.id = name;
  21023. this._scene = scene;
  21024. if (!doNotAdd) {
  21025. scene.materials.push(this);
  21026. }
  21027. }
  21028. Object.defineProperty(Material, "TriangleFillMode", {
  21029. get: function () {
  21030. return Material._TriangleFillMode;
  21031. },
  21032. enumerable: true,
  21033. configurable: true
  21034. });
  21035. Object.defineProperty(Material, "WireFrameFillMode", {
  21036. get: function () {
  21037. return Material._WireFrameFillMode;
  21038. },
  21039. enumerable: true,
  21040. configurable: true
  21041. });
  21042. Object.defineProperty(Material, "PointFillMode", {
  21043. get: function () {
  21044. return Material._PointFillMode;
  21045. },
  21046. enumerable: true,
  21047. configurable: true
  21048. });
  21049. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  21050. get: function () {
  21051. return Material._ClockWiseSideOrientation;
  21052. },
  21053. enumerable: true,
  21054. configurable: true
  21055. });
  21056. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  21057. get: function () {
  21058. return Material._CounterClockWiseSideOrientation;
  21059. },
  21060. enumerable: true,
  21061. configurable: true
  21062. });
  21063. Object.defineProperty(Material.prototype, "wireframe", {
  21064. get: function () {
  21065. return this._fillMode === Material.WireFrameFillMode;
  21066. },
  21067. set: function (value) {
  21068. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  21069. },
  21070. enumerable: true,
  21071. configurable: true
  21072. });
  21073. Object.defineProperty(Material.prototype, "pointsCloud", {
  21074. get: function () {
  21075. return this._fillMode === Material.PointFillMode;
  21076. },
  21077. set: function (value) {
  21078. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  21079. },
  21080. enumerable: true,
  21081. configurable: true
  21082. });
  21083. Object.defineProperty(Material.prototype, "fillMode", {
  21084. get: function () {
  21085. return this._fillMode;
  21086. },
  21087. set: function (value) {
  21088. this._fillMode = value;
  21089. },
  21090. enumerable: true,
  21091. configurable: true
  21092. });
  21093. /**
  21094. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21095. * subclasses should override adding information pertainent to themselves
  21096. */
  21097. Material.prototype.toString = function (fullDetails) {
  21098. var ret = "Name: " + this.name;
  21099. if (fullDetails) {
  21100. }
  21101. return ret;
  21102. };
  21103. Object.defineProperty(Material.prototype, "isFrozen", {
  21104. get: function () {
  21105. return this.checkReadyOnlyOnce;
  21106. },
  21107. enumerable: true,
  21108. configurable: true
  21109. });
  21110. Material.prototype.freeze = function () {
  21111. this.checkReadyOnlyOnce = true;
  21112. };
  21113. Material.prototype.unfreeze = function () {
  21114. this.checkReadyOnlyOnce = false;
  21115. };
  21116. Material.prototype.isReady = function (mesh, useInstances) {
  21117. return true;
  21118. };
  21119. Material.prototype.getEffect = function () {
  21120. return this._effect;
  21121. };
  21122. Material.prototype.getScene = function () {
  21123. return this._scene;
  21124. };
  21125. Material.prototype.needAlphaBlending = function () {
  21126. return (this.alpha < 1.0);
  21127. };
  21128. Material.prototype.needAlphaTesting = function () {
  21129. return false;
  21130. };
  21131. Material.prototype.getAlphaTestTexture = function () {
  21132. return null;
  21133. };
  21134. Material.prototype.trackCreation = function (onCompiled, onError) {
  21135. };
  21136. Material.prototype.markDirty = function () {
  21137. this._wasPreviouslyReady = false;
  21138. };
  21139. Material.prototype._preBind = function () {
  21140. var engine = this._scene.getEngine();
  21141. engine.enableEffect(this._effect);
  21142. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  21143. };
  21144. Material.prototype.bind = function (world, mesh) {
  21145. this._scene._cachedMaterial = this;
  21146. if (this.onBind) {
  21147. this.onBind(this, mesh);
  21148. }
  21149. if (this.disableDepthWrite) {
  21150. var engine = this._scene.getEngine();
  21151. this._cachedDepthWriteState = engine.getDepthWrite();
  21152. engine.setDepthWrite(false);
  21153. }
  21154. };
  21155. Material.prototype.bindOnlyWorldMatrix = function (world) {
  21156. };
  21157. Material.prototype.unbind = function () {
  21158. if (this.disableDepthWrite) {
  21159. var engine = this._scene.getEngine();
  21160. engine.setDepthWrite(this._cachedDepthWriteState);
  21161. }
  21162. };
  21163. Material.prototype.clone = function (name) {
  21164. return null;
  21165. };
  21166. Material.prototype.getBindedMeshes = function () {
  21167. var result = new Array();
  21168. for (var index = 0; index < this._scene.meshes.length; index++) {
  21169. var mesh = this._scene.meshes[index];
  21170. if (mesh.material === this) {
  21171. result.push(mesh);
  21172. }
  21173. }
  21174. return result;
  21175. };
  21176. Material.prototype.dispose = function (forceDisposeEffect) {
  21177. // Animations
  21178. this.getScene().stopAnimation(this);
  21179. // Remove from scene
  21180. var index = this._scene.materials.indexOf(this);
  21181. if (index >= 0) {
  21182. this._scene.materials.splice(index, 1);
  21183. }
  21184. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  21185. if (forceDisposeEffect && this._effect) {
  21186. this._scene.getEngine()._releaseEffect(this._effect);
  21187. this._effect = null;
  21188. }
  21189. // Remove from meshes
  21190. for (index = 0; index < this._scene.meshes.length; index++) {
  21191. var mesh = this._scene.meshes[index];
  21192. if (mesh.material === this) {
  21193. mesh.material = null;
  21194. }
  21195. }
  21196. // Callback
  21197. if (this.onDispose) {
  21198. this.onDispose();
  21199. }
  21200. };
  21201. Material.prototype.serialize = function () {
  21202. return BABYLON.SerializationHelper.Serialize(this);
  21203. };
  21204. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  21205. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  21206. multiMaterial.id = parsedMultiMaterial.id;
  21207. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  21208. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21209. var subMatId = parsedMultiMaterial.materials[matIndex];
  21210. if (subMatId) {
  21211. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  21212. }
  21213. else {
  21214. multiMaterial.subMaterials.push(null);
  21215. }
  21216. }
  21217. return multiMaterial;
  21218. };
  21219. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  21220. if (!parsedMaterial.customType) {
  21221. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  21222. }
  21223. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  21224. return materialType.Parse(parsedMaterial, scene, rootUrl);
  21225. ;
  21226. };
  21227. Material._TriangleFillMode = 0;
  21228. Material._WireFrameFillMode = 1;
  21229. Material._PointFillMode = 2;
  21230. Material._ClockWiseSideOrientation = 0;
  21231. Material._CounterClockWiseSideOrientation = 1;
  21232. __decorate([
  21233. BABYLON.serialize()
  21234. ], Material.prototype, "id", void 0);
  21235. __decorate([
  21236. BABYLON.serialize()
  21237. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  21238. __decorate([
  21239. BABYLON.serialize()
  21240. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  21241. __decorate([
  21242. BABYLON.serialize()
  21243. ], Material.prototype, "state", void 0);
  21244. __decorate([
  21245. BABYLON.serialize()
  21246. ], Material.prototype, "alpha", void 0);
  21247. __decorate([
  21248. BABYLON.serialize()
  21249. ], Material.prototype, "backFaceCulling", void 0);
  21250. __decorate([
  21251. BABYLON.serialize()
  21252. ], Material.prototype, "sideOrientation", void 0);
  21253. __decorate([
  21254. BABYLON.serialize()
  21255. ], Material.prototype, "alphaMode", void 0);
  21256. __decorate([
  21257. BABYLON.serialize()
  21258. ], Material.prototype, "disableDepthWrite", void 0);
  21259. __decorate([
  21260. BABYLON.serialize()
  21261. ], Material.prototype, "fogEnabled", void 0);
  21262. __decorate([
  21263. BABYLON.serialize()
  21264. ], Material.prototype, "pointSize", void 0);
  21265. __decorate([
  21266. BABYLON.serialize()
  21267. ], Material.prototype, "zOffset", void 0);
  21268. __decorate([
  21269. BABYLON.serialize()
  21270. ], Material.prototype, "wireframe", null);
  21271. __decorate([
  21272. BABYLON.serialize()
  21273. ], Material.prototype, "pointsCloud", null);
  21274. __decorate([
  21275. BABYLON.serialize()
  21276. ], Material.prototype, "fillMode", null);
  21277. return Material;
  21278. })();
  21279. BABYLON.Material = Material;
  21280. })(BABYLON || (BABYLON = {}));
  21281. var BABYLON;
  21282. (function (BABYLON) {
  21283. var StandardMaterialDefines = (function (_super) {
  21284. __extends(StandardMaterialDefines, _super);
  21285. function StandardMaterialDefines() {
  21286. _super.call(this);
  21287. this.DIFFUSE = false;
  21288. this.AMBIENT = false;
  21289. this.OPACITY = false;
  21290. this.OPACITYRGB = false;
  21291. this.REFLECTION = false;
  21292. this.EMISSIVE = false;
  21293. this.SPECULAR = false;
  21294. this.BUMP = false;
  21295. this.PARALLAX = false;
  21296. this.PARALLAXOCCLUSION = false;
  21297. this.SPECULAROVERALPHA = false;
  21298. this.CLIPPLANE = false;
  21299. this.ALPHATEST = false;
  21300. this.ALPHAFROMDIFFUSE = false;
  21301. this.POINTSIZE = false;
  21302. this.FOG = false;
  21303. this.LIGHT0 = false;
  21304. this.LIGHT1 = false;
  21305. this.LIGHT2 = false;
  21306. this.LIGHT3 = false;
  21307. this.SPOTLIGHT0 = false;
  21308. this.SPOTLIGHT1 = false;
  21309. this.SPOTLIGHT2 = false;
  21310. this.SPOTLIGHT3 = false;
  21311. this.HEMILIGHT0 = false;
  21312. this.HEMILIGHT1 = false;
  21313. this.HEMILIGHT2 = false;
  21314. this.HEMILIGHT3 = false;
  21315. this.POINTLIGHT0 = false;
  21316. this.POINTLIGHT1 = false;
  21317. this.POINTLIGHT2 = false;
  21318. this.POINTLIGHT3 = false;
  21319. this.DIRLIGHT0 = false;
  21320. this.DIRLIGHT1 = false;
  21321. this.DIRLIGHT2 = false;
  21322. this.DIRLIGHT3 = false;
  21323. this.SPECULARTERM = false;
  21324. this.SHADOW0 = false;
  21325. this.SHADOW1 = false;
  21326. this.SHADOW2 = false;
  21327. this.SHADOW3 = false;
  21328. this.SHADOWS = false;
  21329. this.SHADOWVSM0 = false;
  21330. this.SHADOWVSM1 = false;
  21331. this.SHADOWVSM2 = false;
  21332. this.SHADOWVSM3 = false;
  21333. this.SHADOWPCF0 = false;
  21334. this.SHADOWPCF1 = false;
  21335. this.SHADOWPCF2 = false;
  21336. this.SHADOWPCF3 = false;
  21337. this.DIFFUSEFRESNEL = false;
  21338. this.OPACITYFRESNEL = false;
  21339. this.REFLECTIONFRESNEL = false;
  21340. this.REFRACTIONFRESNEL = false;
  21341. this.EMISSIVEFRESNEL = false;
  21342. this.FRESNEL = false;
  21343. this.NORMAL = false;
  21344. this.UV1 = false;
  21345. this.UV2 = false;
  21346. this.VERTEXCOLOR = false;
  21347. this.VERTEXALPHA = false;
  21348. this.NUM_BONE_INFLUENCERS = 0;
  21349. this.BonesPerMesh = 0;
  21350. this.INSTANCES = false;
  21351. this.GLOSSINESS = false;
  21352. this.ROUGHNESS = false;
  21353. this.EMISSIVEASILLUMINATION = false;
  21354. this.LINKEMISSIVEWITHDIFFUSE = false;
  21355. this.REFLECTIONFRESNELFROMSPECULAR = false;
  21356. this.LIGHTMAP = false;
  21357. this.USELIGHTMAPASSHADOWMAP = false;
  21358. this.REFLECTIONMAP_3D = false;
  21359. this.REFLECTIONMAP_SPHERICAL = false;
  21360. this.REFLECTIONMAP_PLANAR = false;
  21361. this.REFLECTIONMAP_CUBIC = false;
  21362. this.REFLECTIONMAP_PROJECTION = false;
  21363. this.REFLECTIONMAP_SKYBOX = false;
  21364. this.REFLECTIONMAP_EXPLICIT = false;
  21365. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  21366. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  21367. this.INVERTCUBICMAP = false;
  21368. this.LOGARITHMICDEPTH = false;
  21369. this.REFRACTION = false;
  21370. this.REFRACTIONMAP_3D = false;
  21371. this.REFLECTIONOVERALPHA = false;
  21372. this._keys = Object.keys(this);
  21373. }
  21374. return StandardMaterialDefines;
  21375. })(BABYLON.MaterialDefines);
  21376. var StandardMaterial = (function (_super) {
  21377. __extends(StandardMaterial, _super);
  21378. function StandardMaterial(name, scene) {
  21379. var _this = this;
  21380. _super.call(this, name, scene);
  21381. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21382. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  21383. this.specularColor = new BABYLON.Color3(1, 1, 1);
  21384. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  21385. this.specularPower = 64;
  21386. this.useAlphaFromDiffuseTexture = false;
  21387. this.useEmissiveAsIllumination = false;
  21388. this.linkEmissiveWithDiffuse = false;
  21389. this.useReflectionFresnelFromSpecular = false;
  21390. this.useSpecularOverAlpha = false;
  21391. this.useReflectionOverAlpha = false;
  21392. this.disableLighting = false;
  21393. this.useParallax = false;
  21394. this.useParallaxOcclusion = false;
  21395. this.parallaxScaleBias = 0.05;
  21396. this.roughness = 0;
  21397. this.indexOfRefraction = 0.98;
  21398. this.invertRefractionY = true;
  21399. this.useLightmapAsShadowmap = false;
  21400. this.useGlossinessFromSpecularMapAlpha = false;
  21401. this._renderTargets = new BABYLON.SmartArray(16);
  21402. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  21403. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  21404. this._defines = new StandardMaterialDefines();
  21405. this._cachedDefines = new StandardMaterialDefines();
  21406. this._cachedDefines.BonesPerMesh = -1;
  21407. this.getRenderTargetTextures = function () {
  21408. _this._renderTargets.reset();
  21409. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  21410. _this._renderTargets.push(_this.reflectionTexture);
  21411. }
  21412. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  21413. _this._renderTargets.push(_this.refractionTexture);
  21414. }
  21415. return _this._renderTargets;
  21416. };
  21417. }
  21418. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  21419. get: function () {
  21420. return this._useLogarithmicDepth;
  21421. },
  21422. set: function (value) {
  21423. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  21424. },
  21425. enumerable: true,
  21426. configurable: true
  21427. });
  21428. StandardMaterial.prototype.needAlphaBlending = function () {
  21429. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  21430. };
  21431. StandardMaterial.prototype.needAlphaTesting = function () {
  21432. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  21433. };
  21434. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  21435. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  21436. };
  21437. StandardMaterial.prototype.getAlphaTestTexture = function () {
  21438. return this.diffuseTexture;
  21439. };
  21440. // Methods
  21441. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  21442. if (!mesh) {
  21443. return true;
  21444. }
  21445. if (this._defines.INSTANCES !== useInstances) {
  21446. return false;
  21447. }
  21448. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  21449. return true;
  21450. }
  21451. return false;
  21452. };
  21453. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  21454. if (this.isFrozen) {
  21455. if (this._wasPreviouslyReady) {
  21456. return true;
  21457. }
  21458. }
  21459. var scene = this.getScene();
  21460. if (!this.checkReadyOnEveryCall) {
  21461. if (this._renderId === scene.getRenderId()) {
  21462. if (this._checkCache(scene, mesh, useInstances)) {
  21463. return true;
  21464. }
  21465. }
  21466. }
  21467. var engine = scene.getEngine();
  21468. var needNormals = false;
  21469. var needUVs = false;
  21470. this._defines.reset();
  21471. // Textures
  21472. if (scene.texturesEnabled) {
  21473. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  21474. if (!this.diffuseTexture.isReady()) {
  21475. return false;
  21476. }
  21477. else {
  21478. needUVs = true;
  21479. this._defines.DIFFUSE = true;
  21480. }
  21481. }
  21482. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  21483. if (!this.ambientTexture.isReady()) {
  21484. return false;
  21485. }
  21486. else {
  21487. needUVs = true;
  21488. this._defines.AMBIENT = true;
  21489. }
  21490. }
  21491. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  21492. if (!this.opacityTexture.isReady()) {
  21493. return false;
  21494. }
  21495. else {
  21496. needUVs = true;
  21497. this._defines.OPACITY = true;
  21498. if (this.opacityTexture.getAlphaFromRGB) {
  21499. this._defines.OPACITYRGB = true;
  21500. }
  21501. }
  21502. }
  21503. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  21504. if (!this.reflectionTexture.isReady()) {
  21505. return false;
  21506. }
  21507. else {
  21508. needNormals = true;
  21509. this._defines.REFLECTION = true;
  21510. if (this.roughness > 0) {
  21511. this._defines.ROUGHNESS = true;
  21512. }
  21513. if (this.useReflectionOverAlpha) {
  21514. this._defines.REFLECTIONOVERALPHA = true;
  21515. }
  21516. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  21517. this._defines.INVERTCUBICMAP = true;
  21518. }
  21519. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  21520. switch (this.reflectionTexture.coordinatesMode) {
  21521. case BABYLON.Texture.CUBIC_MODE:
  21522. case BABYLON.Texture.INVCUBIC_MODE:
  21523. this._defines.REFLECTIONMAP_CUBIC = true;
  21524. break;
  21525. case BABYLON.Texture.EXPLICIT_MODE:
  21526. this._defines.REFLECTIONMAP_EXPLICIT = true;
  21527. break;
  21528. case BABYLON.Texture.PLANAR_MODE:
  21529. this._defines.REFLECTIONMAP_PLANAR = true;
  21530. break;
  21531. case BABYLON.Texture.PROJECTION_MODE:
  21532. this._defines.REFLECTIONMAP_PROJECTION = true;
  21533. break;
  21534. case BABYLON.Texture.SKYBOX_MODE:
  21535. this._defines.REFLECTIONMAP_SKYBOX = true;
  21536. break;
  21537. case BABYLON.Texture.SPHERICAL_MODE:
  21538. this._defines.REFLECTIONMAP_SPHERICAL = true;
  21539. break;
  21540. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  21541. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  21542. break;
  21543. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  21544. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  21545. break;
  21546. }
  21547. }
  21548. }
  21549. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  21550. if (!this.emissiveTexture.isReady()) {
  21551. return false;
  21552. }
  21553. else {
  21554. needUVs = true;
  21555. this._defines.EMISSIVE = true;
  21556. }
  21557. }
  21558. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  21559. if (!this.lightmapTexture.isReady()) {
  21560. return false;
  21561. }
  21562. else {
  21563. needUVs = true;
  21564. this._defines.LIGHTMAP = true;
  21565. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  21566. }
  21567. }
  21568. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  21569. if (!this.specularTexture.isReady()) {
  21570. return false;
  21571. }
  21572. else {
  21573. needUVs = true;
  21574. this._defines.SPECULAR = true;
  21575. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  21576. }
  21577. }
  21578. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  21579. if (!this.bumpTexture.isReady()) {
  21580. return false;
  21581. }
  21582. else {
  21583. needUVs = true;
  21584. this._defines.BUMP = true;
  21585. if (this.useParallax) {
  21586. this._defines.PARALLAX = true;
  21587. if (this.useParallaxOcclusion) {
  21588. this._defines.PARALLAXOCCLUSION = true;
  21589. }
  21590. }
  21591. }
  21592. }
  21593. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  21594. if (!this.refractionTexture.isReady()) {
  21595. return false;
  21596. }
  21597. else {
  21598. needUVs = true;
  21599. this._defines.REFRACTION = true;
  21600. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  21601. }
  21602. }
  21603. }
  21604. // Effect
  21605. if (scene.clipPlane) {
  21606. this._defines.CLIPPLANE = true;
  21607. }
  21608. if (engine.getAlphaTesting()) {
  21609. this._defines.ALPHATEST = true;
  21610. }
  21611. if (this._shouldUseAlphaFromDiffuseTexture()) {
  21612. this._defines.ALPHAFROMDIFFUSE = true;
  21613. }
  21614. if (this.useEmissiveAsIllumination) {
  21615. this._defines.EMISSIVEASILLUMINATION = true;
  21616. }
  21617. if (this.linkEmissiveWithDiffuse) {
  21618. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  21619. }
  21620. if (this.useLogarithmicDepth) {
  21621. this._defines.LOGARITHMICDEPTH = true;
  21622. }
  21623. // Point size
  21624. if (this.pointsCloud || scene.forcePointsCloud) {
  21625. this._defines.POINTSIZE = true;
  21626. }
  21627. // Fog
  21628. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21629. this._defines.FOG = true;
  21630. }
  21631. if (scene.lightsEnabled && !this.disableLighting) {
  21632. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  21633. }
  21634. if (StandardMaterial.FresnelEnabled) {
  21635. // Fresnel
  21636. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  21637. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  21638. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  21639. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  21640. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21641. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  21642. this._defines.DIFFUSEFRESNEL = true;
  21643. }
  21644. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  21645. this._defines.OPACITYFRESNEL = true;
  21646. }
  21647. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21648. this._defines.REFLECTIONFRESNEL = true;
  21649. if (this.useReflectionFresnelFromSpecular) {
  21650. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  21651. }
  21652. }
  21653. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  21654. this._defines.REFRACTIONFRESNEL = true;
  21655. }
  21656. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  21657. this._defines.EMISSIVEFRESNEL = true;
  21658. }
  21659. needNormals = true;
  21660. this._defines.FRESNEL = true;
  21661. }
  21662. }
  21663. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  21664. this._defines.SPECULAROVERALPHA = true;
  21665. }
  21666. // Attribs
  21667. if (mesh) {
  21668. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21669. this._defines.NORMAL = true;
  21670. }
  21671. if (needUVs) {
  21672. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21673. this._defines.UV1 = true;
  21674. }
  21675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21676. this._defines.UV2 = true;
  21677. }
  21678. }
  21679. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21680. this._defines.VERTEXCOLOR = true;
  21681. if (mesh.hasVertexAlpha) {
  21682. this._defines.VERTEXALPHA = true;
  21683. }
  21684. }
  21685. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  21686. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  21687. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  21688. }
  21689. // Instances
  21690. if (useInstances) {
  21691. this._defines.INSTANCES = true;
  21692. }
  21693. }
  21694. // Get correct effect
  21695. if (!this._defines.isEqual(this._cachedDefines)) {
  21696. this._defines.cloneTo(this._cachedDefines);
  21697. scene.resetCachedMaterial();
  21698. // Fallbacks
  21699. var fallbacks = new BABYLON.EffectFallbacks();
  21700. if (this._defines.REFLECTION) {
  21701. fallbacks.addFallback(0, "REFLECTION");
  21702. }
  21703. if (this._defines.SPECULAR) {
  21704. fallbacks.addFallback(0, "SPECULAR");
  21705. }
  21706. if (this._defines.BUMP) {
  21707. fallbacks.addFallback(0, "BUMP");
  21708. }
  21709. if (this._defines.PARALLAX) {
  21710. fallbacks.addFallback(1, "PARALLAX");
  21711. }
  21712. if (this._defines.PARALLAXOCCLUSION) {
  21713. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  21714. }
  21715. if (this._defines.SPECULAROVERALPHA) {
  21716. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  21717. }
  21718. if (this._defines.FOG) {
  21719. fallbacks.addFallback(1, "FOG");
  21720. }
  21721. if (this._defines.POINTSIZE) {
  21722. fallbacks.addFallback(0, "POINTSIZE");
  21723. }
  21724. if (this._defines.LOGARITHMICDEPTH) {
  21725. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  21726. }
  21727. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  21728. if (this._defines.SPECULARTERM) {
  21729. fallbacks.addFallback(0, "SPECULARTERM");
  21730. }
  21731. if (this._defines.DIFFUSEFRESNEL) {
  21732. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  21733. }
  21734. if (this._defines.OPACITYFRESNEL) {
  21735. fallbacks.addFallback(2, "OPACITYFRESNEL");
  21736. }
  21737. if (this._defines.REFLECTIONFRESNEL) {
  21738. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  21739. }
  21740. if (this._defines.EMISSIVEFRESNEL) {
  21741. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  21742. }
  21743. if (this._defines.FRESNEL) {
  21744. fallbacks.addFallback(4, "FRESNEL");
  21745. }
  21746. //Attributes
  21747. var attribs = [BABYLON.VertexBuffer.PositionKind];
  21748. if (this._defines.NORMAL) {
  21749. attribs.push(BABYLON.VertexBuffer.NormalKind);
  21750. }
  21751. if (this._defines.UV1) {
  21752. attribs.push(BABYLON.VertexBuffer.UVKind);
  21753. }
  21754. if (this._defines.UV2) {
  21755. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  21756. }
  21757. if (this._defines.VERTEXCOLOR) {
  21758. attribs.push(BABYLON.VertexBuffer.ColorKind);
  21759. }
  21760. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  21761. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  21762. // Legacy browser patch
  21763. var shaderName = "default";
  21764. if (!scene.getEngine().getCaps().standardDerivatives) {
  21765. shaderName = "legacydefault";
  21766. }
  21767. var join = this._defines.toString();
  21768. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  21769. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  21770. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  21771. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  21772. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  21773. "vFogInfos", "vFogColor", "pointSize",
  21774. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  21775. "mBones",
  21776. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  21777. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  21778. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  21779. "logarithmicDepthConstant"
  21780. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  21781. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  21782. ], join, fallbacks, this.onCompiled, this.onError);
  21783. }
  21784. if (!this._effect.isReady()) {
  21785. return false;
  21786. }
  21787. this._renderId = scene.getRenderId();
  21788. this._wasPreviouslyReady = true;
  21789. if (mesh) {
  21790. if (!mesh._materialDefines) {
  21791. mesh._materialDefines = new StandardMaterialDefines();
  21792. }
  21793. this._defines.cloneTo(mesh._materialDefines);
  21794. }
  21795. return true;
  21796. };
  21797. StandardMaterial.prototype.unbind = function () {
  21798. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  21799. this._effect.setTexture("reflection2DSampler", null);
  21800. }
  21801. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  21802. this._effect.setTexture("refraction2DSampler", null);
  21803. }
  21804. _super.prototype.unbind.call(this);
  21805. };
  21806. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21807. this._effect.setMatrix("world", world);
  21808. };
  21809. StandardMaterial.prototype.bind = function (world, mesh) {
  21810. var scene = this.getScene();
  21811. // Matrices
  21812. this.bindOnlyWorldMatrix(world);
  21813. // Bones
  21814. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  21815. if (scene.getCachedMaterial() !== this) {
  21816. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  21817. if (StandardMaterial.FresnelEnabled) {
  21818. // Fresnel
  21819. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  21820. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  21821. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  21822. }
  21823. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  21824. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  21825. }
  21826. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21827. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  21828. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  21829. }
  21830. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  21831. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  21832. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  21833. }
  21834. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  21835. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  21836. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  21837. }
  21838. }
  21839. // Textures
  21840. if (scene.texturesEnabled) {
  21841. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  21842. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  21843. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  21844. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  21845. }
  21846. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  21847. this._effect.setTexture("ambientSampler", this.ambientTexture);
  21848. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  21849. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  21850. }
  21851. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  21852. this._effect.setTexture("opacitySampler", this.opacityTexture);
  21853. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  21854. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  21855. }
  21856. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  21857. if (this.reflectionTexture.isCube) {
  21858. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  21859. }
  21860. else {
  21861. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  21862. }
  21863. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  21864. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  21865. }
  21866. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  21867. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  21868. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  21869. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  21870. }
  21871. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  21872. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  21873. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  21874. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  21875. }
  21876. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  21877. this._effect.setTexture("specularSampler", this.specularTexture);
  21878. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  21879. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  21880. }
  21881. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  21882. this._effect.setTexture("bumpSampler", this.bumpTexture);
  21883. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  21884. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  21885. }
  21886. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  21887. var depth = 1.0;
  21888. if (this.refractionTexture.isCube) {
  21889. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  21890. }
  21891. else {
  21892. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  21893. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  21894. if (this.refractionTexture.depth) {
  21895. depth = this.refractionTexture.depth;
  21896. }
  21897. }
  21898. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  21899. }
  21900. }
  21901. // Clip plane
  21902. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  21903. // Point size
  21904. if (this.pointsCloud) {
  21905. this._effect.setFloat("pointSize", this.pointSize);
  21906. }
  21907. // Colors
  21908. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  21909. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  21910. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  21911. if (this._defines.SPECULARTERM) {
  21912. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  21913. }
  21914. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  21915. }
  21916. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  21917. // Diffuse
  21918. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  21919. // Lights
  21920. if (scene.lightsEnabled && !this.disableLighting) {
  21921. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  21922. }
  21923. // View
  21924. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  21925. this._effect.setMatrix("view", scene.getViewMatrix());
  21926. }
  21927. // Fog
  21928. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  21929. // Log. depth
  21930. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  21931. }
  21932. _super.prototype.bind.call(this, world, mesh);
  21933. };
  21934. StandardMaterial.prototype.getAnimatables = function () {
  21935. var results = [];
  21936. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  21937. results.push(this.diffuseTexture);
  21938. }
  21939. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  21940. results.push(this.ambientTexture);
  21941. }
  21942. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  21943. results.push(this.opacityTexture);
  21944. }
  21945. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  21946. results.push(this.reflectionTexture);
  21947. }
  21948. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  21949. results.push(this.emissiveTexture);
  21950. }
  21951. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  21952. results.push(this.specularTexture);
  21953. }
  21954. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  21955. results.push(this.bumpTexture);
  21956. }
  21957. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  21958. results.push(this.lightmapTexture);
  21959. }
  21960. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  21961. results.push(this.refractionTexture);
  21962. }
  21963. return results;
  21964. };
  21965. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  21966. if (this.diffuseTexture) {
  21967. this.diffuseTexture.dispose();
  21968. }
  21969. if (this.ambientTexture) {
  21970. this.ambientTexture.dispose();
  21971. }
  21972. if (this.opacityTexture) {
  21973. this.opacityTexture.dispose();
  21974. }
  21975. if (this.reflectionTexture) {
  21976. this.reflectionTexture.dispose();
  21977. }
  21978. if (this.emissiveTexture) {
  21979. this.emissiveTexture.dispose();
  21980. }
  21981. if (this.specularTexture) {
  21982. this.specularTexture.dispose();
  21983. }
  21984. if (this.bumpTexture) {
  21985. this.bumpTexture.dispose();
  21986. }
  21987. if (this.lightmapTexture) {
  21988. this.lightmapTexture.dispose();
  21989. }
  21990. if (this.refractionTexture) {
  21991. this.refractionTexture.dispose();
  21992. }
  21993. _super.prototype.dispose.call(this, forceDisposeEffect);
  21994. };
  21995. StandardMaterial.prototype.clone = function (name) {
  21996. var _this = this;
  21997. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  21998. };
  21999. StandardMaterial.prototype.serialize = function () {
  22000. return BABYLON.SerializationHelper.Serialize(this);
  22001. };
  22002. // Statics
  22003. StandardMaterial.Parse = function (source, scene, rootUrl) {
  22004. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  22005. };
  22006. // Flags used to enable or disable a type of texture for all Standard Materials
  22007. StandardMaterial.DiffuseTextureEnabled = true;
  22008. StandardMaterial.AmbientTextureEnabled = true;
  22009. StandardMaterial.OpacityTextureEnabled = true;
  22010. StandardMaterial.ReflectionTextureEnabled = true;
  22011. StandardMaterial.EmissiveTextureEnabled = true;
  22012. StandardMaterial.SpecularTextureEnabled = true;
  22013. StandardMaterial.BumpTextureEnabled = true;
  22014. StandardMaterial.FresnelEnabled = true;
  22015. StandardMaterial.LightmapTextureEnabled = true;
  22016. StandardMaterial.RefractionTextureEnabled = true;
  22017. __decorate([
  22018. BABYLON.serializeAsTexture()
  22019. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  22020. __decorate([
  22021. BABYLON.serializeAsTexture()
  22022. ], StandardMaterial.prototype, "ambientTexture", void 0);
  22023. __decorate([
  22024. BABYLON.serializeAsTexture()
  22025. ], StandardMaterial.prototype, "opacityTexture", void 0);
  22026. __decorate([
  22027. BABYLON.serializeAsTexture()
  22028. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  22029. __decorate([
  22030. BABYLON.serializeAsTexture()
  22031. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  22032. __decorate([
  22033. BABYLON.serializeAsTexture()
  22034. ], StandardMaterial.prototype, "specularTexture", void 0);
  22035. __decorate([
  22036. BABYLON.serializeAsTexture()
  22037. ], StandardMaterial.prototype, "bumpTexture", void 0);
  22038. __decorate([
  22039. BABYLON.serializeAsTexture()
  22040. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  22041. __decorate([
  22042. BABYLON.serializeAsTexture()
  22043. ], StandardMaterial.prototype, "refractionTexture", void 0);
  22044. __decorate([
  22045. BABYLON.serializeAsColor3("ambient")
  22046. ], StandardMaterial.prototype, "ambientColor", void 0);
  22047. __decorate([
  22048. BABYLON.serializeAsColor3("diffuse")
  22049. ], StandardMaterial.prototype, "diffuseColor", void 0);
  22050. __decorate([
  22051. BABYLON.serializeAsColor3("specular")
  22052. ], StandardMaterial.prototype, "specularColor", void 0);
  22053. __decorate([
  22054. BABYLON.serializeAsColor3("emissive")
  22055. ], StandardMaterial.prototype, "emissiveColor", void 0);
  22056. __decorate([
  22057. BABYLON.serialize()
  22058. ], StandardMaterial.prototype, "specularPower", void 0);
  22059. __decorate([
  22060. BABYLON.serialize()
  22061. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  22062. __decorate([
  22063. BABYLON.serialize()
  22064. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  22065. __decorate([
  22066. BABYLON.serialize()
  22067. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  22068. __decorate([
  22069. BABYLON.serialize()
  22070. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  22071. __decorate([
  22072. BABYLON.serialize()
  22073. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  22074. __decorate([
  22075. BABYLON.serialize()
  22076. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  22077. __decorate([
  22078. BABYLON.serialize()
  22079. ], StandardMaterial.prototype, "disableLighting", void 0);
  22080. __decorate([
  22081. BABYLON.serialize()
  22082. ], StandardMaterial.prototype, "useParallax", void 0);
  22083. __decorate([
  22084. BABYLON.serialize()
  22085. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  22086. __decorate([
  22087. BABYLON.serialize()
  22088. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  22089. __decorate([
  22090. BABYLON.serialize()
  22091. ], StandardMaterial.prototype, "roughness", void 0);
  22092. __decorate([
  22093. BABYLON.serialize()
  22094. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  22095. __decorate([
  22096. BABYLON.serialize()
  22097. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  22098. __decorate([
  22099. BABYLON.serialize()
  22100. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  22101. __decorate([
  22102. BABYLON.serializeAsFresnelParameters()
  22103. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  22104. __decorate([
  22105. BABYLON.serializeAsFresnelParameters()
  22106. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  22107. __decorate([
  22108. BABYLON.serializeAsFresnelParameters()
  22109. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  22110. __decorate([
  22111. BABYLON.serializeAsFresnelParameters()
  22112. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  22113. __decorate([
  22114. BABYLON.serializeAsFresnelParameters()
  22115. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  22116. __decorate([
  22117. BABYLON.serialize()
  22118. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  22119. __decorate([
  22120. BABYLON.serialize()
  22121. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  22122. return StandardMaterial;
  22123. })(BABYLON.Material);
  22124. BABYLON.StandardMaterial = StandardMaterial;
  22125. })(BABYLON || (BABYLON = {}));
  22126. var BABYLON;
  22127. (function (BABYLON) {
  22128. var MultiMaterial = (function (_super) {
  22129. __extends(MultiMaterial, _super);
  22130. function MultiMaterial(name, scene) {
  22131. _super.call(this, name, scene, true);
  22132. this.subMaterials = new Array();
  22133. scene.multiMaterials.push(this);
  22134. }
  22135. // Properties
  22136. MultiMaterial.prototype.getSubMaterial = function (index) {
  22137. if (index < 0 || index >= this.subMaterials.length) {
  22138. return this.getScene().defaultMaterial;
  22139. }
  22140. return this.subMaterials[index];
  22141. };
  22142. // Methods
  22143. MultiMaterial.prototype.isReady = function (mesh) {
  22144. for (var index = 0; index < this.subMaterials.length; index++) {
  22145. var subMaterial = this.subMaterials[index];
  22146. if (subMaterial) {
  22147. if (!this.subMaterials[index].isReady(mesh)) {
  22148. return false;
  22149. }
  22150. }
  22151. }
  22152. return true;
  22153. };
  22154. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  22155. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  22156. for (var index = 0; index < this.subMaterials.length; index++) {
  22157. var subMaterial = null;
  22158. if (cloneChildren) {
  22159. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  22160. }
  22161. else {
  22162. subMaterial = this.subMaterials[index];
  22163. }
  22164. newMultiMaterial.subMaterials.push(subMaterial);
  22165. }
  22166. return newMultiMaterial;
  22167. };
  22168. MultiMaterial.prototype.serialize = function () {
  22169. var serializationObject = {};
  22170. serializationObject.name = this.name;
  22171. serializationObject.id = this.id;
  22172. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22173. serializationObject.materials = [];
  22174. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  22175. var subMat = this.subMaterials[matIndex];
  22176. if (subMat) {
  22177. serializationObject.materials.push(subMat.id);
  22178. }
  22179. else {
  22180. serializationObject.materials.push(null);
  22181. }
  22182. }
  22183. return serializationObject;
  22184. };
  22185. return MultiMaterial;
  22186. })(BABYLON.Material);
  22187. BABYLON.MultiMaterial = MultiMaterial;
  22188. })(BABYLON || (BABYLON = {}));
  22189. var BABYLON;
  22190. (function (BABYLON) {
  22191. var SceneLoader = (function () {
  22192. function SceneLoader() {
  22193. }
  22194. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  22195. get: function () {
  22196. return 0;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  22202. get: function () {
  22203. return 1;
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  22209. get: function () {
  22210. return 2;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  22216. get: function () {
  22217. return 3;
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  22223. get: function () {
  22224. return SceneLoader._ForceFullSceneLoadingForIncremental;
  22225. },
  22226. set: function (value) {
  22227. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  22228. },
  22229. enumerable: true,
  22230. configurable: true
  22231. });
  22232. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  22233. get: function () {
  22234. return SceneLoader._ShowLoadingScreen;
  22235. },
  22236. set: function (value) {
  22237. SceneLoader._ShowLoadingScreen = value;
  22238. },
  22239. enumerable: true,
  22240. configurable: true
  22241. });
  22242. Object.defineProperty(SceneLoader, "loggingLevel", {
  22243. get: function () {
  22244. return SceneLoader._loggingLevel;
  22245. },
  22246. set: function (value) {
  22247. SceneLoader._loggingLevel = value;
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. SceneLoader._getPluginForFilename = function (sceneFilename) {
  22253. var dotPosition = sceneFilename.lastIndexOf(".");
  22254. var queryStringPosition = sceneFilename.indexOf("?");
  22255. if (queryStringPosition === -1) {
  22256. queryStringPosition = sceneFilename.length;
  22257. }
  22258. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  22259. for (var index = 0; index < this._registeredPlugins.length; index++) {
  22260. var plugin = this._registeredPlugins[index];
  22261. if (plugin.extensions.indexOf(extension) !== -1) {
  22262. return plugin;
  22263. }
  22264. }
  22265. return this._registeredPlugins[this._registeredPlugins.length - 1];
  22266. };
  22267. // Public functions
  22268. SceneLoader.GetPluginForExtension = function (extension) {
  22269. for (var index = 0; index < this._registeredPlugins.length; index++) {
  22270. var plugin = this._registeredPlugins[index];
  22271. if (plugin.extensions.indexOf(extension) !== -1) {
  22272. return plugin;
  22273. }
  22274. }
  22275. return null;
  22276. };
  22277. SceneLoader.RegisterPlugin = function (plugin) {
  22278. plugin.extensions = plugin.extensions.toLowerCase();
  22279. SceneLoader._registeredPlugins.push(plugin);
  22280. };
  22281. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  22282. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  22283. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  22284. return;
  22285. }
  22286. var loadingToken = {};
  22287. scene._addPendingData(loadingToken);
  22288. var manifestChecked = function (success) {
  22289. scene.database = database;
  22290. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  22291. var importMeshFromData = function (data) {
  22292. var meshes = [];
  22293. var particleSystems = [];
  22294. var skeletons = [];
  22295. try {
  22296. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  22297. if (onerror) {
  22298. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  22299. }
  22300. scene._removePendingData(loadingToken);
  22301. return;
  22302. }
  22303. }
  22304. catch (e) {
  22305. if (onerror) {
  22306. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  22307. }
  22308. scene._removePendingData(loadingToken);
  22309. return;
  22310. }
  22311. if (onsuccess) {
  22312. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  22313. onsuccess(meshes, particleSystems, skeletons);
  22314. scene._removePendingData(loadingToken);
  22315. }
  22316. };
  22317. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  22318. // Direct load
  22319. importMeshFromData(sceneFilename.substr(5));
  22320. return;
  22321. }
  22322. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  22323. importMeshFromData(data);
  22324. }, progressCallBack, database);
  22325. };
  22326. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  22327. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  22328. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  22329. }
  22330. else {
  22331. // If the scene is a data stream or offline support is not enabled, it's a direct load
  22332. manifestChecked(true);
  22333. }
  22334. };
  22335. /**
  22336. * Load a scene
  22337. * @param rootUrl a string that defines the root url for scene and resources
  22338. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  22339. * @param engine is the instance of BABYLON.Engine to use to create the scene
  22340. */
  22341. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  22342. if (!SceneLoader._warned) {
  22343. BABYLON.Tools.Warn("SceneLoader.Load deprecated since 2.4. Use SceneLoader.Append.");
  22344. SceneLoader._warned = true;
  22345. }
  22346. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  22347. };
  22348. /**
  22349. * Append a scene
  22350. * @param rootUrl a string that defines the root url for scene and resources
  22351. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  22352. * @param scene is the instance of BABYLON.Scene to append to
  22353. */
  22354. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  22355. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  22356. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  22357. return;
  22358. }
  22359. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  22360. var database;
  22361. var loadingToken = {};
  22362. scene._addPendingData(loadingToken);
  22363. if (SceneLoader.ShowLoadingScreen) {
  22364. scene.getEngine().displayLoadingUI();
  22365. }
  22366. var loadSceneFromData = function (data) {
  22367. scene.database = database;
  22368. if (!plugin.load(scene, data, rootUrl)) {
  22369. if (onerror) {
  22370. onerror(scene);
  22371. }
  22372. scene._removePendingData(loadingToken);
  22373. scene.getEngine().hideLoadingUI();
  22374. return;
  22375. }
  22376. if (onsuccess) {
  22377. onsuccess(scene);
  22378. }
  22379. scene._removePendingData(loadingToken);
  22380. if (SceneLoader.ShowLoadingScreen) {
  22381. scene.executeWhenReady(function () {
  22382. scene.getEngine().hideLoadingUI();
  22383. });
  22384. }
  22385. };
  22386. var manifestChecked = function (success) {
  22387. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  22388. };
  22389. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  22390. // Direct load
  22391. loadSceneFromData(sceneFilename.substr(5));
  22392. return;
  22393. }
  22394. if (rootUrl.indexOf("file:") === -1) {
  22395. if (scene.getEngine().enableOfflineSupport) {
  22396. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  22397. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  22398. }
  22399. else {
  22400. manifestChecked(true);
  22401. }
  22402. }
  22403. else {
  22404. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  22405. }
  22406. };
  22407. // Flags
  22408. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  22409. SceneLoader._ShowLoadingScreen = true;
  22410. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  22411. // Members
  22412. SceneLoader._registeredPlugins = new Array();
  22413. return SceneLoader;
  22414. })();
  22415. BABYLON.SceneLoader = SceneLoader;
  22416. ;
  22417. })(BABYLON || (BABYLON = {}));
  22418. var BABYLON;
  22419. (function (BABYLON) {
  22420. var Internals;
  22421. (function (Internals) {
  22422. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  22423. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  22424. var parsedMaterial = parsedData.materials[index];
  22425. if (parsedMaterial.id === id) {
  22426. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  22427. }
  22428. }
  22429. return null;
  22430. };
  22431. var isDescendantOf = function (mesh, names, hierarchyIds) {
  22432. names = (names instanceof Array) ? names : [names];
  22433. for (var i in names) {
  22434. if (mesh.name === names[i]) {
  22435. hierarchyIds.push(mesh.id);
  22436. return true;
  22437. }
  22438. }
  22439. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  22440. hierarchyIds.push(mesh.id);
  22441. return true;
  22442. }
  22443. return false;
  22444. };
  22445. var logOperation = function (operation, producer) {
  22446. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  22447. };
  22448. BABYLON.SceneLoader.RegisterPlugin({
  22449. extensions: ".babylon",
  22450. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  22451. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  22452. // when SceneLoader.debugLogging = true (default), or exception encountered.
  22453. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  22454. // and avoid problems with multiple concurrent .babylon loads.
  22455. var log = "importMesh has failed JSON parse";
  22456. try {
  22457. var parsedData = JSON.parse(data);
  22458. log = "";
  22459. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  22460. var loadedSkeletonsIds = [];
  22461. var loadedMaterialsIds = [];
  22462. var hierarchyIds = [];
  22463. var index;
  22464. var cache;
  22465. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  22466. var parsedMesh = parsedData.meshes[index];
  22467. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  22468. if (meshesNames instanceof Array) {
  22469. // Remove found mesh name from list.
  22470. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  22471. }
  22472. //Geometry?
  22473. if (parsedMesh.geometryId) {
  22474. //does the file contain geometries?
  22475. if (parsedData.geometries) {
  22476. //find the correct geometry and add it to the scene
  22477. var found = false;
  22478. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  22479. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  22480. return;
  22481. }
  22482. else {
  22483. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  22484. if (parsedGeometryData.id === parsedMesh.geometryId) {
  22485. switch (geometryType) {
  22486. case "boxes":
  22487. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  22488. break;
  22489. case "spheres":
  22490. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  22491. break;
  22492. case "cylinders":
  22493. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  22494. break;
  22495. case "toruses":
  22496. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  22497. break;
  22498. case "grounds":
  22499. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  22500. break;
  22501. case "planes":
  22502. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  22503. break;
  22504. case "torusKnots":
  22505. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  22506. break;
  22507. case "vertexData":
  22508. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  22509. break;
  22510. }
  22511. found = true;
  22512. }
  22513. });
  22514. }
  22515. });
  22516. if (!found) {
  22517. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  22518. }
  22519. }
  22520. }
  22521. // Material ?
  22522. if (parsedMesh.materialId) {
  22523. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  22524. if (!materialFound && parsedData.multiMaterials) {
  22525. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  22526. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  22527. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  22528. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  22529. var subMatId = parsedMultiMaterial.materials[matIndex];
  22530. loadedMaterialsIds.push(subMatId);
  22531. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  22532. log += "\n\tMaterial " + mat.toString(fullDetails);
  22533. }
  22534. loadedMaterialsIds.push(parsedMultiMaterial.id);
  22535. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  22536. materialFound = true;
  22537. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  22538. break;
  22539. }
  22540. }
  22541. }
  22542. if (!materialFound) {
  22543. loadedMaterialsIds.push(parsedMesh.materialId);
  22544. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  22545. if (!mat) {
  22546. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  22547. }
  22548. else {
  22549. log += "\n\tMaterial " + mat.toString(fullDetails);
  22550. }
  22551. }
  22552. }
  22553. // Skeleton ?
  22554. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  22555. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  22556. if (!skeletonAlreadyLoaded) {
  22557. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  22558. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  22559. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  22560. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  22561. skeletons.push(skeleton);
  22562. loadedSkeletonsIds.push(parsedSkeleton.id);
  22563. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  22564. }
  22565. }
  22566. }
  22567. }
  22568. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  22569. meshes.push(mesh);
  22570. log += "\n\tMesh " + mesh.toString(fullDetails);
  22571. }
  22572. }
  22573. // Connecting parents
  22574. var currentMesh;
  22575. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22576. currentMesh = scene.meshes[index];
  22577. if (currentMesh._waitingParentId) {
  22578. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  22579. currentMesh._waitingParentId = undefined;
  22580. }
  22581. }
  22582. // freeze and compute world matrix application
  22583. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22584. currentMesh = scene.meshes[index];
  22585. if (currentMesh._waitingFreezeWorldMatrix) {
  22586. currentMesh.freezeWorldMatrix();
  22587. currentMesh._waitingFreezeWorldMatrix = undefined;
  22588. }
  22589. else {
  22590. currentMesh.computeWorldMatrix(true);
  22591. }
  22592. }
  22593. // Particles
  22594. if (parsedData.particleSystems) {
  22595. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  22596. var parsedParticleSystem = parsedData.particleSystems[index];
  22597. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  22598. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  22599. }
  22600. }
  22601. }
  22602. return true;
  22603. }
  22604. catch (err) {
  22605. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  22606. log = null;
  22607. throw err;
  22608. }
  22609. finally {
  22610. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  22611. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  22612. }
  22613. }
  22614. },
  22615. load: function (scene, data, rootUrl) {
  22616. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  22617. // when SceneLoader.debugLogging = true (default), or exception encountered.
  22618. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  22619. // and avoid problems with multiple concurrent .babylon loads.
  22620. var log = "importScene has failed JSON parse";
  22621. try {
  22622. var parsedData = JSON.parse(data);
  22623. log = "";
  22624. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  22625. // Scene
  22626. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  22627. scene.autoClear = parsedData.autoClear;
  22628. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  22629. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  22630. if (parsedData.gravity) {
  22631. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  22632. }
  22633. // Fog
  22634. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  22635. scene.fogMode = parsedData.fogMode;
  22636. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  22637. scene.fogStart = parsedData.fogStart;
  22638. scene.fogEnd = parsedData.fogEnd;
  22639. scene.fogDensity = parsedData.fogDensity;
  22640. log += "\tFog mode for scene: ";
  22641. switch (scene.fogMode) {
  22642. // getters not compiling, so using hardcoded
  22643. case 1:
  22644. log += "exp\n";
  22645. break;
  22646. case 2:
  22647. log += "exp2\n";
  22648. break;
  22649. case 3:
  22650. log += "linear\n";
  22651. break;
  22652. }
  22653. }
  22654. //Physics
  22655. if (parsedData.physicsEnabled) {
  22656. var physicsPlugin;
  22657. if (parsedData.physicsEngine === "cannon") {
  22658. physicsPlugin = new BABYLON.CannonJSPlugin();
  22659. }
  22660. else if (parsedData.physicsEngine === "oimo") {
  22661. physicsPlugin = new BABYLON.OimoJSPlugin();
  22662. }
  22663. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  22664. //else - default engine, which is currently oimo
  22665. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  22666. scene.enablePhysics(physicsGravity, physicsPlugin);
  22667. }
  22668. //collisions, if defined. otherwise, default is true
  22669. if (parsedData.collisionsEnabled != undefined) {
  22670. scene.collisionsEnabled = parsedData.collisionsEnabled;
  22671. }
  22672. scene.workerCollisions = !!parsedData.workerCollisions;
  22673. var index;
  22674. var cache;
  22675. // Lights
  22676. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  22677. var parsedLight = parsedData.lights[index];
  22678. var light = BABYLON.Light.Parse(parsedLight, scene);
  22679. log += (index === 0 ? "\n\tLights:" : "");
  22680. log += "\n\t\t" + light.toString(fullDetails);
  22681. }
  22682. // Animations
  22683. if (parsedData.animations) {
  22684. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  22685. var parsedAnimation = parsedData.animations[index];
  22686. var animation = BABYLON.Animation.Parse(parsedAnimation);
  22687. scene.animations.push(animation);
  22688. log += (index === 0 ? "\n\tAnimations:" : "");
  22689. log += "\n\t\t" + animation.toString(fullDetails);
  22690. }
  22691. }
  22692. // Materials
  22693. if (parsedData.materials) {
  22694. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  22695. var parsedMaterial = parsedData.materials[index];
  22696. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  22697. log += (index === 0 ? "\n\tMaterials:" : "");
  22698. log += "\n\t\t" + mat.toString(fullDetails);
  22699. }
  22700. }
  22701. if (parsedData.multiMaterials) {
  22702. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  22703. var parsedMultiMaterial = parsedData.multiMaterials[index];
  22704. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  22705. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  22706. log += "\n\t\t" + mmat.toString(fullDetails);
  22707. }
  22708. }
  22709. // Skeletons
  22710. if (parsedData.skeletons) {
  22711. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  22712. var parsedSkeleton = parsedData.skeletons[index];
  22713. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  22714. log += (index === 0 ? "\n\tSkeletons:" : "");
  22715. log += "\n\t\t" + skeleton.toString(fullDetails);
  22716. }
  22717. }
  22718. // Geometries
  22719. var geometries = parsedData.geometries;
  22720. if (geometries) {
  22721. // Boxes
  22722. var boxes = geometries.boxes;
  22723. if (boxes) {
  22724. for (index = 0, cache = boxes.length; index < cache; index++) {
  22725. var parsedBox = boxes[index];
  22726. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  22727. }
  22728. }
  22729. // Spheres
  22730. var spheres = geometries.spheres;
  22731. if (spheres) {
  22732. for (index = 0, cache = spheres.length; index < cache; index++) {
  22733. var parsedSphere = spheres[index];
  22734. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  22735. }
  22736. }
  22737. // Cylinders
  22738. var cylinders = geometries.cylinders;
  22739. if (cylinders) {
  22740. for (index = 0, cache = cylinders.length; index < cache; index++) {
  22741. var parsedCylinder = cylinders[index];
  22742. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  22743. }
  22744. }
  22745. // Toruses
  22746. var toruses = geometries.toruses;
  22747. if (toruses) {
  22748. for (index = 0, cache = toruses.length; index < cache; index++) {
  22749. var parsedTorus = toruses[index];
  22750. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  22751. }
  22752. }
  22753. // Grounds
  22754. var grounds = geometries.grounds;
  22755. if (grounds) {
  22756. for (index = 0, cache = grounds.length; index < cache; index++) {
  22757. var parsedGround = grounds[index];
  22758. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  22759. }
  22760. }
  22761. // Planes
  22762. var planes = geometries.planes;
  22763. if (planes) {
  22764. for (index = 0, cache = planes.length; index < cache; index++) {
  22765. var parsedPlane = planes[index];
  22766. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  22767. }
  22768. }
  22769. // TorusKnots
  22770. var torusKnots = geometries.torusKnots;
  22771. if (torusKnots) {
  22772. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  22773. var parsedTorusKnot = torusKnots[index];
  22774. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  22775. }
  22776. }
  22777. // VertexData
  22778. var vertexData = geometries.vertexData;
  22779. if (vertexData) {
  22780. for (index = 0, cache = vertexData.length; index < cache; index++) {
  22781. var parsedVertexData = vertexData[index];
  22782. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  22783. }
  22784. }
  22785. }
  22786. // Meshes
  22787. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  22788. var parsedMesh = parsedData.meshes[index];
  22789. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  22790. log += (index === 0 ? "\n\tMeshes:" : "");
  22791. log += "\n\t\t" + mesh.toString(fullDetails);
  22792. }
  22793. // Cameras
  22794. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  22795. var parsedCamera = parsedData.cameras[index];
  22796. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  22797. log += (index === 0 ? "\n\tCameras:" : "");
  22798. log += "\n\t\t" + camera.toString(fullDetails);
  22799. }
  22800. if (parsedData.activeCameraID) {
  22801. scene.setActiveCameraByID(parsedData.activeCameraID);
  22802. }
  22803. // Browsing all the graph to connect the dots
  22804. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  22805. var camera = scene.cameras[index];
  22806. if (camera._waitingParentId) {
  22807. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  22808. camera._waitingParentId = undefined;
  22809. }
  22810. }
  22811. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  22812. var light = scene.lights[index];
  22813. if (light._waitingParentId) {
  22814. light.parent = scene.getLastEntryByID(light._waitingParentId);
  22815. light._waitingParentId = undefined;
  22816. }
  22817. }
  22818. // Sounds
  22819. var loadedSounds = [];
  22820. var loadedSound;
  22821. if (BABYLON.AudioEngine && parsedData.sounds) {
  22822. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  22823. var parsedSound = parsedData.sounds[index];
  22824. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  22825. if (!parsedSound.url)
  22826. parsedSound.url = parsedSound.name;
  22827. if (!loadedSounds[parsedSound.url]) {
  22828. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  22829. loadedSounds[parsedSound.url] = loadedSound;
  22830. }
  22831. else {
  22832. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  22833. }
  22834. }
  22835. else {
  22836. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  22837. }
  22838. }
  22839. log += (index === 0 ? "\n\tSounds:" : "");
  22840. log += "\n\t\t" + mat.toString(fullDetails);
  22841. }
  22842. loadedSounds = [];
  22843. // Connect parents & children and parse actions
  22844. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22845. var mesh = scene.meshes[index];
  22846. if (mesh._waitingParentId) {
  22847. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  22848. mesh._waitingParentId = undefined;
  22849. }
  22850. if (mesh._waitingActions) {
  22851. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  22852. mesh._waitingActions = undefined;
  22853. }
  22854. }
  22855. // freeze world matrix application
  22856. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22857. var currentMesh = scene.meshes[index];
  22858. if (currentMesh._waitingFreezeWorldMatrix) {
  22859. currentMesh.freezeWorldMatrix();
  22860. currentMesh._waitingFreezeWorldMatrix = undefined;
  22861. }
  22862. else {
  22863. currentMesh.computeWorldMatrix(true);
  22864. }
  22865. }
  22866. // Particles Systems
  22867. if (parsedData.particleSystems) {
  22868. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  22869. var parsedParticleSystem = parsedData.particleSystems[index];
  22870. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  22871. }
  22872. }
  22873. // Lens flares
  22874. if (parsedData.lensFlareSystems) {
  22875. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  22876. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  22877. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  22878. }
  22879. }
  22880. // Shadows
  22881. if (parsedData.shadowGenerators) {
  22882. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  22883. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  22884. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  22885. }
  22886. }
  22887. // Actions (scene)
  22888. if (parsedData.actions) {
  22889. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  22890. }
  22891. // Finish
  22892. return true;
  22893. }
  22894. catch (err) {
  22895. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  22896. log = null;
  22897. throw err;
  22898. }
  22899. finally {
  22900. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  22901. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  22902. }
  22903. }
  22904. }
  22905. });
  22906. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22907. })(BABYLON || (BABYLON = {}));
  22908. var BABYLON;
  22909. (function (BABYLON) {
  22910. var SpriteManager = (function () {
  22911. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  22912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22913. this.name = name;
  22914. this.cellSize = cellSize;
  22915. this.sprites = new Array();
  22916. this.renderingGroupId = 0;
  22917. this.layerMask = 0x0FFFFFFF;
  22918. this.fogEnabled = true;
  22919. this.isPickable = false;
  22920. this._vertexDeclaration = [4, 4, 4, 4];
  22921. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  22922. this._capacity = capacity;
  22923. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  22924. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22925. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22926. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  22927. this._scene = scene;
  22928. this._scene.spriteManagers.push(this);
  22929. // VBO
  22930. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  22931. var indices = [];
  22932. var index = 0;
  22933. for (var count = 0; count < capacity; count++) {
  22934. indices.push(index);
  22935. indices.push(index + 1);
  22936. indices.push(index + 2);
  22937. indices.push(index);
  22938. indices.push(index + 2);
  22939. indices.push(index + 3);
  22940. index += 4;
  22941. }
  22942. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22943. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  22944. // Effects
  22945. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  22946. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  22947. }
  22948. Object.defineProperty(SpriteManager.prototype, "texture", {
  22949. get: function () {
  22950. return this._spriteTexture;
  22951. },
  22952. set: function (value) {
  22953. this._spriteTexture = value;
  22954. },
  22955. enumerable: true,
  22956. configurable: true
  22957. });
  22958. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  22959. var arrayOffset = index * 16;
  22960. if (offsetX === 0)
  22961. offsetX = this._epsilon;
  22962. else if (offsetX === 1)
  22963. offsetX = 1 - this._epsilon;
  22964. if (offsetY === 0)
  22965. offsetY = this._epsilon;
  22966. else if (offsetY === 1)
  22967. offsetY = 1 - this._epsilon;
  22968. this._vertices[arrayOffset] = sprite.position.x;
  22969. this._vertices[arrayOffset + 1] = sprite.position.y;
  22970. this._vertices[arrayOffset + 2] = sprite.position.z;
  22971. this._vertices[arrayOffset + 3] = sprite.angle;
  22972. this._vertices[arrayOffset + 4] = sprite.width;
  22973. this._vertices[arrayOffset + 5] = sprite.height;
  22974. this._vertices[arrayOffset + 6] = offsetX;
  22975. this._vertices[arrayOffset + 7] = offsetY;
  22976. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  22977. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  22978. var offset = (sprite.cellIndex / rowSize) >> 0;
  22979. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  22980. this._vertices[arrayOffset + 11] = offset;
  22981. // Color
  22982. this._vertices[arrayOffset + 12] = sprite.color.r;
  22983. this._vertices[arrayOffset + 13] = sprite.color.g;
  22984. this._vertices[arrayOffset + 14] = sprite.color.b;
  22985. this._vertices[arrayOffset + 15] = sprite.color.a;
  22986. };
  22987. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  22988. var count = Math.min(this._capacity, this.sprites.length);
  22989. var min = BABYLON.Vector3.Zero();
  22990. var max = BABYLON.Vector3.Zero();
  22991. var distance = Number.MAX_VALUE;
  22992. var currentSprite;
  22993. var cameraSpacePosition = BABYLON.Vector3.Zero();
  22994. var cameraView = camera.getViewMatrix();
  22995. for (var index = 0; index < count; index++) {
  22996. var sprite = this.sprites[index];
  22997. if (!sprite) {
  22998. continue;
  22999. }
  23000. if (predicate) {
  23001. if (!predicate(sprite)) {
  23002. continue;
  23003. }
  23004. }
  23005. else if (!sprite.isPickable) {
  23006. continue;
  23007. }
  23008. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  23009. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  23010. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  23011. if (ray.intersectsBoxMinMax(min, max)) {
  23012. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  23013. if (distance > currentDistance) {
  23014. distance = currentDistance;
  23015. currentSprite = sprite;
  23016. if (fastCheck) {
  23017. break;
  23018. }
  23019. }
  23020. }
  23021. }
  23022. if (currentSprite) {
  23023. var result = new BABYLON.PickingInfo();
  23024. result.hit = true;
  23025. result.pickedSprite = currentSprite;
  23026. result.distance = distance;
  23027. return result;
  23028. }
  23029. return null;
  23030. };
  23031. SpriteManager.prototype.render = function () {
  23032. // Check
  23033. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  23034. return;
  23035. var engine = this._scene.getEngine();
  23036. var baseSize = this._spriteTexture.getBaseSize();
  23037. // Sprites
  23038. var deltaTime = engine.getDeltaTime();
  23039. var max = Math.min(this._capacity, this.sprites.length);
  23040. var rowSize = baseSize.width / this.cellSize;
  23041. var offset = 0;
  23042. for (var index = 0; index < max; index++) {
  23043. var sprite = this.sprites[index];
  23044. if (!sprite) {
  23045. continue;
  23046. }
  23047. sprite._animate(deltaTime);
  23048. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  23049. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  23050. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  23051. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  23052. }
  23053. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  23054. // Render
  23055. var effect = this._effectBase;
  23056. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23057. effect = this._effectFog;
  23058. }
  23059. engine.enableEffect(effect);
  23060. var viewMatrix = this._scene.getViewMatrix();
  23061. effect.setTexture("diffuseSampler", this._spriteTexture);
  23062. effect.setMatrix("view", viewMatrix);
  23063. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  23064. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  23065. // Fog
  23066. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23067. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  23068. effect.setColor3("vFogColor", this._scene.fogColor);
  23069. }
  23070. // VBOs
  23071. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23072. // Draw order
  23073. engine.setDepthFunctionToLessOrEqual();
  23074. effect.setBool("alphaTest", true);
  23075. engine.setColorWrite(false);
  23076. engine.draw(true, 0, max * 6);
  23077. engine.setColorWrite(true);
  23078. effect.setBool("alphaTest", false);
  23079. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23080. engine.draw(true, 0, max * 6);
  23081. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23082. };
  23083. SpriteManager.prototype.dispose = function () {
  23084. if (this._vertexBuffer) {
  23085. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23086. this._vertexBuffer = null;
  23087. }
  23088. if (this._indexBuffer) {
  23089. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23090. this._indexBuffer = null;
  23091. }
  23092. if (this._spriteTexture) {
  23093. this._spriteTexture.dispose();
  23094. this._spriteTexture = null;
  23095. }
  23096. // Remove from scene
  23097. var index = this._scene.spriteManagers.indexOf(this);
  23098. this._scene.spriteManagers.splice(index, 1);
  23099. // Callback
  23100. if (this.onDispose) {
  23101. this.onDispose();
  23102. }
  23103. };
  23104. return SpriteManager;
  23105. })();
  23106. BABYLON.SpriteManager = SpriteManager;
  23107. })(BABYLON || (BABYLON = {}));
  23108. var BABYLON;
  23109. (function (BABYLON) {
  23110. var Sprite = (function () {
  23111. function Sprite(name, manager) {
  23112. this.name = name;
  23113. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23114. this.width = 1.0;
  23115. this.height = 1.0;
  23116. this.angle = 0;
  23117. this.cellIndex = 0;
  23118. this.invertU = 0;
  23119. this.invertV = 0;
  23120. this.animations = new Array();
  23121. this.isPickable = false;
  23122. this._animationStarted = false;
  23123. this._loopAnimation = false;
  23124. this._fromIndex = 0;
  23125. this._toIndex = 0;
  23126. this._delay = 0;
  23127. this._direction = 1;
  23128. this._frameCount = 0;
  23129. this._time = 0;
  23130. this._manager = manager;
  23131. this._manager.sprites.push(this);
  23132. this.position = BABYLON.Vector3.Zero();
  23133. }
  23134. Object.defineProperty(Sprite.prototype, "size", {
  23135. get: function () {
  23136. return this.width;
  23137. },
  23138. set: function (value) {
  23139. this.width = value;
  23140. this.height = value;
  23141. },
  23142. enumerable: true,
  23143. configurable: true
  23144. });
  23145. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  23146. this._fromIndex = from;
  23147. this._toIndex = to;
  23148. this._loopAnimation = loop;
  23149. this._delay = delay;
  23150. this._animationStarted = true;
  23151. this._direction = from < to ? 1 : -1;
  23152. this.cellIndex = from;
  23153. this._time = 0;
  23154. };
  23155. Sprite.prototype.stopAnimation = function () {
  23156. this._animationStarted = false;
  23157. };
  23158. Sprite.prototype._animate = function (deltaTime) {
  23159. if (!this._animationStarted)
  23160. return;
  23161. this._time += deltaTime;
  23162. if (this._time > this._delay) {
  23163. this._time = this._time % this._delay;
  23164. this.cellIndex += this._direction;
  23165. if (this.cellIndex == this._toIndex) {
  23166. if (this._loopAnimation) {
  23167. this.cellIndex = this._fromIndex;
  23168. }
  23169. else {
  23170. this._animationStarted = false;
  23171. if (this.disposeWhenFinishedAnimating) {
  23172. this.dispose();
  23173. }
  23174. }
  23175. }
  23176. }
  23177. };
  23178. Sprite.prototype.dispose = function () {
  23179. for (var i = 0; i < this._manager.sprites.length; i++) {
  23180. if (this._manager.sprites[i] == this) {
  23181. this._manager.sprites.splice(i, 1);
  23182. }
  23183. }
  23184. };
  23185. return Sprite;
  23186. })();
  23187. BABYLON.Sprite = Sprite;
  23188. })(BABYLON || (BABYLON = {}));
  23189. var BABYLON;
  23190. (function (BABYLON) {
  23191. var Layer = (function () {
  23192. function Layer(name, imgUrl, scene, isBackground, color) {
  23193. this.name = name;
  23194. this.scale = new BABYLON.Vector2(1, 1);
  23195. this.offset = new BABYLON.Vector2(0, 0);
  23196. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  23197. this._vertexDeclaration = [2];
  23198. this._vertexStrideSize = 2 * 4;
  23199. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  23200. this.isBackground = isBackground === undefined ? true : isBackground;
  23201. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  23202. this._scene = scene;
  23203. this._scene.layers.push(this);
  23204. // VBO
  23205. var vertices = [];
  23206. vertices.push(1, 1);
  23207. vertices.push(-1, 1);
  23208. vertices.push(-1, -1);
  23209. vertices.push(1, -1);
  23210. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23211. // Indices
  23212. var indices = [];
  23213. indices.push(0);
  23214. indices.push(1);
  23215. indices.push(2);
  23216. indices.push(0);
  23217. indices.push(2);
  23218. indices.push(3);
  23219. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23220. // Effects
  23221. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  23222. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  23223. }
  23224. Layer.prototype.render = function () {
  23225. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  23226. // Check
  23227. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  23228. return;
  23229. var engine = this._scene.getEngine();
  23230. if (this.onBeforeRender) {
  23231. this.onBeforeRender();
  23232. }
  23233. // Render
  23234. engine.enableEffect(currentEffect);
  23235. engine.setState(false);
  23236. // Texture
  23237. currentEffect.setTexture("textureSampler", this.texture);
  23238. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  23239. // Color
  23240. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  23241. // Scale / offset
  23242. currentEffect.setVector2("offset", this.offset);
  23243. currentEffect.setVector2("scale", this.scale);
  23244. // VBOs
  23245. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  23246. // Draw order
  23247. if (!this._alphaTestEffect) {
  23248. engine.setAlphaMode(this.alphaBlendingMode);
  23249. engine.draw(true, 0, 6);
  23250. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23251. }
  23252. else {
  23253. engine.draw(true, 0, 6);
  23254. }
  23255. if (this.onAfterRender) {
  23256. this.onAfterRender();
  23257. }
  23258. };
  23259. Layer.prototype.dispose = function () {
  23260. if (this._vertexBuffer) {
  23261. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23262. this._vertexBuffer = null;
  23263. }
  23264. if (this._indexBuffer) {
  23265. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23266. this._indexBuffer = null;
  23267. }
  23268. if (this.texture) {
  23269. this.texture.dispose();
  23270. this.texture = null;
  23271. }
  23272. // Remove from scene
  23273. var index = this._scene.layers.indexOf(this);
  23274. this._scene.layers.splice(index, 1);
  23275. // Callback
  23276. if (this.onDispose) {
  23277. this.onDispose();
  23278. }
  23279. };
  23280. return Layer;
  23281. })();
  23282. BABYLON.Layer = Layer;
  23283. })(BABYLON || (BABYLON = {}));
  23284. var BABYLON;
  23285. (function (BABYLON) {
  23286. var Particle = (function () {
  23287. function Particle() {
  23288. this.position = BABYLON.Vector3.Zero();
  23289. this.direction = BABYLON.Vector3.Zero();
  23290. this.color = new BABYLON.Color4(0, 0, 0, 0);
  23291. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  23292. this.lifeTime = 1.0;
  23293. this.age = 0;
  23294. this.size = 0;
  23295. this.angle = 0;
  23296. this.angularSpeed = 0;
  23297. }
  23298. Particle.prototype.copyTo = function (other) {
  23299. other.position.copyFrom(this.position);
  23300. other.direction.copyFrom(this.direction);
  23301. other.color.copyFrom(this.color);
  23302. other.colorStep.copyFrom(this.colorStep);
  23303. other.lifeTime = this.lifeTime;
  23304. other.age = this.age;
  23305. other.size = this.size;
  23306. other.angle = this.angle;
  23307. other.angularSpeed = this.angularSpeed;
  23308. };
  23309. return Particle;
  23310. })();
  23311. BABYLON.Particle = Particle;
  23312. })(BABYLON || (BABYLON = {}));
  23313. var BABYLON;
  23314. (function (BABYLON) {
  23315. var randomNumber = function (min, max) {
  23316. if (min === max) {
  23317. return (min);
  23318. }
  23319. var random = Math.random();
  23320. return ((random * (max - min)) + min);
  23321. };
  23322. var ParticleSystem = (function () {
  23323. function ParticleSystem(name, capacity, scene, customEffect) {
  23324. var _this = this;
  23325. this.name = name;
  23326. // Members
  23327. this.animations = [];
  23328. this.renderingGroupId = 0;
  23329. this.emitter = null;
  23330. this.emitRate = 10;
  23331. this.manualEmitCount = -1;
  23332. this.updateSpeed = 0.01;
  23333. this.targetStopDuration = 0;
  23334. this.disposeOnStop = false;
  23335. this.minEmitPower = 1;
  23336. this.maxEmitPower = 1;
  23337. this.minLifeTime = 1;
  23338. this.maxLifeTime = 1;
  23339. this.minSize = 1;
  23340. this.maxSize = 1;
  23341. this.minAngularSpeed = 0;
  23342. this.maxAngularSpeed = 0;
  23343. this.layerMask = 0x0FFFFFFF;
  23344. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  23345. this.forceDepthWrite = false;
  23346. this.gravity = BABYLON.Vector3.Zero();
  23347. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  23348. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  23349. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  23350. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  23351. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23352. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23353. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  23354. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23355. this.particles = new Array();
  23356. this._vertexDeclaration = [3, 4, 4];
  23357. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  23358. this._stockParticles = new Array();
  23359. this._newPartsExcess = 0;
  23360. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  23361. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  23362. this._scaledDirection = BABYLON.Vector3.Zero();
  23363. this._scaledGravity = BABYLON.Vector3.Zero();
  23364. this._currentRenderId = -1;
  23365. this._started = false;
  23366. this._stopped = false;
  23367. this._actualFrame = 0;
  23368. this.id = name;
  23369. this._capacity = capacity;
  23370. this._scene = scene;
  23371. this._customEffect = customEffect;
  23372. scene.particleSystems.push(this);
  23373. // VBO
  23374. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  23375. var indices = [];
  23376. var index = 0;
  23377. for (var count = 0; count < capacity; count++) {
  23378. indices.push(index);
  23379. indices.push(index + 1);
  23380. indices.push(index + 2);
  23381. indices.push(index);
  23382. indices.push(index + 2);
  23383. indices.push(index + 3);
  23384. index += 4;
  23385. }
  23386. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23387. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  23388. // Default behaviors
  23389. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  23390. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  23391. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  23392. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  23393. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  23394. };
  23395. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  23396. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  23397. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  23398. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  23399. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  23400. };
  23401. this.updateFunction = function (particles) {
  23402. for (var index = 0; index < particles.length; index++) {
  23403. var particle = particles[index];
  23404. particle.age += _this._scaledUpdateSpeed;
  23405. if (particle.age >= particle.lifeTime) {
  23406. _this.recycleParticle(particle);
  23407. index--;
  23408. continue;
  23409. }
  23410. else {
  23411. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  23412. particle.color.addInPlace(_this._scaledColorStep);
  23413. if (particle.color.a < 0)
  23414. particle.color.a = 0;
  23415. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  23416. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  23417. particle.position.addInPlace(_this._scaledDirection);
  23418. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  23419. particle.direction.addInPlace(_this._scaledGravity);
  23420. }
  23421. }
  23422. };
  23423. }
  23424. ParticleSystem.prototype.recycleParticle = function (particle) {
  23425. var lastParticle = this.particles.pop();
  23426. if (lastParticle !== particle) {
  23427. lastParticle.copyTo(particle);
  23428. this._stockParticles.push(lastParticle);
  23429. }
  23430. };
  23431. ParticleSystem.prototype.getCapacity = function () {
  23432. return this._capacity;
  23433. };
  23434. ParticleSystem.prototype.isAlive = function () {
  23435. return this._alive;
  23436. };
  23437. ParticleSystem.prototype.isStarted = function () {
  23438. return this._started;
  23439. };
  23440. ParticleSystem.prototype.start = function () {
  23441. this._started = true;
  23442. this._stopped = false;
  23443. this._actualFrame = 0;
  23444. };
  23445. ParticleSystem.prototype.stop = function () {
  23446. this._stopped = true;
  23447. };
  23448. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  23449. var offset = index * 11;
  23450. this._vertices[offset] = particle.position.x;
  23451. this._vertices[offset + 1] = particle.position.y;
  23452. this._vertices[offset + 2] = particle.position.z;
  23453. this._vertices[offset + 3] = particle.color.r;
  23454. this._vertices[offset + 4] = particle.color.g;
  23455. this._vertices[offset + 5] = particle.color.b;
  23456. this._vertices[offset + 6] = particle.color.a;
  23457. this._vertices[offset + 7] = particle.angle;
  23458. this._vertices[offset + 8] = particle.size;
  23459. this._vertices[offset + 9] = offsetX;
  23460. this._vertices[offset + 10] = offsetY;
  23461. };
  23462. ParticleSystem.prototype._update = function (newParticles) {
  23463. // Update current
  23464. this._alive = this.particles.length > 0;
  23465. this.updateFunction(this.particles);
  23466. // Add new ones
  23467. var worldMatrix;
  23468. if (this.emitter.position) {
  23469. worldMatrix = this.emitter.getWorldMatrix();
  23470. }
  23471. else {
  23472. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  23473. }
  23474. var particle;
  23475. for (var index = 0; index < newParticles; index++) {
  23476. if (this.particles.length === this._capacity) {
  23477. break;
  23478. }
  23479. if (this._stockParticles.length !== 0) {
  23480. particle = this._stockParticles.pop();
  23481. particle.age = 0;
  23482. }
  23483. else {
  23484. particle = new BABYLON.Particle();
  23485. }
  23486. this.particles.push(particle);
  23487. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  23488. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  23489. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  23490. particle.size = randomNumber(this.minSize, this.maxSize);
  23491. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  23492. this.startPositionFunction(worldMatrix, particle.position, particle);
  23493. var step = randomNumber(0, 1.0);
  23494. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  23495. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  23496. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  23497. }
  23498. };
  23499. ParticleSystem.prototype._getEffect = function () {
  23500. if (this._customEffect) {
  23501. return this._customEffect;
  23502. }
  23503. ;
  23504. var defines = [];
  23505. if (this._scene.clipPlane) {
  23506. defines.push("#define CLIPPLANE");
  23507. }
  23508. // Effect
  23509. var join = defines.join("\n");
  23510. if (this._cachedDefines !== join) {
  23511. this._cachedDefines = join;
  23512. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  23513. }
  23514. return this._effect;
  23515. };
  23516. ParticleSystem.prototype.animate = function () {
  23517. if (!this._started)
  23518. return;
  23519. var effect = this._getEffect();
  23520. // Check
  23521. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  23522. return;
  23523. if (this._currentRenderId === this._scene.getRenderId()) {
  23524. return;
  23525. }
  23526. this._currentRenderId = this._scene.getRenderId();
  23527. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  23528. // determine the number of particles we need to create
  23529. var newParticles;
  23530. if (this.manualEmitCount > -1) {
  23531. newParticles = this.manualEmitCount;
  23532. this._newPartsExcess = 0;
  23533. this.manualEmitCount = 0;
  23534. }
  23535. else {
  23536. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  23537. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  23538. }
  23539. if (this._newPartsExcess > 1.0) {
  23540. newParticles += this._newPartsExcess >> 0;
  23541. this._newPartsExcess -= this._newPartsExcess >> 0;
  23542. }
  23543. this._alive = false;
  23544. if (!this._stopped) {
  23545. this._actualFrame += this._scaledUpdateSpeed;
  23546. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  23547. this.stop();
  23548. }
  23549. else {
  23550. newParticles = 0;
  23551. }
  23552. this._update(newParticles);
  23553. // Stopped?
  23554. if (this._stopped) {
  23555. if (!this._alive) {
  23556. this._started = false;
  23557. if (this.disposeOnStop) {
  23558. this._scene._toBeDisposed.push(this);
  23559. }
  23560. }
  23561. }
  23562. // Update VBO
  23563. var offset = 0;
  23564. for (var index = 0; index < this.particles.length; index++) {
  23565. var particle = this.particles[index];
  23566. this._appendParticleVertex(offset++, particle, 0, 0);
  23567. this._appendParticleVertex(offset++, particle, 1, 0);
  23568. this._appendParticleVertex(offset++, particle, 1, 1);
  23569. this._appendParticleVertex(offset++, particle, 0, 1);
  23570. }
  23571. var engine = this._scene.getEngine();
  23572. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  23573. };
  23574. ParticleSystem.prototype.render = function () {
  23575. var effect = this._getEffect();
  23576. // Check
  23577. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  23578. return 0;
  23579. var engine = this._scene.getEngine();
  23580. // Render
  23581. engine.enableEffect(effect);
  23582. engine.setState(false);
  23583. var viewMatrix = this._scene.getViewMatrix();
  23584. effect.setTexture("diffuseSampler", this.particleTexture);
  23585. effect.setMatrix("view", viewMatrix);
  23586. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  23587. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  23588. if (this._scene.clipPlane) {
  23589. var clipPlane = this._scene.clipPlane;
  23590. var invView = viewMatrix.clone();
  23591. invView.invert();
  23592. effect.setMatrix("invView", invView);
  23593. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23594. }
  23595. // VBOs
  23596. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23597. // Draw order
  23598. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  23599. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23600. }
  23601. else {
  23602. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23603. }
  23604. if (this.forceDepthWrite) {
  23605. engine.setDepthWrite(true);
  23606. }
  23607. engine.draw(true, 0, this.particles.length * 6);
  23608. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23609. return this.particles.length;
  23610. };
  23611. ParticleSystem.prototype.dispose = function () {
  23612. if (this._vertexBuffer) {
  23613. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23614. this._vertexBuffer = null;
  23615. }
  23616. if (this._indexBuffer) {
  23617. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23618. this._indexBuffer = null;
  23619. }
  23620. if (this.particleTexture) {
  23621. this.particleTexture.dispose();
  23622. this.particleTexture = null;
  23623. }
  23624. // Remove from scene
  23625. var index = this._scene.particleSystems.indexOf(this);
  23626. this._scene.particleSystems.splice(index, 1);
  23627. // Callback
  23628. if (this.onDispose) {
  23629. this.onDispose();
  23630. }
  23631. };
  23632. // Clone
  23633. ParticleSystem.prototype.clone = function (name, newEmitter) {
  23634. var result = new ParticleSystem(name, this._capacity, this._scene);
  23635. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  23636. if (newEmitter === undefined) {
  23637. newEmitter = this.emitter;
  23638. }
  23639. result.emitter = newEmitter;
  23640. if (this.particleTexture) {
  23641. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  23642. }
  23643. result.start();
  23644. return result;
  23645. };
  23646. ParticleSystem.prototype.serialize = function () {
  23647. var serializationObject = {};
  23648. serializationObject.name = this.name;
  23649. serializationObject.id = this.id;
  23650. // Emitter
  23651. if (this.emitter.position) {
  23652. serializationObject.emitterId = this.emitter.id;
  23653. }
  23654. else {
  23655. serializationObject.emitter = this.emitter.asArray();
  23656. }
  23657. serializationObject.capacity = this.getCapacity();
  23658. if (this.particleTexture) {
  23659. serializationObject.textureName = this.particleTexture.name;
  23660. }
  23661. // Animations
  23662. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23663. // Particle system
  23664. serializationObject.minAngularSpeed = this.minAngularSpeed;
  23665. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  23666. serializationObject.minSize = this.minSize;
  23667. serializationObject.maxSize = this.maxSize;
  23668. serializationObject.minEmitPower = this.minEmitPower;
  23669. serializationObject.maxEmitPower = this.maxEmitPower;
  23670. serializationObject.minLifeTime = this.minLifeTime;
  23671. serializationObject.maxLifeTime = this.maxLifeTime;
  23672. serializationObject.emitRate = this.emitRate;
  23673. serializationObject.minEmitBox = this.minEmitBox.asArray();
  23674. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  23675. serializationObject.gravity = this.gravity.asArray();
  23676. serializationObject.direction1 = this.direction1.asArray();
  23677. serializationObject.direction2 = this.direction2.asArray();
  23678. serializationObject.color1 = this.color1.asArray();
  23679. serializationObject.color2 = this.color2.asArray();
  23680. serializationObject.colorDead = this.colorDead.asArray();
  23681. serializationObject.updateSpeed = this.updateSpeed;
  23682. serializationObject.targetStopDuration = this.targetStopDuration;
  23683. serializationObject.textureMask = this.textureMask.asArray();
  23684. serializationObject.blendMode = this.blendMode;
  23685. return serializationObject;
  23686. };
  23687. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  23688. var name = parsedParticleSystem.name;
  23689. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  23690. if (parsedParticleSystem.id) {
  23691. particleSystem.id = parsedParticleSystem.id;
  23692. }
  23693. // Texture
  23694. if (parsedParticleSystem.textureName) {
  23695. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  23696. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  23697. }
  23698. // Emitter
  23699. if (parsedParticleSystem.emitterId) {
  23700. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  23701. }
  23702. else {
  23703. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  23704. }
  23705. // Animations
  23706. if (parsedParticleSystem.animations) {
  23707. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  23708. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  23709. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23710. }
  23711. }
  23712. if (parsedParticleSystem.autoAnimate) {
  23713. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  23714. }
  23715. // Particle system
  23716. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  23717. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  23718. particleSystem.minSize = parsedParticleSystem.minSize;
  23719. particleSystem.maxSize = parsedParticleSystem.maxSize;
  23720. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  23721. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  23722. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  23723. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  23724. particleSystem.emitRate = parsedParticleSystem.emitRate;
  23725. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  23726. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  23727. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  23728. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  23729. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  23730. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  23731. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  23732. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  23733. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  23734. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  23735. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  23736. particleSystem.blendMode = parsedParticleSystem.blendMode;
  23737. particleSystem.start();
  23738. return particleSystem;
  23739. };
  23740. // Statics
  23741. ParticleSystem.BLENDMODE_ONEONE = 0;
  23742. ParticleSystem.BLENDMODE_STANDARD = 1;
  23743. return ParticleSystem;
  23744. })();
  23745. BABYLON.ParticleSystem = ParticleSystem;
  23746. })(BABYLON || (BABYLON = {}));
  23747. var BABYLON;
  23748. (function (BABYLON) {
  23749. var AnimationRange = (function () {
  23750. function AnimationRange(name, from, to) {
  23751. this.name = name;
  23752. this.from = from;
  23753. this.to = to;
  23754. }
  23755. AnimationRange.prototype.clone = function () {
  23756. return new AnimationRange(this.name, this.from, this.to);
  23757. };
  23758. return AnimationRange;
  23759. })();
  23760. BABYLON.AnimationRange = AnimationRange;
  23761. /**
  23762. * Composed of a frame, and an action function
  23763. */
  23764. var AnimationEvent = (function () {
  23765. function AnimationEvent(frame, action, onlyOnce) {
  23766. this.frame = frame;
  23767. this.action = action;
  23768. this.onlyOnce = onlyOnce;
  23769. this.isDone = false;
  23770. }
  23771. return AnimationEvent;
  23772. })();
  23773. BABYLON.AnimationEvent = AnimationEvent;
  23774. var PathCursor = (function () {
  23775. function PathCursor(path) {
  23776. this.path = path;
  23777. this._onchange = new Array();
  23778. this.value = 0;
  23779. this.animations = new Array();
  23780. }
  23781. PathCursor.prototype.getPoint = function () {
  23782. var point = this.path.getPointAtLengthPosition(this.value);
  23783. return new BABYLON.Vector3(point.x, 0, point.y);
  23784. };
  23785. PathCursor.prototype.moveAhead = function (step) {
  23786. if (step === void 0) { step = 0.002; }
  23787. this.move(step);
  23788. return this;
  23789. };
  23790. PathCursor.prototype.moveBack = function (step) {
  23791. if (step === void 0) { step = 0.002; }
  23792. this.move(-step);
  23793. return this;
  23794. };
  23795. PathCursor.prototype.move = function (step) {
  23796. if (Math.abs(step) > 1) {
  23797. throw "step size should be less than 1.";
  23798. }
  23799. this.value += step;
  23800. this.ensureLimits();
  23801. this.raiseOnChange();
  23802. return this;
  23803. };
  23804. PathCursor.prototype.ensureLimits = function () {
  23805. while (this.value > 1) {
  23806. this.value -= 1;
  23807. }
  23808. while (this.value < 0) {
  23809. this.value += 1;
  23810. }
  23811. return this;
  23812. };
  23813. // used by animation engine
  23814. PathCursor.prototype.markAsDirty = function (propertyName) {
  23815. this.ensureLimits();
  23816. this.raiseOnChange();
  23817. return this;
  23818. };
  23819. PathCursor.prototype.raiseOnChange = function () {
  23820. var _this = this;
  23821. this._onchange.forEach(function (f) { return f(_this); });
  23822. return this;
  23823. };
  23824. PathCursor.prototype.onchange = function (f) {
  23825. this._onchange.push(f);
  23826. return this;
  23827. };
  23828. return PathCursor;
  23829. })();
  23830. BABYLON.PathCursor = PathCursor;
  23831. var Animation = (function () {
  23832. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  23833. this.name = name;
  23834. this.targetProperty = targetProperty;
  23835. this.framePerSecond = framePerSecond;
  23836. this.dataType = dataType;
  23837. this.loopMode = loopMode;
  23838. this.enableBlending = enableBlending;
  23839. this._offsetsCache = {};
  23840. this._highLimitsCache = {};
  23841. this._stopped = false;
  23842. this._blendingFactor = 0;
  23843. // The set of event that will be linked to this animation
  23844. this._events = new Array();
  23845. this.allowMatricesInterpolation = false;
  23846. this.blendingSpeed = 0.01;
  23847. this._ranges = {};
  23848. this.targetPropertyPath = targetProperty.split(".");
  23849. this.dataType = dataType;
  23850. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  23851. }
  23852. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  23853. var dataType = undefined;
  23854. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  23855. dataType = Animation.ANIMATIONTYPE_FLOAT;
  23856. }
  23857. else if (from instanceof BABYLON.Quaternion) {
  23858. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  23859. }
  23860. else if (from instanceof BABYLON.Vector3) {
  23861. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  23862. }
  23863. else if (from instanceof BABYLON.Vector2) {
  23864. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  23865. }
  23866. else if (from instanceof BABYLON.Color3) {
  23867. dataType = Animation.ANIMATIONTYPE_COLOR3;
  23868. }
  23869. if (dataType == undefined) {
  23870. return null;
  23871. }
  23872. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  23873. var keys = [];
  23874. keys.push({ frame: 0, value: from });
  23875. keys.push({ frame: totalFrame, value: to });
  23876. animation.setKeys(keys);
  23877. if (easingFunction !== undefined) {
  23878. animation.setEasingFunction(easingFunction);
  23879. }
  23880. return animation;
  23881. };
  23882. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  23883. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  23884. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  23885. };
  23886. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  23887. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  23888. node.animations.push(animation);
  23889. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  23890. };
  23891. // Methods
  23892. /**
  23893. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23894. */
  23895. Animation.prototype.toString = function (fullDetails) {
  23896. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  23897. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  23898. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  23899. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  23900. if (fullDetails) {
  23901. ret += ", Ranges: {";
  23902. var first = true;
  23903. for (var name in this._ranges) {
  23904. if (!first) {
  23905. ret + ", ";
  23906. first = false;
  23907. }
  23908. ret += name;
  23909. }
  23910. ret += "}";
  23911. }
  23912. return ret;
  23913. };
  23914. /**
  23915. * Add an event to this animation.
  23916. */
  23917. Animation.prototype.addEvent = function (event) {
  23918. this._events.push(event);
  23919. };
  23920. /**
  23921. * Remove all events found at the given frame
  23922. * @param frame
  23923. */
  23924. Animation.prototype.removeEvents = function (frame) {
  23925. for (var index = 0; index < this._events.length; index++) {
  23926. if (this._events[index].frame === frame) {
  23927. this._events.splice(index, 1);
  23928. index--;
  23929. }
  23930. }
  23931. };
  23932. Animation.prototype.createRange = function (name, from, to) {
  23933. // check name not already in use; could happen for bones after serialized
  23934. if (!this._ranges[name]) {
  23935. this._ranges[name] = new AnimationRange(name, from, to);
  23936. }
  23937. };
  23938. Animation.prototype.deleteRange = function (name, deleteFrames) {
  23939. if (deleteFrames === void 0) { deleteFrames = true; }
  23940. if (this._ranges[name]) {
  23941. if (deleteFrames) {
  23942. var from = this._ranges[name].from;
  23943. var to = this._ranges[name].to;
  23944. // this loop MUST go high to low for multiple splices to work
  23945. for (var key = this._keys.length - 1; key >= 0; key--) {
  23946. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  23947. this._keys.splice(key, 1);
  23948. }
  23949. }
  23950. }
  23951. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23952. }
  23953. };
  23954. Animation.prototype.getRange = function (name) {
  23955. return this._ranges[name];
  23956. };
  23957. Animation.prototype.reset = function () {
  23958. this._offsetsCache = {};
  23959. this._highLimitsCache = {};
  23960. this.currentFrame = 0;
  23961. this._blendingFactor = 0;
  23962. this._originalBlendValue = null;
  23963. };
  23964. Animation.prototype.isStopped = function () {
  23965. return this._stopped;
  23966. };
  23967. Animation.prototype.getKeys = function () {
  23968. return this._keys;
  23969. };
  23970. Animation.prototype.getHighestFrame = function () {
  23971. var ret = 0;
  23972. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  23973. if (ret < this._keys[key].frame) {
  23974. ret = this._keys[key].frame;
  23975. }
  23976. }
  23977. return ret;
  23978. };
  23979. Animation.prototype.getEasingFunction = function () {
  23980. return this._easingFunction;
  23981. };
  23982. Animation.prototype.setEasingFunction = function (easingFunction) {
  23983. this._easingFunction = easingFunction;
  23984. };
  23985. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  23986. return startValue + (endValue - startValue) * gradient;
  23987. };
  23988. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  23989. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  23990. };
  23991. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  23992. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  23993. };
  23994. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  23995. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  23996. };
  23997. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  23998. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  23999. };
  24000. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  24001. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  24002. };
  24003. Animation.prototype.clone = function () {
  24004. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  24005. if (this._keys) {
  24006. clone.setKeys(this._keys);
  24007. }
  24008. if (this._ranges) {
  24009. clone._ranges = {};
  24010. for (var name in this._ranges) {
  24011. clone._ranges[name] = this._ranges[name].clone();
  24012. }
  24013. }
  24014. return clone;
  24015. };
  24016. Animation.prototype.setKeys = function (values) {
  24017. this._keys = values.slice(0);
  24018. this._offsetsCache = {};
  24019. this._highLimitsCache = {};
  24020. };
  24021. Animation.prototype._getKeyValue = function (value) {
  24022. if (typeof value === "function") {
  24023. return value();
  24024. }
  24025. return value;
  24026. };
  24027. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  24028. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  24029. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  24030. }
  24031. this.currentFrame = currentFrame;
  24032. // Try to get a hash to find the right key
  24033. 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));
  24034. if (this._keys[startKey].frame >= currentFrame) {
  24035. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  24036. startKey--;
  24037. }
  24038. }
  24039. for (var key = startKey; key < this._keys.length; key++) {
  24040. if (this._keys[key + 1].frame >= currentFrame) {
  24041. var startValue = this._getKeyValue(this._keys[key].value);
  24042. var endValue = this._getKeyValue(this._keys[key + 1].value);
  24043. // gradient : percent of currentFrame between the frame inf and the frame sup
  24044. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  24045. // check for easingFunction and correction of gradient
  24046. if (this._easingFunction != null) {
  24047. gradient = this._easingFunction.ease(gradient);
  24048. }
  24049. switch (this.dataType) {
  24050. // Float
  24051. case Animation.ANIMATIONTYPE_FLOAT:
  24052. switch (loopMode) {
  24053. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24054. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24055. return this.floatInterpolateFunction(startValue, endValue, gradient);
  24056. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24057. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  24058. }
  24059. break;
  24060. // Quaternion
  24061. case Animation.ANIMATIONTYPE_QUATERNION:
  24062. var quaternion = null;
  24063. switch (loopMode) {
  24064. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24065. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24066. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  24067. break;
  24068. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24069. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24070. break;
  24071. }
  24072. return quaternion;
  24073. // Vector3
  24074. case Animation.ANIMATIONTYPE_VECTOR3:
  24075. switch (loopMode) {
  24076. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24077. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24078. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  24079. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24080. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24081. }
  24082. // Vector2
  24083. case Animation.ANIMATIONTYPE_VECTOR2:
  24084. switch (loopMode) {
  24085. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24086. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24087. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  24088. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24089. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24090. }
  24091. // Color3
  24092. case Animation.ANIMATIONTYPE_COLOR3:
  24093. switch (loopMode) {
  24094. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24095. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24096. return this.color3InterpolateFunction(startValue, endValue, gradient);
  24097. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24098. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24099. }
  24100. // Matrix
  24101. case Animation.ANIMATIONTYPE_MATRIX:
  24102. switch (loopMode) {
  24103. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24104. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24105. if (this.allowMatricesInterpolation) {
  24106. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  24107. }
  24108. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24109. return startValue;
  24110. }
  24111. default:
  24112. break;
  24113. }
  24114. break;
  24115. }
  24116. }
  24117. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  24118. };
  24119. Animation.prototype.setValue = function (currentValue, blend) {
  24120. if (blend === void 0) { blend = false; }
  24121. // Set value
  24122. var path;
  24123. var destination;
  24124. if (this.targetPropertyPath.length > 1) {
  24125. var property = this._target[this.targetPropertyPath[0]];
  24126. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  24127. property = property[this.targetPropertyPath[index]];
  24128. }
  24129. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  24130. destination = property;
  24131. }
  24132. else {
  24133. path = this.targetPropertyPath[0];
  24134. destination = this._target;
  24135. }
  24136. // Blending
  24137. if (this.enableBlending && this._blendingFactor <= 1.0) {
  24138. if (!this._originalBlendValue) {
  24139. this._originalBlendValue = destination[path];
  24140. }
  24141. if (this._originalBlendValue.prototype) {
  24142. if (this._originalBlendValue.prototype.Lerp) {
  24143. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  24144. }
  24145. else {
  24146. destination[path] = currentValue;
  24147. }
  24148. }
  24149. else {
  24150. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  24151. }
  24152. this._blendingFactor += this.blendingSpeed;
  24153. }
  24154. else {
  24155. destination[path] = currentValue;
  24156. }
  24157. if (this._target.markAsDirty) {
  24158. this._target.markAsDirty(this.targetProperty);
  24159. }
  24160. };
  24161. Animation.prototype.goToFrame = function (frame) {
  24162. if (frame < this._keys[0].frame) {
  24163. frame = this._keys[0].frame;
  24164. }
  24165. else if (frame > this._keys[this._keys.length - 1].frame) {
  24166. frame = this._keys[this._keys.length - 1].frame;
  24167. }
  24168. var currentValue = this._interpolate(frame, 0, this.loopMode);
  24169. this.setValue(currentValue);
  24170. };
  24171. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  24172. if (blend === void 0) { blend = false; }
  24173. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  24174. this._stopped = true;
  24175. return false;
  24176. }
  24177. var returnValue = true;
  24178. // Adding a start key at frame 0 if missing
  24179. if (this._keys[0].frame !== 0) {
  24180. var newKey = { frame: 0, value: this._keys[0].value };
  24181. this._keys.splice(0, 0, newKey);
  24182. }
  24183. // Check limits
  24184. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  24185. from = this._keys[0].frame;
  24186. }
  24187. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  24188. to = this._keys[this._keys.length - 1].frame;
  24189. }
  24190. // Compute ratio
  24191. var range = to - from;
  24192. var offsetValue;
  24193. // ratio represents the frame delta between from and to
  24194. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  24195. var highLimitValue = 0;
  24196. if (ratio > range && !loop) {
  24197. returnValue = false;
  24198. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  24199. }
  24200. else {
  24201. // Get max value if required
  24202. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  24203. var keyOffset = to.toString() + from.toString();
  24204. if (!this._offsetsCache[keyOffset]) {
  24205. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24206. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24207. switch (this.dataType) {
  24208. // Float
  24209. case Animation.ANIMATIONTYPE_FLOAT:
  24210. this._offsetsCache[keyOffset] = toValue - fromValue;
  24211. break;
  24212. // Quaternion
  24213. case Animation.ANIMATIONTYPE_QUATERNION:
  24214. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24215. break;
  24216. // Vector3
  24217. case Animation.ANIMATIONTYPE_VECTOR3:
  24218. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24219. // Vector2
  24220. case Animation.ANIMATIONTYPE_VECTOR2:
  24221. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24222. // Color3
  24223. case Animation.ANIMATIONTYPE_COLOR3:
  24224. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24225. default:
  24226. break;
  24227. }
  24228. this._highLimitsCache[keyOffset] = toValue;
  24229. }
  24230. highLimitValue = this._highLimitsCache[keyOffset];
  24231. offsetValue = this._offsetsCache[keyOffset];
  24232. }
  24233. }
  24234. if (offsetValue === undefined) {
  24235. switch (this.dataType) {
  24236. // Float
  24237. case Animation.ANIMATIONTYPE_FLOAT:
  24238. offsetValue = 0;
  24239. break;
  24240. // Quaternion
  24241. case Animation.ANIMATIONTYPE_QUATERNION:
  24242. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  24243. break;
  24244. // Vector3
  24245. case Animation.ANIMATIONTYPE_VECTOR3:
  24246. offsetValue = BABYLON.Vector3.Zero();
  24247. break;
  24248. // Vector2
  24249. case Animation.ANIMATIONTYPE_VECTOR2:
  24250. offsetValue = BABYLON.Vector2.Zero();
  24251. break;
  24252. // Color3
  24253. case Animation.ANIMATIONTYPE_COLOR3:
  24254. offsetValue = BABYLON.Color3.Black();
  24255. }
  24256. }
  24257. // Compute value
  24258. var repeatCount = (ratio / range) >> 0;
  24259. var currentFrame = returnValue ? from + ratio % range : to;
  24260. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  24261. // Set value
  24262. this.setValue(currentValue);
  24263. // Check events
  24264. for (var index = 0; index < this._events.length; index++) {
  24265. if (currentFrame >= this._events[index].frame) {
  24266. var event = this._events[index];
  24267. if (!event.isDone) {
  24268. // If event should be done only once, remove it.
  24269. if (event.onlyOnce) {
  24270. this._events.splice(index, 1);
  24271. index--;
  24272. }
  24273. event.isDone = true;
  24274. event.action();
  24275. } // Don't do anything if the event has already be done.
  24276. }
  24277. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  24278. // reset event, the animation is looping
  24279. this._events[index].isDone = false;
  24280. }
  24281. }
  24282. if (!returnValue) {
  24283. this._stopped = true;
  24284. }
  24285. return returnValue;
  24286. };
  24287. Animation.prototype.serialize = function () {
  24288. var serializationObject = {};
  24289. serializationObject.name = this.name;
  24290. serializationObject.property = this.targetProperty;
  24291. serializationObject.framePerSecond = this.framePerSecond;
  24292. serializationObject.dataType = this.dataType;
  24293. serializationObject.loopBehavior = this.loopMode;
  24294. var dataType = this.dataType;
  24295. serializationObject.keys = [];
  24296. var keys = this.getKeys();
  24297. for (var index = 0; index < keys.length; index++) {
  24298. var animationKey = keys[index];
  24299. var key = {};
  24300. key.frame = animationKey.frame;
  24301. switch (dataType) {
  24302. case Animation.ANIMATIONTYPE_FLOAT:
  24303. key.values = [animationKey.value];
  24304. break;
  24305. case Animation.ANIMATIONTYPE_QUATERNION:
  24306. case Animation.ANIMATIONTYPE_MATRIX:
  24307. case Animation.ANIMATIONTYPE_VECTOR3:
  24308. case Animation.ANIMATIONTYPE_COLOR3:
  24309. key.values = animationKey.value.asArray();
  24310. break;
  24311. }
  24312. serializationObject.keys.push(key);
  24313. }
  24314. serializationObject.ranges = [];
  24315. for (var name in this._ranges) {
  24316. var range = {};
  24317. range.name = name;
  24318. range.from = this._ranges[name].from;
  24319. range.to = this._ranges[name].to;
  24320. serializationObject.ranges.push(range);
  24321. }
  24322. return serializationObject;
  24323. };
  24324. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  24325. get: function () {
  24326. return Animation._ANIMATIONTYPE_FLOAT;
  24327. },
  24328. enumerable: true,
  24329. configurable: true
  24330. });
  24331. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  24332. get: function () {
  24333. return Animation._ANIMATIONTYPE_VECTOR3;
  24334. },
  24335. enumerable: true,
  24336. configurable: true
  24337. });
  24338. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  24339. get: function () {
  24340. return Animation._ANIMATIONTYPE_VECTOR2;
  24341. },
  24342. enumerable: true,
  24343. configurable: true
  24344. });
  24345. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  24346. get: function () {
  24347. return Animation._ANIMATIONTYPE_QUATERNION;
  24348. },
  24349. enumerable: true,
  24350. configurable: true
  24351. });
  24352. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  24353. get: function () {
  24354. return Animation._ANIMATIONTYPE_MATRIX;
  24355. },
  24356. enumerable: true,
  24357. configurable: true
  24358. });
  24359. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  24360. get: function () {
  24361. return Animation._ANIMATIONTYPE_COLOR3;
  24362. },
  24363. enumerable: true,
  24364. configurable: true
  24365. });
  24366. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  24367. get: function () {
  24368. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  24369. },
  24370. enumerable: true,
  24371. configurable: true
  24372. });
  24373. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  24374. get: function () {
  24375. return Animation._ANIMATIONLOOPMODE_CYCLE;
  24376. },
  24377. enumerable: true,
  24378. configurable: true
  24379. });
  24380. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  24381. get: function () {
  24382. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Animation.Parse = function (parsedAnimation) {
  24388. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  24389. var dataType = parsedAnimation.dataType;
  24390. var keys = [];
  24391. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  24392. var key = parsedAnimation.keys[index];
  24393. var data;
  24394. switch (dataType) {
  24395. case Animation.ANIMATIONTYPE_FLOAT:
  24396. data = key.values[0];
  24397. break;
  24398. case Animation.ANIMATIONTYPE_QUATERNION:
  24399. data = BABYLON.Quaternion.FromArray(key.values);
  24400. break;
  24401. case Animation.ANIMATIONTYPE_MATRIX:
  24402. data = BABYLON.Matrix.FromArray(key.values);
  24403. break;
  24404. case Animation.ANIMATIONTYPE_COLOR3:
  24405. data = BABYLON.Color3.FromArray(key.values);
  24406. break;
  24407. case Animation.ANIMATIONTYPE_VECTOR3:
  24408. default:
  24409. data = BABYLON.Vector3.FromArray(key.values);
  24410. break;
  24411. }
  24412. keys.push({
  24413. frame: key.frame,
  24414. value: data
  24415. });
  24416. }
  24417. animation.setKeys(keys);
  24418. if (parsedAnimation.ranges) {
  24419. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  24420. data = parsedAnimation.ranges[index];
  24421. animation.createRange(data.name, data.from, data.to);
  24422. }
  24423. }
  24424. return animation;
  24425. };
  24426. Animation.AppendSerializedAnimations = function (source, destination) {
  24427. if (source.animations) {
  24428. destination.animations = [];
  24429. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24430. var animation = source.animations[animationIndex];
  24431. destination.animations.push(animation.serialize());
  24432. }
  24433. }
  24434. };
  24435. // Statics
  24436. Animation._ANIMATIONTYPE_FLOAT = 0;
  24437. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  24438. Animation._ANIMATIONTYPE_QUATERNION = 2;
  24439. Animation._ANIMATIONTYPE_MATRIX = 3;
  24440. Animation._ANIMATIONTYPE_COLOR3 = 4;
  24441. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  24442. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  24443. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  24444. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  24445. return Animation;
  24446. })();
  24447. BABYLON.Animation = Animation;
  24448. })(BABYLON || (BABYLON = {}));
  24449. var BABYLON;
  24450. (function (BABYLON) {
  24451. var Animatable = (function () {
  24452. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  24453. if (fromFrame === void 0) { fromFrame = 0; }
  24454. if (toFrame === void 0) { toFrame = 100; }
  24455. if (loopAnimation === void 0) { loopAnimation = false; }
  24456. if (speedRatio === void 0) { speedRatio = 1.0; }
  24457. this.target = target;
  24458. this.fromFrame = fromFrame;
  24459. this.toFrame = toFrame;
  24460. this.loopAnimation = loopAnimation;
  24461. this.speedRatio = speedRatio;
  24462. this.onAnimationEnd = onAnimationEnd;
  24463. this._animations = new Array();
  24464. this._paused = false;
  24465. this.animationStarted = false;
  24466. if (animations) {
  24467. this.appendAnimations(target, animations);
  24468. }
  24469. this._scene = scene;
  24470. scene._activeAnimatables.push(this);
  24471. }
  24472. // Methods
  24473. Animatable.prototype.getAnimations = function () {
  24474. return this._animations;
  24475. };
  24476. Animatable.prototype.appendAnimations = function (target, animations) {
  24477. for (var index = 0; index < animations.length; index++) {
  24478. var animation = animations[index];
  24479. animation._target = target;
  24480. this._animations.push(animation);
  24481. }
  24482. };
  24483. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  24484. var animations = this._animations;
  24485. for (var index = 0; index < animations.length; index++) {
  24486. if (animations[index].targetProperty === property) {
  24487. return animations[index];
  24488. }
  24489. }
  24490. return null;
  24491. };
  24492. Animatable.prototype.reset = function () {
  24493. var animations = this._animations;
  24494. for (var index = 0; index < animations.length; index++) {
  24495. animations[index].reset();
  24496. }
  24497. this._localDelayOffset = null;
  24498. this._pausedDelay = null;
  24499. };
  24500. Animatable.prototype.enableBlending = function (blendingSpeed) {
  24501. var animations = this._animations;
  24502. for (var index = 0; index < animations.length; index++) {
  24503. animations[index].enableBlending = true;
  24504. animations[index].blendingSpeed = blendingSpeed;
  24505. }
  24506. };
  24507. Animatable.prototype.disableBlending = function () {
  24508. var animations = this._animations;
  24509. for (var index = 0; index < animations.length; index++) {
  24510. animations[index].enableBlending = false;
  24511. }
  24512. };
  24513. Animatable.prototype.goToFrame = function (frame) {
  24514. var animations = this._animations;
  24515. for (var index = 0; index < animations.length; index++) {
  24516. animations[index].goToFrame(frame);
  24517. }
  24518. };
  24519. Animatable.prototype.pause = function () {
  24520. if (this._paused) {
  24521. return;
  24522. }
  24523. this._paused = true;
  24524. };
  24525. Animatable.prototype.restart = function () {
  24526. this._paused = false;
  24527. };
  24528. Animatable.prototype.stop = function () {
  24529. var index = this._scene._activeAnimatables.indexOf(this);
  24530. if (index > -1) {
  24531. this._scene._activeAnimatables.splice(index, 1);
  24532. var animations = this._animations;
  24533. for (var index = 0; index < animations.length; index++) {
  24534. animations[index].reset();
  24535. }
  24536. if (this.onAnimationEnd) {
  24537. this.onAnimationEnd();
  24538. }
  24539. }
  24540. };
  24541. Animatable.prototype._animate = function (delay) {
  24542. if (this._paused) {
  24543. this.animationStarted = false;
  24544. if (!this._pausedDelay) {
  24545. this._pausedDelay = delay;
  24546. }
  24547. return true;
  24548. }
  24549. if (!this._localDelayOffset) {
  24550. this._localDelayOffset = delay;
  24551. }
  24552. else if (this._pausedDelay) {
  24553. this._localDelayOffset += delay - this._pausedDelay;
  24554. this._pausedDelay = null;
  24555. }
  24556. // Animating
  24557. var running = false;
  24558. var animations = this._animations;
  24559. var index;
  24560. for (index = 0; index < animations.length; index++) {
  24561. var animation = animations[index];
  24562. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  24563. running = running || isRunning;
  24564. }
  24565. this.animationStarted = running;
  24566. if (!running) {
  24567. // Remove from active animatables
  24568. index = this._scene._activeAnimatables.indexOf(this);
  24569. this._scene._activeAnimatables.splice(index, 1);
  24570. }
  24571. if (!running && this.onAnimationEnd) {
  24572. this.onAnimationEnd();
  24573. this.onAnimationEnd = null;
  24574. }
  24575. return running;
  24576. };
  24577. return Animatable;
  24578. })();
  24579. BABYLON.Animatable = Animatable;
  24580. })(BABYLON || (BABYLON = {}));
  24581. var BABYLON;
  24582. (function (BABYLON) {
  24583. var EasingFunction = (function () {
  24584. function EasingFunction() {
  24585. // Properties
  24586. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  24587. }
  24588. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  24589. get: function () {
  24590. return EasingFunction._EASINGMODE_EASEIN;
  24591. },
  24592. enumerable: true,
  24593. configurable: true
  24594. });
  24595. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  24596. get: function () {
  24597. return EasingFunction._EASINGMODE_EASEOUT;
  24598. },
  24599. enumerable: true,
  24600. configurable: true
  24601. });
  24602. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  24603. get: function () {
  24604. return EasingFunction._EASINGMODE_EASEINOUT;
  24605. },
  24606. enumerable: true,
  24607. configurable: true
  24608. });
  24609. EasingFunction.prototype.setEasingMode = function (easingMode) {
  24610. var n = Math.min(Math.max(easingMode, 0), 2);
  24611. this._easingMode = n;
  24612. };
  24613. EasingFunction.prototype.getEasingMode = function () {
  24614. return this._easingMode;
  24615. };
  24616. EasingFunction.prototype.easeInCore = function (gradient) {
  24617. throw new Error('You must implement this method');
  24618. };
  24619. EasingFunction.prototype.ease = function (gradient) {
  24620. switch (this._easingMode) {
  24621. case EasingFunction.EASINGMODE_EASEIN:
  24622. return this.easeInCore(gradient);
  24623. case EasingFunction.EASINGMODE_EASEOUT:
  24624. return (1 - this.easeInCore(1 - gradient));
  24625. }
  24626. if (gradient >= 0.5) {
  24627. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  24628. }
  24629. return (this.easeInCore(gradient * 2) * 0.5);
  24630. };
  24631. //Statics
  24632. EasingFunction._EASINGMODE_EASEIN = 0;
  24633. EasingFunction._EASINGMODE_EASEOUT = 1;
  24634. EasingFunction._EASINGMODE_EASEINOUT = 2;
  24635. return EasingFunction;
  24636. })();
  24637. BABYLON.EasingFunction = EasingFunction;
  24638. var CircleEase = (function (_super) {
  24639. __extends(CircleEase, _super);
  24640. function CircleEase() {
  24641. _super.apply(this, arguments);
  24642. }
  24643. CircleEase.prototype.easeInCore = function (gradient) {
  24644. gradient = Math.max(0, Math.min(1, gradient));
  24645. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  24646. };
  24647. return CircleEase;
  24648. })(EasingFunction);
  24649. BABYLON.CircleEase = CircleEase;
  24650. var BackEase = (function (_super) {
  24651. __extends(BackEase, _super);
  24652. function BackEase(amplitude) {
  24653. if (amplitude === void 0) { amplitude = 1; }
  24654. _super.call(this);
  24655. this.amplitude = amplitude;
  24656. }
  24657. BackEase.prototype.easeInCore = function (gradient) {
  24658. var num = Math.max(0, this.amplitude);
  24659. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  24660. };
  24661. return BackEase;
  24662. })(EasingFunction);
  24663. BABYLON.BackEase = BackEase;
  24664. var BounceEase = (function (_super) {
  24665. __extends(BounceEase, _super);
  24666. function BounceEase(bounces, bounciness) {
  24667. if (bounces === void 0) { bounces = 3; }
  24668. if (bounciness === void 0) { bounciness = 2; }
  24669. _super.call(this);
  24670. this.bounces = bounces;
  24671. this.bounciness = bounciness;
  24672. }
  24673. BounceEase.prototype.easeInCore = function (gradient) {
  24674. var y = Math.max(0.0, this.bounces);
  24675. var bounciness = this.bounciness;
  24676. if (bounciness <= 1.0) {
  24677. bounciness = 1.001;
  24678. }
  24679. var num9 = Math.pow(bounciness, y);
  24680. var num5 = 1.0 - bounciness;
  24681. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  24682. var num15 = gradient * num4;
  24683. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  24684. var num3 = Math.floor(num65);
  24685. var num13 = num3 + 1.0;
  24686. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  24687. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  24688. var num7 = (num8 + num12) * 0.5;
  24689. var num6 = gradient - num7;
  24690. var num2 = num7 - num8;
  24691. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  24692. };
  24693. return BounceEase;
  24694. })(EasingFunction);
  24695. BABYLON.BounceEase = BounceEase;
  24696. var CubicEase = (function (_super) {
  24697. __extends(CubicEase, _super);
  24698. function CubicEase() {
  24699. _super.apply(this, arguments);
  24700. }
  24701. CubicEase.prototype.easeInCore = function (gradient) {
  24702. return (gradient * gradient * gradient);
  24703. };
  24704. return CubicEase;
  24705. })(EasingFunction);
  24706. BABYLON.CubicEase = CubicEase;
  24707. var ElasticEase = (function (_super) {
  24708. __extends(ElasticEase, _super);
  24709. function ElasticEase(oscillations, springiness) {
  24710. if (oscillations === void 0) { oscillations = 3; }
  24711. if (springiness === void 0) { springiness = 3; }
  24712. _super.call(this);
  24713. this.oscillations = oscillations;
  24714. this.springiness = springiness;
  24715. }
  24716. ElasticEase.prototype.easeInCore = function (gradient) {
  24717. var num2;
  24718. var num3 = Math.max(0.0, this.oscillations);
  24719. var num = Math.max(0.0, this.springiness);
  24720. if (num == 0) {
  24721. num2 = gradient;
  24722. }
  24723. else {
  24724. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  24725. }
  24726. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  24727. };
  24728. return ElasticEase;
  24729. })(EasingFunction);
  24730. BABYLON.ElasticEase = ElasticEase;
  24731. var ExponentialEase = (function (_super) {
  24732. __extends(ExponentialEase, _super);
  24733. function ExponentialEase(exponent) {
  24734. if (exponent === void 0) { exponent = 2; }
  24735. _super.call(this);
  24736. this.exponent = exponent;
  24737. }
  24738. ExponentialEase.prototype.easeInCore = function (gradient) {
  24739. if (this.exponent <= 0) {
  24740. return gradient;
  24741. }
  24742. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  24743. };
  24744. return ExponentialEase;
  24745. })(EasingFunction);
  24746. BABYLON.ExponentialEase = ExponentialEase;
  24747. var PowerEase = (function (_super) {
  24748. __extends(PowerEase, _super);
  24749. function PowerEase(power) {
  24750. if (power === void 0) { power = 2; }
  24751. _super.call(this);
  24752. this.power = power;
  24753. }
  24754. PowerEase.prototype.easeInCore = function (gradient) {
  24755. var y = Math.max(0.0, this.power);
  24756. return Math.pow(gradient, y);
  24757. };
  24758. return PowerEase;
  24759. })(EasingFunction);
  24760. BABYLON.PowerEase = PowerEase;
  24761. var QuadraticEase = (function (_super) {
  24762. __extends(QuadraticEase, _super);
  24763. function QuadraticEase() {
  24764. _super.apply(this, arguments);
  24765. }
  24766. QuadraticEase.prototype.easeInCore = function (gradient) {
  24767. return (gradient * gradient);
  24768. };
  24769. return QuadraticEase;
  24770. })(EasingFunction);
  24771. BABYLON.QuadraticEase = QuadraticEase;
  24772. var QuarticEase = (function (_super) {
  24773. __extends(QuarticEase, _super);
  24774. function QuarticEase() {
  24775. _super.apply(this, arguments);
  24776. }
  24777. QuarticEase.prototype.easeInCore = function (gradient) {
  24778. return (gradient * gradient * gradient * gradient);
  24779. };
  24780. return QuarticEase;
  24781. })(EasingFunction);
  24782. BABYLON.QuarticEase = QuarticEase;
  24783. var QuinticEase = (function (_super) {
  24784. __extends(QuinticEase, _super);
  24785. function QuinticEase() {
  24786. _super.apply(this, arguments);
  24787. }
  24788. QuinticEase.prototype.easeInCore = function (gradient) {
  24789. return (gradient * gradient * gradient * gradient * gradient);
  24790. };
  24791. return QuinticEase;
  24792. })(EasingFunction);
  24793. BABYLON.QuinticEase = QuinticEase;
  24794. var SineEase = (function (_super) {
  24795. __extends(SineEase, _super);
  24796. function SineEase() {
  24797. _super.apply(this, arguments);
  24798. }
  24799. SineEase.prototype.easeInCore = function (gradient) {
  24800. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  24801. };
  24802. return SineEase;
  24803. })(EasingFunction);
  24804. BABYLON.SineEase = SineEase;
  24805. var BezierCurveEase = (function (_super) {
  24806. __extends(BezierCurveEase, _super);
  24807. function BezierCurveEase(x1, y1, x2, y2) {
  24808. if (x1 === void 0) { x1 = 0; }
  24809. if (y1 === void 0) { y1 = 0; }
  24810. if (x2 === void 0) { x2 = 1; }
  24811. if (y2 === void 0) { y2 = 1; }
  24812. _super.call(this);
  24813. this.x1 = x1;
  24814. this.y1 = y1;
  24815. this.x2 = x2;
  24816. this.y2 = y2;
  24817. }
  24818. BezierCurveEase.prototype.easeInCore = function (gradient) {
  24819. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  24820. };
  24821. return BezierCurveEase;
  24822. })(EasingFunction);
  24823. BABYLON.BezierCurveEase = BezierCurveEase;
  24824. })(BABYLON || (BABYLON = {}));
  24825. var BABYLON;
  24826. (function (BABYLON) {
  24827. var Bone = (function (_super) {
  24828. __extends(Bone, _super);
  24829. function Bone(name, skeleton, parentBone, matrix, restPose) {
  24830. _super.call(this, name, skeleton.getScene());
  24831. this.name = name;
  24832. this.children = new Array();
  24833. this.animations = new Array();
  24834. this._worldTransform = new BABYLON.Matrix();
  24835. this._absoluteTransform = new BABYLON.Matrix();
  24836. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  24837. this._skeleton = skeleton;
  24838. this._matrix = matrix;
  24839. this._baseMatrix = matrix;
  24840. this._restPose = restPose ? restPose : matrix.clone();
  24841. skeleton.bones.push(this);
  24842. if (parentBone) {
  24843. this._parent = parentBone;
  24844. parentBone.children.push(this);
  24845. }
  24846. else {
  24847. this._parent = null;
  24848. }
  24849. this._updateDifferenceMatrix();
  24850. }
  24851. // Members
  24852. Bone.prototype.getParent = function () {
  24853. return this._parent;
  24854. };
  24855. Bone.prototype.getLocalMatrix = function () {
  24856. return this._matrix;
  24857. };
  24858. Bone.prototype.getBaseMatrix = function () {
  24859. return this._baseMatrix;
  24860. };
  24861. Bone.prototype.getRestPose = function () {
  24862. return this._restPose;
  24863. };
  24864. Bone.prototype.returnToRest = function () {
  24865. this.updateMatrix(this._restPose.clone());
  24866. };
  24867. Bone.prototype.getWorldMatrix = function () {
  24868. return this._worldTransform;
  24869. };
  24870. Bone.prototype.getInvertedAbsoluteTransform = function () {
  24871. return this._invertedAbsoluteTransform;
  24872. };
  24873. Bone.prototype.getAbsoluteTransform = function () {
  24874. return this._absoluteTransform;
  24875. };
  24876. // Methods
  24877. Bone.prototype.updateMatrix = function (matrix) {
  24878. this._baseMatrix = matrix.clone();
  24879. this._matrix = matrix.clone();
  24880. this._skeleton._markAsDirty();
  24881. this._updateDifferenceMatrix();
  24882. };
  24883. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  24884. if (!rootMatrix) {
  24885. rootMatrix = this._baseMatrix;
  24886. }
  24887. if (this._parent) {
  24888. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  24889. }
  24890. else {
  24891. this._absoluteTransform.copyFrom(rootMatrix);
  24892. }
  24893. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  24894. for (var index = 0; index < this.children.length; index++) {
  24895. this.children[index]._updateDifferenceMatrix();
  24896. }
  24897. };
  24898. Bone.prototype.markAsDirty = function () {
  24899. this._currentRenderId++;
  24900. this._skeleton._markAsDirty();
  24901. };
  24902. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  24903. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  24904. // all animation may be coming from a library skeleton, so may need to create animation
  24905. if (this.animations.length === 0) {
  24906. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  24907. this.animations[0].setKeys([]);
  24908. }
  24909. // get animation info / verify there is such a range from the source bone
  24910. var sourceRange = source.animations[0].getRange(rangeName);
  24911. if (!sourceRange) {
  24912. return false;
  24913. }
  24914. var from = sourceRange.from;
  24915. var to = sourceRange.to;
  24916. var sourceKeys = source.animations[0].getKeys();
  24917. // rescaling prep
  24918. var sourceBoneLength = source.length;
  24919. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  24920. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  24921. var destKeys = this.animations[0].getKeys();
  24922. // loop vars declaration / initialization
  24923. var orig;
  24924. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  24925. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  24926. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  24927. var mat;
  24928. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  24929. orig = sourceKeys[key];
  24930. if (orig.frame >= from && orig.frame <= to) {
  24931. if (scalingReqd) {
  24932. orig.value.decompose(origScale, origRotation, origTranslation);
  24933. origTranslation.scaleInPlace(ratio);
  24934. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  24935. }
  24936. else {
  24937. mat = orig.value;
  24938. }
  24939. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  24940. }
  24941. }
  24942. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  24943. return true;
  24944. };
  24945. return Bone;
  24946. })(BABYLON.Node);
  24947. BABYLON.Bone = Bone;
  24948. })(BABYLON || (BABYLON = {}));
  24949. var BABYLON;
  24950. (function (BABYLON) {
  24951. var Skeleton = (function () {
  24952. function Skeleton(name, id, scene) {
  24953. this.name = name;
  24954. this.id = id;
  24955. this.bones = new Array();
  24956. this.needInitialSkinMatrix = false;
  24957. this._isDirty = true;
  24958. this._meshesWithPoseMatrix = new Array();
  24959. this._identity = BABYLON.Matrix.Identity();
  24960. this._ranges = {};
  24961. this.bones = [];
  24962. this._scene = scene;
  24963. scene.skeletons.push(this);
  24964. //make sure it will recalculate the matrix next time prepare is called.
  24965. this._isDirty = true;
  24966. }
  24967. // Members
  24968. Skeleton.prototype.getTransformMatrices = function (mesh) {
  24969. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  24970. return mesh._bonesTransformMatrices;
  24971. }
  24972. return this._transformMatrices;
  24973. };
  24974. Skeleton.prototype.getScene = function () {
  24975. return this._scene;
  24976. };
  24977. // Methods
  24978. /**
  24979. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24980. */
  24981. Skeleton.prototype.toString = function (fullDetails) {
  24982. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  24983. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  24984. if (fullDetails) {
  24985. ret += ", Ranges: {";
  24986. var first = true;
  24987. for (var name in this._ranges) {
  24988. if (!first) {
  24989. ret + ", ";
  24990. first = false;
  24991. }
  24992. ret += name;
  24993. }
  24994. ret += "}";
  24995. }
  24996. return ret;
  24997. };
  24998. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  24999. // check name not already in use
  25000. if (!this._ranges[name]) {
  25001. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  25002. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  25003. if (this.bones[i].animations[0]) {
  25004. this.bones[i].animations[0].createRange(name, from, to);
  25005. }
  25006. }
  25007. }
  25008. };
  25009. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  25010. if (deleteFrames === void 0) { deleteFrames = true; }
  25011. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  25012. if (this.bones[i].animations[0]) {
  25013. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  25014. }
  25015. }
  25016. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25017. };
  25018. Skeleton.prototype.getAnimationRange = function (name) {
  25019. return this._ranges[name];
  25020. };
  25021. /**
  25022. * Returns as an Array, all AnimationRanges defined on this skeleton
  25023. */
  25024. Skeleton.prototype.getAnimationRanges = function () {
  25025. var animationRanges = [];
  25026. var name;
  25027. var i = 0;
  25028. for (name in this._ranges) {
  25029. animationRanges[i] = this._ranges[name];
  25030. i++;
  25031. }
  25032. return animationRanges;
  25033. };
  25034. /**
  25035. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  25036. */
  25037. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  25038. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  25039. if (this._ranges[name] || !source.getAnimationRange(name)) {
  25040. return false;
  25041. }
  25042. var ret = true;
  25043. var frameOffset = this._getHighestAnimationFrame() + 1;
  25044. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  25045. var boneDict = {};
  25046. var sourceBones = source.bones;
  25047. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  25048. boneDict[sourceBones[i].name] = sourceBones[i];
  25049. }
  25050. if (this.bones.length !== sourceBones.length) {
  25051. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  25052. ret = false;
  25053. }
  25054. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  25055. var boneName = this.bones[i].name;
  25056. var sourceBone = boneDict[boneName];
  25057. if (sourceBone) {
  25058. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  25059. }
  25060. else {
  25061. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  25062. ret = false;
  25063. }
  25064. }
  25065. // do not call createAnimationRange(), since it also is done to bones, which was already done
  25066. var range = source.getAnimationRange(name);
  25067. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  25068. return ret;
  25069. };
  25070. Skeleton.prototype.returnToRest = function () {
  25071. for (var index = 0; index < this.bones.length; index++) {
  25072. this.bones[index].returnToRest();
  25073. }
  25074. };
  25075. Skeleton.prototype._getHighestAnimationFrame = function () {
  25076. var ret = 0;
  25077. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  25078. if (this.bones[i].animations[0]) {
  25079. var highest = this.bones[i].animations[0].getHighestFrame();
  25080. if (ret < highest) {
  25081. ret = highest;
  25082. }
  25083. }
  25084. }
  25085. return ret;
  25086. };
  25087. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  25088. var range = this.getAnimationRange(name);
  25089. if (!range) {
  25090. return null;
  25091. }
  25092. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  25093. };
  25094. Skeleton.prototype._markAsDirty = function () {
  25095. this._isDirty = true;
  25096. };
  25097. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  25098. this._meshesWithPoseMatrix.push(mesh);
  25099. };
  25100. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  25101. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  25102. if (index > -1) {
  25103. this._meshesWithPoseMatrix.splice(index, 1);
  25104. }
  25105. };
  25106. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  25107. for (var index = 0; index < this.bones.length; index++) {
  25108. var bone = this.bones[index];
  25109. var parentBone = bone.getParent();
  25110. if (parentBone) {
  25111. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  25112. }
  25113. else {
  25114. if (initialSkinMatrix) {
  25115. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  25116. }
  25117. else {
  25118. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  25119. }
  25120. }
  25121. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  25122. }
  25123. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  25124. };
  25125. Skeleton.prototype.prepare = function () {
  25126. if (!this._isDirty) {
  25127. return;
  25128. }
  25129. if (this.needInitialSkinMatrix) {
  25130. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  25131. var mesh = this._meshesWithPoseMatrix[index];
  25132. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  25133. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  25134. }
  25135. var poseMatrix = mesh.getPoseMatrix();
  25136. // Prepare bones
  25137. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  25138. var bone = this.bones[boneIndex];
  25139. if (!bone.getParent()) {
  25140. var matrix = bone.getBaseMatrix();
  25141. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  25142. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  25143. }
  25144. }
  25145. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  25146. }
  25147. }
  25148. else {
  25149. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  25150. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  25151. }
  25152. this._computeTransformMatrices(this._transformMatrices, null);
  25153. }
  25154. this._isDirty = false;
  25155. this._scene._activeBones += this.bones.length;
  25156. };
  25157. Skeleton.prototype.getAnimatables = function () {
  25158. if (!this._animatables || this._animatables.length !== this.bones.length) {
  25159. this._animatables = [];
  25160. for (var index = 0; index < this.bones.length; index++) {
  25161. this._animatables.push(this.bones[index]);
  25162. }
  25163. }
  25164. return this._animatables;
  25165. };
  25166. Skeleton.prototype.clone = function (name, id) {
  25167. var result = new Skeleton(name, id || name, this._scene);
  25168. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25169. for (var index = 0; index < this.bones.length; index++) {
  25170. var source = this.bones[index];
  25171. var parentBone = null;
  25172. if (source.getParent()) {
  25173. var parentIndex = this.bones.indexOf(source.getParent());
  25174. parentBone = result.bones[parentIndex];
  25175. }
  25176. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  25177. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  25178. }
  25179. if (this._ranges) {
  25180. result._ranges = {};
  25181. for (var rangeName in this._ranges) {
  25182. result._ranges[rangeName] = this._ranges[rangeName].clone();
  25183. }
  25184. }
  25185. this._isDirty = true;
  25186. return result;
  25187. };
  25188. Skeleton.prototype.dispose = function () {
  25189. this._meshesWithPoseMatrix = [];
  25190. // Animations
  25191. this.getScene().stopAnimation(this);
  25192. // Remove from scene
  25193. this.getScene().removeSkeleton(this);
  25194. };
  25195. Skeleton.prototype.serialize = function () {
  25196. var serializationObject = {};
  25197. serializationObject.name = this.name;
  25198. serializationObject.id = this.id;
  25199. serializationObject.bones = [];
  25200. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25201. for (var index = 0; index < this.bones.length; index++) {
  25202. var bone = this.bones[index];
  25203. var serializedBone = {
  25204. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  25205. name: bone.name,
  25206. matrix: bone.getLocalMatrix().toArray(),
  25207. rest: bone.getRestPose().toArray()
  25208. };
  25209. serializationObject.bones.push(serializedBone);
  25210. if (bone.length) {
  25211. serializedBone.length = bone.length;
  25212. }
  25213. if (bone.animations && bone.animations.length > 0) {
  25214. serializedBone.animation = bone.animations[0].serialize();
  25215. }
  25216. serializationObject.ranges = [];
  25217. for (var name in this._ranges) {
  25218. var range = {};
  25219. range.name = name;
  25220. range.from = this._ranges[name].from;
  25221. range.to = this._ranges[name].to;
  25222. serializationObject.ranges.push(range);
  25223. }
  25224. }
  25225. return serializationObject;
  25226. };
  25227. Skeleton.Parse = function (parsedSkeleton, scene) {
  25228. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  25229. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  25230. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  25231. var parsedBone = parsedSkeleton.bones[index];
  25232. var parentBone = null;
  25233. if (parsedBone.parentBoneIndex > -1) {
  25234. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  25235. }
  25236. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  25237. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  25238. if (parsedBone.length) {
  25239. bone.length = parsedBone.length;
  25240. }
  25241. if (parsedBone.animation) {
  25242. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  25243. }
  25244. }
  25245. // placed after bones, so createAnimationRange can cascade down
  25246. if (parsedSkeleton.ranges) {
  25247. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  25248. var data = parsedSkeleton.ranges[index];
  25249. skeleton.createAnimationRange(data.name, data.from, data.to);
  25250. }
  25251. }
  25252. return skeleton;
  25253. };
  25254. return Skeleton;
  25255. })();
  25256. BABYLON.Skeleton = Skeleton;
  25257. })(BABYLON || (BABYLON = {}));
  25258. var BABYLON;
  25259. (function (BABYLON) {
  25260. var PostProcess = (function () {
  25261. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  25262. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  25263. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25264. this.name = name;
  25265. this.width = -1;
  25266. this.height = -1;
  25267. this._reusable = false;
  25268. this._textures = new BABYLON.SmartArray(2);
  25269. this._currentRenderTextureInd = 0;
  25270. if (camera != null) {
  25271. this._camera = camera;
  25272. this._scene = camera.getScene();
  25273. camera.attachPostProcess(this);
  25274. this._engine = this._scene.getEngine();
  25275. }
  25276. else {
  25277. this._engine = engine;
  25278. }
  25279. this._renderRatio = ratio;
  25280. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  25281. this._reusable = reusable || false;
  25282. this._textureType = textureType;
  25283. this._samplers = samplers || [];
  25284. this._samplers.push("textureSampler");
  25285. this._fragmentUrl = fragmentUrl;
  25286. this._parameters = parameters || [];
  25287. this.updateEffect(defines);
  25288. }
  25289. PostProcess.prototype.updateEffect = function (defines) {
  25290. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  25291. };
  25292. PostProcess.prototype.isReusable = function () {
  25293. return this._reusable;
  25294. };
  25295. PostProcess.prototype.activate = function (camera, sourceTexture) {
  25296. camera = camera || this._camera;
  25297. var scene = camera.getScene();
  25298. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  25299. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  25300. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  25301. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  25302. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  25303. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  25304. if (this._textures.length > 0) {
  25305. for (var i = 0; i < this._textures.length; i++) {
  25306. this._engine._releaseTexture(this._textures.data[i]);
  25307. }
  25308. this._textures.reset();
  25309. }
  25310. this.width = desiredWidth;
  25311. this.height = desiredHeight;
  25312. 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 }));
  25313. if (this._reusable) {
  25314. 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 }));
  25315. }
  25316. if (this.onSizeChanged) {
  25317. this.onSizeChanged();
  25318. }
  25319. }
  25320. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  25321. if (this.onActivate) {
  25322. this.onActivate(camera);
  25323. }
  25324. // Clear
  25325. if (this.clearColor) {
  25326. this._engine.clear(this.clearColor, true, true);
  25327. }
  25328. else {
  25329. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  25330. }
  25331. if (this._reusable) {
  25332. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  25333. }
  25334. };
  25335. Object.defineProperty(PostProcess.prototype, "isSupported", {
  25336. get: function () {
  25337. return this._effect.isSupported;
  25338. },
  25339. enumerable: true,
  25340. configurable: true
  25341. });
  25342. PostProcess.prototype.apply = function () {
  25343. // Check
  25344. if (!this._effect.isReady())
  25345. return null;
  25346. // States
  25347. this._engine.enableEffect(this._effect);
  25348. this._engine.setState(false);
  25349. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25350. this._engine.setDepthBuffer(false);
  25351. this._engine.setDepthWrite(false);
  25352. // Texture
  25353. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  25354. // Parameters
  25355. if (this.onApply) {
  25356. this.onApply(this._effect);
  25357. }
  25358. return this._effect;
  25359. };
  25360. PostProcess.prototype.dispose = function (camera) {
  25361. camera = camera || this._camera;
  25362. if (this._textures.length > 0) {
  25363. for (var i = 0; i < this._textures.length; i++) {
  25364. this._engine._releaseTexture(this._textures.data[i]);
  25365. }
  25366. this._textures.reset();
  25367. }
  25368. if (!camera) {
  25369. return;
  25370. }
  25371. camera.detachPostProcess(this);
  25372. var index = camera._postProcesses.indexOf(this);
  25373. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  25374. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  25375. }
  25376. };
  25377. return PostProcess;
  25378. })();
  25379. BABYLON.PostProcess = PostProcess;
  25380. })(BABYLON || (BABYLON = {}));
  25381. var BABYLON;
  25382. (function (BABYLON) {
  25383. var PostProcessManager = (function () {
  25384. function PostProcessManager(scene) {
  25385. this._vertexDeclaration = [2];
  25386. this._vertexStrideSize = 2 * 4;
  25387. this._scene = scene;
  25388. }
  25389. PostProcessManager.prototype._prepareBuffers = function () {
  25390. if (this._vertexBuffer) {
  25391. return;
  25392. }
  25393. // VBO
  25394. var vertices = [];
  25395. vertices.push(1, 1);
  25396. vertices.push(-1, 1);
  25397. vertices.push(-1, -1);
  25398. vertices.push(1, -1);
  25399. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  25400. // Indices
  25401. var indices = [];
  25402. indices.push(0);
  25403. indices.push(1);
  25404. indices.push(2);
  25405. indices.push(0);
  25406. indices.push(2);
  25407. indices.push(3);
  25408. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  25409. };
  25410. // Methods
  25411. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  25412. var postProcesses = this._scene.activeCamera._postProcesses;
  25413. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  25414. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  25415. return false;
  25416. }
  25417. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  25418. return true;
  25419. };
  25420. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  25421. var engine = this._scene.getEngine();
  25422. for (var index = 0; index < postProcesses.length; index++) {
  25423. if (index < postProcesses.length - 1) {
  25424. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  25425. }
  25426. else {
  25427. if (targetTexture) {
  25428. engine.bindFramebuffer(targetTexture);
  25429. }
  25430. else {
  25431. engine.restoreDefaultFramebuffer();
  25432. }
  25433. }
  25434. var pp = postProcesses[index];
  25435. var effect = pp.apply();
  25436. if (effect) {
  25437. if (pp.onBeforeRender) {
  25438. pp.onBeforeRender(effect);
  25439. }
  25440. // VBOs
  25441. this._prepareBuffers();
  25442. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25443. // Draw order
  25444. engine.draw(true, 0, 6);
  25445. if (pp.onAfterRender) {
  25446. pp.onAfterRender(effect);
  25447. }
  25448. }
  25449. }
  25450. // Restore depth buffer
  25451. engine.setDepthBuffer(true);
  25452. engine.setDepthWrite(true);
  25453. };
  25454. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  25455. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  25456. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  25457. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  25458. return;
  25459. }
  25460. var engine = this._scene.getEngine();
  25461. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  25462. if (index < postProcessesTakenIndices.length - 1) {
  25463. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  25464. }
  25465. else {
  25466. if (targetTexture) {
  25467. engine.bindFramebuffer(targetTexture, faceIndex);
  25468. }
  25469. else {
  25470. engine.restoreDefaultFramebuffer();
  25471. }
  25472. }
  25473. if (doNotPresent) {
  25474. break;
  25475. }
  25476. var pp = postProcesses[postProcessesTakenIndices[index]];
  25477. var effect = pp.apply();
  25478. if (effect) {
  25479. if (pp.onBeforeRender) {
  25480. pp.onBeforeRender(effect);
  25481. }
  25482. // VBOs
  25483. this._prepareBuffers();
  25484. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25485. // Draw order
  25486. engine.draw(true, 0, 6);
  25487. if (pp.onAfterRender) {
  25488. pp.onAfterRender(effect);
  25489. }
  25490. }
  25491. }
  25492. // Restore depth buffer
  25493. engine.setDepthBuffer(true);
  25494. engine.setDepthWrite(true);
  25495. };
  25496. PostProcessManager.prototype.dispose = function () {
  25497. if (this._vertexBuffer) {
  25498. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25499. this._vertexBuffer = null;
  25500. }
  25501. if (this._indexBuffer) {
  25502. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25503. this._indexBuffer = null;
  25504. }
  25505. };
  25506. return PostProcessManager;
  25507. })();
  25508. BABYLON.PostProcessManager = PostProcessManager;
  25509. })(BABYLON || (BABYLON = {}));
  25510. var BABYLON;
  25511. (function (BABYLON) {
  25512. var PassPostProcess = (function (_super) {
  25513. __extends(PassPostProcess, _super);
  25514. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25515. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  25516. }
  25517. return PassPostProcess;
  25518. })(BABYLON.PostProcess);
  25519. BABYLON.PassPostProcess = PassPostProcess;
  25520. })(BABYLON || (BABYLON = {}));
  25521. var BABYLON;
  25522. (function (BABYLON) {
  25523. /**
  25524. * This is a holder class for the physics joint created by the physics plugin.
  25525. * It holds a set of functions to control the underlying joint.
  25526. */
  25527. var PhysicsJoint = (function () {
  25528. function PhysicsJoint(type, jointData) {
  25529. this.type = type;
  25530. this.jointData = jointData;
  25531. jointData.nativeParams = jointData.nativeParams || {};
  25532. }
  25533. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  25534. get: function () {
  25535. return this._physicsJoint;
  25536. },
  25537. set: function (newJoint) {
  25538. if (this._physicsJoint) {
  25539. }
  25540. this._physicsJoint = newJoint;
  25541. },
  25542. enumerable: true,
  25543. configurable: true
  25544. });
  25545. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  25546. set: function (physicsPlugin) {
  25547. this._physicsPlugin = physicsPlugin;
  25548. },
  25549. enumerable: true,
  25550. configurable: true
  25551. });
  25552. /**
  25553. * Execute a function that is physics-plugin specific.
  25554. * @param {Function} func the function that will be executed.
  25555. * It accepts two parameters: the physics world and the physics joint.
  25556. */
  25557. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  25558. func(this._physicsPlugin.world, this._physicsJoint);
  25559. };
  25560. //TODO check if the native joints are the same
  25561. //Joint Types
  25562. PhysicsJoint.DistanceJoint = 0;
  25563. PhysicsJoint.HingeJoint = 1;
  25564. PhysicsJoint.BallAndSocketJoint = 2;
  25565. PhysicsJoint.WheelJoint = 3;
  25566. PhysicsJoint.SliderJoint = 4;
  25567. //OIMO
  25568. PhysicsJoint.PrismaticJoint = 5;
  25569. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  25570. PhysicsJoint.UniversalJoint = 6;
  25571. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  25572. //Cannon
  25573. //Similar to a Ball-Joint. Different in params
  25574. //TODO check!!
  25575. PhysicsJoint.PointToPointJoint = 8;
  25576. //Cannon only at the moment
  25577. PhysicsJoint.SpringJoint = 9;
  25578. return PhysicsJoint;
  25579. })();
  25580. BABYLON.PhysicsJoint = PhysicsJoint;
  25581. /**
  25582. * A class representing a physics distance joint.
  25583. */
  25584. var DistanceJoint = (function (_super) {
  25585. __extends(DistanceJoint, _super);
  25586. function DistanceJoint(jointData) {
  25587. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  25588. }
  25589. /**
  25590. * Update the predefined distance.
  25591. */
  25592. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  25593. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  25594. };
  25595. return DistanceJoint;
  25596. })(PhysicsJoint);
  25597. BABYLON.DistanceJoint = DistanceJoint;
  25598. /**
  25599. * This class represents a single hinge physics joint
  25600. */
  25601. var HingeJoint = (function (_super) {
  25602. __extends(HingeJoint, _super);
  25603. function HingeJoint(jointData) {
  25604. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  25605. }
  25606. /**
  25607. * Set the motor values.
  25608. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25609. * @param {number} force the force to apply
  25610. * @param {number} maxForce max force for this motor.
  25611. */
  25612. HingeJoint.prototype.setMotor = function (force, maxForce) {
  25613. this._physicsPlugin.setMotor(this, force, maxForce);
  25614. };
  25615. /**
  25616. * Set the motor's limits.
  25617. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25618. */
  25619. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  25620. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  25621. };
  25622. return HingeJoint;
  25623. })(PhysicsJoint);
  25624. BABYLON.HingeJoint = HingeJoint;
  25625. /**
  25626. * This class represents a dual hinge physics joint (same as wheel joint)
  25627. */
  25628. var Hinge2Joint = (function (_super) {
  25629. __extends(Hinge2Joint, _super);
  25630. function Hinge2Joint(jointData) {
  25631. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  25632. }
  25633. /**
  25634. * Set the motor values.
  25635. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25636. * @param {number} force the force to apply
  25637. * @param {number} maxForce max force for this motor.
  25638. * @param {motorIndex} the motor's index, 0 or 1.
  25639. */
  25640. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  25641. if (motorIndex === void 0) { motorIndex = 0; }
  25642. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  25643. };
  25644. /**
  25645. * Set the motor limits.
  25646. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25647. * @param {number} upperLimit the upper limit
  25648. * @param {number} lowerLimit lower limit
  25649. * @param {motorIndex} the motor's index, 0 or 1.
  25650. */
  25651. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  25652. if (motorIndex === void 0) { motorIndex = 0; }
  25653. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  25654. };
  25655. return Hinge2Joint;
  25656. })(PhysicsJoint);
  25657. BABYLON.Hinge2Joint = Hinge2Joint;
  25658. })(BABYLON || (BABYLON = {}));
  25659. var BABYLON;
  25660. (function (BABYLON) {
  25661. var PhysicsImpostor = (function () {
  25662. function PhysicsImpostor(_mesh, type, _options) {
  25663. var _this = this;
  25664. if (_options === void 0) { _options = { mass: 0 }; }
  25665. this._mesh = _mesh;
  25666. this.type = type;
  25667. this._options = _options;
  25668. this._bodyUpdateRequired = false;
  25669. this._onBeforePhysicsStepCallbacks = new Array();
  25670. this._onAfterPhysicsStepCallbacks = new Array();
  25671. this._onPhysicsCollideCallbacks = [];
  25672. this._deltaPosition = BABYLON.Vector3.Zero();
  25673. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  25674. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  25675. /**
  25676. * this function is executed by the physics engine.
  25677. */
  25678. this.beforeStep = function () {
  25679. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  25680. //conjugate deltaRotation
  25681. if (_this._deltaRotationConjugated) {
  25682. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  25683. }
  25684. else {
  25685. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  25686. }
  25687. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  25688. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  25689. func(_this);
  25690. });
  25691. };
  25692. /**
  25693. * this function is executed by the physics engine.
  25694. */
  25695. this.afterStep = function () {
  25696. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  25697. func(_this);
  25698. });
  25699. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  25700. _this.mesh.position.addInPlace(_this._deltaPosition);
  25701. if (_this._deltaRotation) {
  25702. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  25703. }
  25704. };
  25705. //event and body object due to cannon's event-based architecture.
  25706. this.onCollide = function (e) {
  25707. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  25708. if (otherImpostor) {
  25709. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  25710. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  25711. }).forEach(function (obj) {
  25712. obj.callback(_this, otherImpostor);
  25713. });
  25714. }
  25715. };
  25716. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  25717. if (!this._physicsEngine) {
  25718. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  25719. }
  25720. else {
  25721. //default options params
  25722. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  25723. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  25724. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  25725. this._joints = [];
  25726. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  25727. if (!this._mesh.parent) {
  25728. this._init();
  25729. }
  25730. }
  25731. }
  25732. /**
  25733. * This function will completly initialize this impostor.
  25734. * It will create a new body - but only if this mesh has no parent.
  25735. * If it has, this impostor will not be used other than to define the impostor
  25736. * of the child mesh.
  25737. */
  25738. PhysicsImpostor.prototype._init = function () {
  25739. this._physicsEngine.removeImpostor(this);
  25740. this.physicsBody = null;
  25741. this._parent = this._parent || this._getPhysicsParent();
  25742. if (!this.parent) {
  25743. this._physicsEngine.addImpostor(this);
  25744. }
  25745. };
  25746. PhysicsImpostor.prototype._getPhysicsParent = function () {
  25747. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  25748. var parentMesh = this.mesh.parent;
  25749. return parentMesh.getPhysicsImpostor();
  25750. }
  25751. return;
  25752. };
  25753. /**
  25754. * Should a new body be generated.
  25755. */
  25756. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  25757. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  25758. };
  25759. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  25760. this.forceUpdate();
  25761. };
  25762. /**
  25763. * Force a regeneration of this or the parent's impostor's body.
  25764. * Use under cautious - This will remove all joints already implemented.
  25765. */
  25766. PhysicsImpostor.prototype.forceUpdate = function () {
  25767. this._init();
  25768. if (this.parent) {
  25769. this.parent.forceUpdate();
  25770. }
  25771. };
  25772. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  25773. get: function () {
  25774. return this._mesh;
  25775. },
  25776. enumerable: true,
  25777. configurable: true
  25778. });
  25779. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  25780. /**
  25781. * Gets the body that holds this impostor. Either its own, or its parent.
  25782. */
  25783. get: function () {
  25784. return this._parent ? this._parent.physicsBody : this._physicsBody;
  25785. },
  25786. /**
  25787. * Set the physics body. Used mainly by the physics engine/plugin
  25788. */
  25789. set: function (physicsBody) {
  25790. if (this._physicsBody) {
  25791. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  25792. }
  25793. this._physicsBody = physicsBody;
  25794. this.resetUpdateFlags();
  25795. },
  25796. enumerable: true,
  25797. configurable: true
  25798. });
  25799. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  25800. get: function () {
  25801. return this._parent;
  25802. },
  25803. enumerable: true,
  25804. configurable: true
  25805. });
  25806. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  25807. this._bodyUpdateRequired = false;
  25808. };
  25809. /**
  25810. * Get a specific parametes from the options parameter.
  25811. */
  25812. PhysicsImpostor.prototype.getParam = function (paramName) {
  25813. return this._options[paramName];
  25814. };
  25815. /**
  25816. * Sets a specific parameter in the options given to the physics plugin
  25817. */
  25818. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  25819. this._options[paramName] = value;
  25820. this._bodyUpdateRequired = true;
  25821. };
  25822. /**
  25823. * Specifically change the body's mass option. Won't recreate the physics body object
  25824. */
  25825. PhysicsImpostor.prototype.setMass = function (mass) {
  25826. if (this.getParam("mass") !== mass) {
  25827. this.setParam("mass", mass);
  25828. }
  25829. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  25830. };
  25831. PhysicsImpostor.prototype.getLinearVelocity = function () {
  25832. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  25833. };
  25834. /**
  25835. * Set the body's linear velocity.
  25836. */
  25837. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  25838. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  25839. };
  25840. PhysicsImpostor.prototype.getAngularVelocity = function () {
  25841. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  25842. };
  25843. /**
  25844. * Set the body's linear velocity.
  25845. */
  25846. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  25847. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  25848. };
  25849. /**
  25850. * Execute a function with the physics plugin native code.
  25851. * Provide a function the will have two variables - the world object and the physics body object.
  25852. */
  25853. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  25854. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  25855. };
  25856. /**
  25857. * Register a function that will be executed before the physics world is stepping forward.
  25858. */
  25859. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  25860. this._onBeforePhysicsStepCallbacks.push(func);
  25861. };
  25862. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  25863. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  25864. if (index > -1) {
  25865. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  25866. }
  25867. else {
  25868. BABYLON.Tools.Warn("Function to remove was not found");
  25869. }
  25870. };
  25871. /**
  25872. * Register a function that will be executed after the physics step
  25873. */
  25874. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  25875. this._onAfterPhysicsStepCallbacks.push(func);
  25876. };
  25877. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  25878. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  25879. if (index > -1) {
  25880. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  25881. }
  25882. else {
  25883. BABYLON.Tools.Warn("Function to remove was not found");
  25884. }
  25885. };
  25886. /**
  25887. * register a function that will be executed when this impostor collides against a different body.
  25888. */
  25889. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  25890. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  25891. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  25892. };
  25893. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  25894. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  25895. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  25896. if (index > -1) {
  25897. this._onPhysicsCollideCallbacks.splice(index, 1);
  25898. }
  25899. else {
  25900. BABYLON.Tools.Warn("Function to remove was not found");
  25901. }
  25902. };
  25903. /**
  25904. * Apply a force
  25905. */
  25906. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  25907. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  25908. };
  25909. /**
  25910. * Apply an impulse
  25911. */
  25912. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  25913. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  25914. };
  25915. /**
  25916. * A help function to create a joint.
  25917. */
  25918. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  25919. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  25920. this.addJoint(otherImpostor, joint);
  25921. };
  25922. /**
  25923. * Add a joint to this impostor with a different impostor.
  25924. */
  25925. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  25926. this._joints.push({
  25927. otherImpostor: otherImpostor,
  25928. joint: joint
  25929. });
  25930. this._physicsEngine.addJoint(this, otherImpostor, joint);
  25931. };
  25932. /**
  25933. * Will keep this body still, in a sleep mode.
  25934. */
  25935. PhysicsImpostor.prototype.sleep = function () {
  25936. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  25937. };
  25938. /**
  25939. * Wake the body up.
  25940. */
  25941. PhysicsImpostor.prototype.wakeUp = function () {
  25942. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  25943. };
  25944. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  25945. if (disposeChildren === void 0) { disposeChildren = true; }
  25946. this.physicsBody = null;
  25947. if (this.parent) {
  25948. this.parent.forceUpdate();
  25949. }
  25950. else {
  25951. this.mesh.getChildMeshes().forEach(function (mesh) {
  25952. if (mesh.physicsImpostor) {
  25953. if (disposeChildren) {
  25954. mesh.physicsImpostor.dispose();
  25955. mesh.physicsImpostor = null;
  25956. }
  25957. }
  25958. });
  25959. }
  25960. };
  25961. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  25962. this._deltaPosition.copyFrom(position);
  25963. };
  25964. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  25965. if (!this._deltaRotation) {
  25966. this._deltaRotation = new BABYLON.Quaternion();
  25967. }
  25968. this._deltaRotation.copyFrom(rotation);
  25969. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  25970. };
  25971. //Impostor types
  25972. PhysicsImpostor.NoImpostor = 0;
  25973. PhysicsImpostor.SphereImpostor = 1;
  25974. PhysicsImpostor.BoxImpostor = 2;
  25975. PhysicsImpostor.PlaneImpostor = 3;
  25976. PhysicsImpostor.MeshImpostor = 4;
  25977. PhysicsImpostor.CapsuleImpostor = 5;
  25978. PhysicsImpostor.ConeImpostor = 6;
  25979. PhysicsImpostor.CylinderImpostor = 7;
  25980. PhysicsImpostor.ConvexHullImpostor = 8;
  25981. PhysicsImpostor.HeightmapImpostor = 9;
  25982. return PhysicsImpostor;
  25983. })();
  25984. BABYLON.PhysicsImpostor = PhysicsImpostor;
  25985. })(BABYLON || (BABYLON = {}));
  25986. var BABYLON;
  25987. (function (BABYLON) {
  25988. var PhysicsEngine = (function () {
  25989. function PhysicsEngine(gravity, _physicsPlugin) {
  25990. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  25991. this._physicsPlugin = _physicsPlugin;
  25992. //new methods and parameters
  25993. this._impostors = [];
  25994. this._joints = [];
  25995. if (!this._physicsPlugin.isSupported()) {
  25996. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  25997. + "Please make sure it is included.");
  25998. }
  25999. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  26000. this.setGravity(gravity);
  26001. this.setTimeStep();
  26002. }
  26003. PhysicsEngine.prototype.setGravity = function (gravity) {
  26004. this.gravity = gravity;
  26005. this._physicsPlugin.setGravity(this.gravity);
  26006. };
  26007. /**
  26008. * Set the time step of the physics engine.
  26009. * default is 1/60.
  26010. * To slow it down, enter 1/600 for example.
  26011. * To speed it up, 1/30
  26012. * @param {number} newTimeStep the new timestep to apply to this world.
  26013. */
  26014. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  26015. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  26016. this._physicsPlugin.setTimeStep(newTimeStep);
  26017. };
  26018. PhysicsEngine.prototype.dispose = function () {
  26019. this._impostors.forEach(function (impostor) {
  26020. impostor.dispose();
  26021. });
  26022. this._physicsPlugin.dispose();
  26023. };
  26024. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  26025. return this._physicsPlugin.name;
  26026. };
  26027. /**
  26028. * Adding a new impostor for the impostor tracking.
  26029. * This will be done by the impostor itself.
  26030. * @param {PhysicsImpostor} impostor the impostor to add
  26031. */
  26032. PhysicsEngine.prototype.addImpostor = function (impostor) {
  26033. this._impostors.push(impostor);
  26034. //if no parent, generate the body
  26035. if (!impostor.parent) {
  26036. this._physicsPlugin.generatePhysicsBody(impostor);
  26037. }
  26038. };
  26039. /**
  26040. * Remove an impostor from the engine.
  26041. * This impostor and its mesh will not longer be updated by the physics engine.
  26042. * @param {PhysicsImpostor} impostor the impostor to remove
  26043. */
  26044. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  26045. var index = this._impostors.indexOf(impostor);
  26046. if (index > -1) {
  26047. var removed = this._impostors.splice(index, 1);
  26048. //Is it needed?
  26049. if (removed.length) {
  26050. //this will also remove it from the world.
  26051. removed[0].physicsBody = null;
  26052. }
  26053. }
  26054. };
  26055. /**
  26056. * Add a joint to the physics engine
  26057. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  26058. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  26059. * @param {PhysicsJoint} the joint that will connect both impostors.
  26060. */
  26061. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  26062. var impostorJoint = {
  26063. mainImpostor: mainImpostor,
  26064. connectedImpostor: connectedImpostor,
  26065. joint: joint
  26066. };
  26067. joint.physicsPlugin = this._physicsPlugin;
  26068. this._joints.push(impostorJoint);
  26069. this._physicsPlugin.generateJoint(impostorJoint);
  26070. };
  26071. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  26072. var matchingJoints = this._joints.filter(function (impostorJoint) {
  26073. return (impostorJoint.connectedImpostor === connectedImpostor
  26074. && impostorJoint.joint === joint
  26075. && impostorJoint.mainImpostor === mainImpostor);
  26076. });
  26077. if (matchingJoints.length) {
  26078. this._physicsPlugin.removeJoint(matchingJoints[0]);
  26079. }
  26080. };
  26081. /**
  26082. * Called by the scene. no need to call it.
  26083. */
  26084. PhysicsEngine.prototype._step = function (delta) {
  26085. var _this = this;
  26086. //check if any mesh has no body / requires an update
  26087. this._impostors.forEach(function (impostor) {
  26088. if (impostor.isBodyInitRequired()) {
  26089. _this._physicsPlugin.generatePhysicsBody(impostor);
  26090. }
  26091. });
  26092. if (delta > 0.1) {
  26093. delta = 0.1;
  26094. }
  26095. else if (delta <= 0) {
  26096. delta = 1.0 / 60.0;
  26097. }
  26098. this._physicsPlugin.executeStep(delta, this._impostors);
  26099. };
  26100. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  26101. return this._physicsPlugin;
  26102. };
  26103. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  26104. for (var i = 0; i < this._impostors.length; ++i) {
  26105. if (this._impostors[i].physicsBody === body) {
  26106. return this._impostors[i];
  26107. }
  26108. }
  26109. };
  26110. // Statics, Legacy support.
  26111. /**
  26112. * @Deprecated
  26113. *
  26114. */
  26115. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  26116. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  26117. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  26118. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  26119. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  26120. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  26121. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  26122. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  26123. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  26124. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  26125. PhysicsEngine.Epsilon = 0.001;
  26126. return PhysicsEngine;
  26127. })();
  26128. BABYLON.PhysicsEngine = PhysicsEngine;
  26129. })(BABYLON || (BABYLON = {}));
  26130. var BABYLON;
  26131. (function (BABYLON) {
  26132. var VertexData = (function () {
  26133. function VertexData() {
  26134. }
  26135. VertexData.prototype.set = function (data, kind) {
  26136. switch (kind) {
  26137. case BABYLON.VertexBuffer.PositionKind:
  26138. this.positions = data;
  26139. break;
  26140. case BABYLON.VertexBuffer.NormalKind:
  26141. this.normals = data;
  26142. break;
  26143. case BABYLON.VertexBuffer.UVKind:
  26144. this.uvs = data;
  26145. break;
  26146. case BABYLON.VertexBuffer.UV2Kind:
  26147. this.uvs2 = data;
  26148. break;
  26149. case BABYLON.VertexBuffer.UV3Kind:
  26150. this.uvs3 = data;
  26151. break;
  26152. case BABYLON.VertexBuffer.UV4Kind:
  26153. this.uvs4 = data;
  26154. break;
  26155. case BABYLON.VertexBuffer.UV5Kind:
  26156. this.uvs5 = data;
  26157. break;
  26158. case BABYLON.VertexBuffer.UV6Kind:
  26159. this.uvs6 = data;
  26160. break;
  26161. case BABYLON.VertexBuffer.ColorKind:
  26162. this.colors = data;
  26163. break;
  26164. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26165. this.matricesIndices = data;
  26166. break;
  26167. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26168. this.matricesWeights = data;
  26169. break;
  26170. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26171. this.matricesIndicesExtra = data;
  26172. break;
  26173. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26174. this.matricesWeightsExtra = data;
  26175. break;
  26176. }
  26177. };
  26178. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26179. this._applyTo(mesh, updatable);
  26180. };
  26181. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26182. this._applyTo(geometry, updatable);
  26183. };
  26184. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26185. this._update(mesh);
  26186. };
  26187. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26188. this._update(geometry);
  26189. };
  26190. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26191. if (this.positions) {
  26192. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26193. }
  26194. if (this.normals) {
  26195. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26196. }
  26197. if (this.uvs) {
  26198. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26199. }
  26200. if (this.uvs2) {
  26201. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26202. }
  26203. if (this.uvs3) {
  26204. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26205. }
  26206. if (this.uvs4) {
  26207. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26208. }
  26209. if (this.uvs5) {
  26210. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26211. }
  26212. if (this.uvs6) {
  26213. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26214. }
  26215. if (this.colors) {
  26216. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26217. }
  26218. if (this.matricesIndices) {
  26219. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26220. }
  26221. if (this.matricesWeights) {
  26222. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26223. }
  26224. if (this.matricesIndicesExtra) {
  26225. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26226. }
  26227. if (this.matricesWeightsExtra) {
  26228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26229. }
  26230. if (this.indices) {
  26231. meshOrGeometry.setIndices(this.indices);
  26232. }
  26233. };
  26234. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26235. if (this.positions) {
  26236. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26237. }
  26238. if (this.normals) {
  26239. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26240. }
  26241. if (this.uvs) {
  26242. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26243. }
  26244. if (this.uvs2) {
  26245. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26246. }
  26247. if (this.uvs3) {
  26248. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26249. }
  26250. if (this.uvs4) {
  26251. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26252. }
  26253. if (this.uvs5) {
  26254. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26255. }
  26256. if (this.uvs6) {
  26257. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26258. }
  26259. if (this.colors) {
  26260. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26261. }
  26262. if (this.matricesIndices) {
  26263. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26264. }
  26265. if (this.matricesWeights) {
  26266. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26267. }
  26268. if (this.matricesIndicesExtra) {
  26269. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26270. }
  26271. if (this.matricesWeightsExtra) {
  26272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26273. }
  26274. if (this.indices) {
  26275. meshOrGeometry.setIndices(this.indices);
  26276. }
  26277. };
  26278. VertexData.prototype.transform = function (matrix) {
  26279. var transformed = BABYLON.Vector3.Zero();
  26280. var index;
  26281. if (this.positions) {
  26282. var position = BABYLON.Vector3.Zero();
  26283. for (index = 0; index < this.positions.length; index += 3) {
  26284. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26285. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26286. this.positions[index] = transformed.x;
  26287. this.positions[index + 1] = transformed.y;
  26288. this.positions[index + 2] = transformed.z;
  26289. }
  26290. }
  26291. if (this.normals) {
  26292. var normal = BABYLON.Vector3.Zero();
  26293. for (index = 0; index < this.normals.length; index += 3) {
  26294. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26295. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26296. this.normals[index] = transformed.x;
  26297. this.normals[index + 1] = transformed.y;
  26298. this.normals[index + 2] = transformed.z;
  26299. }
  26300. }
  26301. };
  26302. VertexData.prototype.merge = function (other) {
  26303. if (other.indices) {
  26304. if (!this.indices) {
  26305. this.indices = [];
  26306. }
  26307. var offset = this.positions ? this.positions.length / 3 : 0;
  26308. for (var index = 0; index < other.indices.length; index++) {
  26309. //TODO check type - if Int32Array!
  26310. this.indices.push(other.indices[index] + offset);
  26311. }
  26312. }
  26313. this.positions = this._mergeElement(this.positions, other.positions);
  26314. this.normals = this._mergeElement(this.normals, other.normals);
  26315. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26316. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26317. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26318. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26319. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26320. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26321. this.colors = this._mergeElement(this.colors, other.colors);
  26322. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26323. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26324. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26325. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26326. };
  26327. VertexData.prototype._mergeElement = function (source, other) {
  26328. if (!other)
  26329. return source;
  26330. if (!source)
  26331. return other;
  26332. var len = other.length + source.length;
  26333. var isSrcTypedArray = source instanceof Float32Array;
  26334. var isOthTypedArray = other instanceof Float32Array;
  26335. // use non-loop method when the source is Float32Array
  26336. if (isSrcTypedArray) {
  26337. var ret32 = new Float32Array(len);
  26338. ret32.set(source);
  26339. ret32.set(other, source.length);
  26340. return ret32;
  26341. }
  26342. else if (!isOthTypedArray) {
  26343. return source.concat(other);
  26344. }
  26345. else {
  26346. var ret = source.slice(0); // copy source to a separate array
  26347. for (var i = 0, len = other.length; i < len; i++) {
  26348. ret.push(other[i]);
  26349. }
  26350. return ret;
  26351. }
  26352. };
  26353. VertexData.prototype.serialize = function () {
  26354. var serializationObject = this.serialize();
  26355. if (this.positions) {
  26356. serializationObject.positions = this.positions;
  26357. }
  26358. if (this.normals) {
  26359. serializationObject.normals = this.normals;
  26360. }
  26361. if (this.uvs) {
  26362. serializationObject.uvs = this.uvs;
  26363. }
  26364. if (this.uvs2) {
  26365. serializationObject.uvs2 = this.uvs2;
  26366. }
  26367. if (this.uvs3) {
  26368. serializationObject.uvs3 = this.uvs3;
  26369. }
  26370. if (this.uvs4) {
  26371. serializationObject.uvs4 = this.uvs4;
  26372. }
  26373. if (this.uvs5) {
  26374. serializationObject.uvs5 = this.uvs5;
  26375. }
  26376. if (this.uvs6) {
  26377. serializationObject.uvs6 = this.uvs6;
  26378. }
  26379. if (this.colors) {
  26380. serializationObject.colors = this.colors;
  26381. }
  26382. if (this.matricesIndices) {
  26383. serializationObject.matricesIndices = this.matricesIndices;
  26384. serializationObject.matricesIndices._isExpanded = true;
  26385. }
  26386. if (this.matricesWeights) {
  26387. serializationObject.matricesWeights = this.matricesWeights;
  26388. }
  26389. if (this.matricesIndicesExtra) {
  26390. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26391. serializationObject.matricesIndicesExtra._isExpanded = true;
  26392. }
  26393. if (this.matricesWeightsExtra) {
  26394. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26395. }
  26396. serializationObject.indices = this.indices;
  26397. return serializationObject;
  26398. };
  26399. // Statics
  26400. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26401. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26402. };
  26403. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26404. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26405. };
  26406. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26407. var result = new VertexData();
  26408. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26409. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26410. }
  26411. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26412. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26413. }
  26414. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26415. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26416. }
  26417. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26418. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26419. }
  26420. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26421. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26422. }
  26423. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26424. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26425. }
  26426. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26427. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26428. }
  26429. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26430. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26431. }
  26432. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26433. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26434. }
  26435. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26436. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26437. }
  26438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26439. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26440. }
  26441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26442. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  26443. }
  26444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26445. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  26446. }
  26447. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26448. return result;
  26449. };
  26450. VertexData.CreateRibbon = function (options) {
  26451. var pathArray = options.pathArray;
  26452. var closeArray = options.closeArray || false;
  26453. var closePath = options.closePath || false;
  26454. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26455. var offset = options.offset || defaultOffset;
  26456. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26457. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26458. var positions = [];
  26459. var indices = [];
  26460. var normals = [];
  26461. var uvs = [];
  26462. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26463. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26464. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26465. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26466. var minlg; // minimal length among all paths from pathArray
  26467. var lg = []; // array of path lengths : nb of vertex per path
  26468. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26469. var p; // path iterator
  26470. var i; // point iterator
  26471. var j; // point iterator
  26472. // if single path in pathArray
  26473. if (pathArray.length < 2) {
  26474. var ar1 = [];
  26475. var ar2 = [];
  26476. for (i = 0; i < pathArray[0].length - offset; i++) {
  26477. ar1.push(pathArray[0][i]);
  26478. ar2.push(pathArray[0][i + offset]);
  26479. }
  26480. pathArray = [ar1, ar2];
  26481. }
  26482. // positions and horizontal distances (u)
  26483. var idc = 0;
  26484. var closePathCorr = (closePath) ? 1 : 0;
  26485. var path;
  26486. var l;
  26487. minlg = pathArray[0].length;
  26488. var vectlg;
  26489. var dist;
  26490. for (p = 0; p < pathArray.length; p++) {
  26491. uTotalDistance[p] = 0;
  26492. us[p] = [0];
  26493. path = pathArray[p];
  26494. l = path.length;
  26495. minlg = (minlg < l) ? minlg : l;
  26496. j = 0;
  26497. while (j < l) {
  26498. positions.push(path[j].x, path[j].y, path[j].z);
  26499. if (j > 0) {
  26500. vectlg = path[j].subtract(path[j - 1]).length();
  26501. dist = vectlg + uTotalDistance[p];
  26502. us[p].push(dist);
  26503. uTotalDistance[p] = dist;
  26504. }
  26505. j++;
  26506. }
  26507. if (closePath) {
  26508. j--;
  26509. positions.push(path[0].x, path[0].y, path[0].z);
  26510. vectlg = path[j].subtract(path[0]).length();
  26511. dist = vectlg + uTotalDistance[p];
  26512. us[p].push(dist);
  26513. uTotalDistance[p] = dist;
  26514. }
  26515. lg[p] = l + closePathCorr;
  26516. idx[p] = idc;
  26517. idc += (l + closePathCorr);
  26518. }
  26519. // vertical distances (v)
  26520. var path1;
  26521. var path2;
  26522. var vertex1;
  26523. var vertex2;
  26524. for (i = 0; i < minlg + closePathCorr; i++) {
  26525. vTotalDistance[i] = 0;
  26526. vs[i] = [0];
  26527. for (p = 0; p < pathArray.length - 1; p++) {
  26528. path1 = pathArray[p];
  26529. path2 = pathArray[p + 1];
  26530. if (i === minlg) {
  26531. vertex1 = path1[0];
  26532. vertex2 = path2[0];
  26533. }
  26534. else {
  26535. vertex1 = path1[i];
  26536. vertex2 = path2[i];
  26537. }
  26538. vectlg = vertex2.subtract(vertex1).length();
  26539. dist = vectlg + vTotalDistance[i];
  26540. vs[i].push(dist);
  26541. vTotalDistance[i] = dist;
  26542. }
  26543. if (closeArray) {
  26544. path1 = pathArray[p];
  26545. path2 = pathArray[0];
  26546. if (i === minlg) {
  26547. vertex2 = path2[0];
  26548. }
  26549. vectlg = vertex2.subtract(vertex1).length();
  26550. dist = vectlg + vTotalDistance[i];
  26551. vTotalDistance[i] = dist;
  26552. }
  26553. }
  26554. // uvs
  26555. var u;
  26556. var v;
  26557. for (p = 0; p < pathArray.length; p++) {
  26558. for (i = 0; i < minlg + closePathCorr; i++) {
  26559. u = us[p][i] / uTotalDistance[p];
  26560. v = vs[i][p] / vTotalDistance[i];
  26561. uvs.push(u, v);
  26562. }
  26563. }
  26564. // indices
  26565. p = 0; // path index
  26566. var pi = 0; // positions array index
  26567. var l1 = lg[p] - 1; // path1 length
  26568. var l2 = lg[p + 1] - 1; // path2 length
  26569. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26570. var shft = idx[1] - idx[0]; // shift
  26571. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26572. while (pi <= min && p < path1nb) {
  26573. // 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
  26574. indices.push(pi, pi + shft, pi + 1);
  26575. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26576. pi += 1;
  26577. if (pi === min) {
  26578. p++;
  26579. if (p === lg.length - 1) {
  26580. shft = idx[0] - idx[p];
  26581. l1 = lg[p] - 1;
  26582. l2 = lg[0] - 1;
  26583. }
  26584. else {
  26585. shft = idx[p + 1] - idx[p];
  26586. l1 = lg[p] - 1;
  26587. l2 = lg[p + 1] - 1;
  26588. }
  26589. pi = idx[p];
  26590. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26591. }
  26592. }
  26593. // normals
  26594. VertexData.ComputeNormals(positions, indices, normals);
  26595. if (closePath) {
  26596. var indexFirst = 0;
  26597. var indexLast = 0;
  26598. for (p = 0; p < pathArray.length; p++) {
  26599. indexFirst = idx[p] * 3;
  26600. if (p + 1 < pathArray.length) {
  26601. indexLast = (idx[p + 1] - 1) * 3;
  26602. }
  26603. else {
  26604. indexLast = normals.length - 3;
  26605. }
  26606. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26607. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26608. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26609. normals[indexLast] = normals[indexFirst];
  26610. normals[indexLast + 1] = normals[indexFirst + 1];
  26611. normals[indexLast + 2] = normals[indexFirst + 2];
  26612. }
  26613. }
  26614. // sides
  26615. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26616. // Result
  26617. var vertexData = new VertexData();
  26618. vertexData.indices = indices;
  26619. vertexData.positions = positions;
  26620. vertexData.normals = normals;
  26621. vertexData.uvs = uvs;
  26622. if (closePath) {
  26623. vertexData._idx = idx;
  26624. }
  26625. return vertexData;
  26626. };
  26627. VertexData.CreateBox = function (options) {
  26628. var normalsSource = [
  26629. new BABYLON.Vector3(0, 0, 1),
  26630. new BABYLON.Vector3(0, 0, -1),
  26631. new BABYLON.Vector3(1, 0, 0),
  26632. new BABYLON.Vector3(-1, 0, 0),
  26633. new BABYLON.Vector3(0, 1, 0),
  26634. new BABYLON.Vector3(0, -1, 0)
  26635. ];
  26636. var indices = [];
  26637. var positions = [];
  26638. var normals = [];
  26639. var uvs = [];
  26640. var width = options.width || options.size || 1;
  26641. var height = options.height || options.size || 1;
  26642. var depth = options.depth || options.size || 1;
  26643. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26644. var faceUV = options.faceUV || new Array(6);
  26645. var faceColors = options.faceColors;
  26646. var colors = [];
  26647. // default face colors and UV if undefined
  26648. for (var f = 0; f < 6; f++) {
  26649. if (faceUV[f] === undefined) {
  26650. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26651. }
  26652. if (faceColors && faceColors[f] === undefined) {
  26653. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26654. }
  26655. }
  26656. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26657. // Create each face in turn.
  26658. for (var index = 0; index < normalsSource.length; index++) {
  26659. var normal = normalsSource[index];
  26660. // Get two vectors perpendicular to the face normal and to each other.
  26661. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26662. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26663. // Six indices (two triangles) per face.
  26664. var verticesLength = positions.length / 3;
  26665. indices.push(verticesLength);
  26666. indices.push(verticesLength + 1);
  26667. indices.push(verticesLength + 2);
  26668. indices.push(verticesLength);
  26669. indices.push(verticesLength + 2);
  26670. indices.push(verticesLength + 3);
  26671. // Four vertices per face.
  26672. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26673. positions.push(vertex.x, vertex.y, vertex.z);
  26674. normals.push(normal.x, normal.y, normal.z);
  26675. uvs.push(faceUV[index].z, faceUV[index].w);
  26676. if (faceColors) {
  26677. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26678. }
  26679. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26680. positions.push(vertex.x, vertex.y, vertex.z);
  26681. normals.push(normal.x, normal.y, normal.z);
  26682. uvs.push(faceUV[index].x, faceUV[index].w);
  26683. if (faceColors) {
  26684. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26685. }
  26686. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26687. positions.push(vertex.x, vertex.y, vertex.z);
  26688. normals.push(normal.x, normal.y, normal.z);
  26689. uvs.push(faceUV[index].x, faceUV[index].y);
  26690. if (faceColors) {
  26691. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26692. }
  26693. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26694. positions.push(vertex.x, vertex.y, vertex.z);
  26695. normals.push(normal.x, normal.y, normal.z);
  26696. uvs.push(faceUV[index].z, faceUV[index].y);
  26697. if (faceColors) {
  26698. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26699. }
  26700. }
  26701. // sides
  26702. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26703. // Result
  26704. var vertexData = new VertexData();
  26705. vertexData.indices = indices;
  26706. vertexData.positions = positions;
  26707. vertexData.normals = normals;
  26708. vertexData.uvs = uvs;
  26709. if (faceColors) {
  26710. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26711. vertexData.colors = totalColors;
  26712. }
  26713. return vertexData;
  26714. };
  26715. VertexData.CreateSphere = function (options) {
  26716. var segments = options.segments || 32;
  26717. var diameterX = options.diameterX || options.diameter || 1;
  26718. var diameterY = options.diameterY || options.diameter || 1;
  26719. var diameterZ = options.diameterZ || options.diameter || 1;
  26720. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26721. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26722. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26723. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26724. var totalZRotationSteps = 2 + segments;
  26725. var totalYRotationSteps = 2 * totalZRotationSteps;
  26726. var indices = [];
  26727. var positions = [];
  26728. var normals = [];
  26729. var uvs = [];
  26730. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26731. var normalizedZ = zRotationStep / totalZRotationSteps;
  26732. var angleZ = normalizedZ * Math.PI * slice;
  26733. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26734. var normalizedY = yRotationStep / totalYRotationSteps;
  26735. var angleY = normalizedY * Math.PI * 2 * arc;
  26736. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26737. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26738. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26739. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26740. var vertex = complete.multiply(radius);
  26741. var normal = complete.divide(radius).normalize();
  26742. positions.push(vertex.x, vertex.y, vertex.z);
  26743. normals.push(normal.x, normal.y, normal.z);
  26744. uvs.push(normalizedY, normalizedZ);
  26745. }
  26746. if (zRotationStep > 0) {
  26747. var verticesCount = positions.length / 3;
  26748. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26749. indices.push((firstIndex));
  26750. indices.push((firstIndex + 1));
  26751. indices.push(firstIndex + totalYRotationSteps + 1);
  26752. indices.push((firstIndex + totalYRotationSteps + 1));
  26753. indices.push((firstIndex + 1));
  26754. indices.push((firstIndex + totalYRotationSteps + 2));
  26755. }
  26756. }
  26757. }
  26758. // Sides
  26759. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26760. // Result
  26761. var vertexData = new VertexData();
  26762. vertexData.indices = indices;
  26763. vertexData.positions = positions;
  26764. vertexData.normals = normals;
  26765. vertexData.uvs = uvs;
  26766. return vertexData;
  26767. };
  26768. // Cylinder and cone
  26769. VertexData.CreateCylinder = function (options) {
  26770. var height = options.height || 2;
  26771. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26772. var diameterBottom = options.diameterBottom || options.diameter || 1;
  26773. var tessellation = options.tessellation || 24;
  26774. var subdivisions = options.subdivisions || 1;
  26775. var hasRings = options.hasRings;
  26776. var enclose = options.enclose;
  26777. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26778. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26779. var faceUV = options.faceUV || new Array(3);
  26780. var faceColors = options.faceColors;
  26781. // default face colors and UV if undefined
  26782. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26783. var ringNb = (hasRings) ? subdivisions : 1;
  26784. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26785. var f;
  26786. for (f = 0; f < surfaceNb; f++) {
  26787. if (faceColors && faceColors[f] === undefined) {
  26788. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26789. }
  26790. }
  26791. for (f = 0; f < surfaceNb; f++) {
  26792. if (faceUV && faceUV[f] === undefined) {
  26793. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26794. }
  26795. }
  26796. var indices = [];
  26797. var positions = [];
  26798. var normals = [];
  26799. var uvs = [];
  26800. var colors = [];
  26801. var angle_step = Math.PI * 2 * arc / tessellation;
  26802. var angle;
  26803. var h;
  26804. var radius;
  26805. var tan = (diameterBottom - diameterTop) / 2 / height;
  26806. var ringVertex = BABYLON.Vector3.Zero();
  26807. var ringNormal = BABYLON.Vector3.Zero();
  26808. var ringFirstVertex = BABYLON.Vector3.Zero();
  26809. var ringFirstNormal = BABYLON.Vector3.Zero();
  26810. var quadNormal = BABYLON.Vector3.Zero();
  26811. var Y = BABYLON.Axis.Y;
  26812. // positions, normals, uvs
  26813. var i;
  26814. var j;
  26815. var r;
  26816. var ringIdx = 1;
  26817. var s = 1; // surface index
  26818. var cs = 0;
  26819. var v = 0;
  26820. for (i = 0; i <= subdivisions; i++) {
  26821. h = i / subdivisions;
  26822. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26823. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26824. for (r = 0; r < ringIdx; r++) {
  26825. if (hasRings) {
  26826. s += r;
  26827. }
  26828. if (enclose) {
  26829. s += 2 * r;
  26830. }
  26831. for (j = 0; j <= tessellation; j++) {
  26832. angle = j * angle_step;
  26833. // position
  26834. ringVertex.x = Math.cos(-angle) * radius;
  26835. ringVertex.y = -height / 2 + h * height;
  26836. ringVertex.z = Math.sin(-angle) * radius;
  26837. // normal
  26838. if (diameterTop === 0 && i === subdivisions) {
  26839. // if no top cap, reuse former normals
  26840. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26841. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26842. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26843. }
  26844. else {
  26845. ringNormal.x = ringVertex.x;
  26846. ringNormal.z = ringVertex.z;
  26847. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26848. ringNormal.normalize();
  26849. }
  26850. // keep first ring vertex values for enclose
  26851. if (j === 0) {
  26852. ringFirstVertex.copyFrom(ringVertex);
  26853. ringFirstNormal.copyFrom(ringNormal);
  26854. }
  26855. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26856. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26857. if (hasRings) {
  26858. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26859. }
  26860. else {
  26861. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26862. }
  26863. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26864. if (faceColors) {
  26865. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26866. }
  26867. }
  26868. // if enclose, add four vertices and their dedicated normals
  26869. if (arc !== 1 && enclose) {
  26870. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26871. positions.push(0, ringVertex.y, 0);
  26872. positions.push(0, ringVertex.y, 0);
  26873. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26874. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26875. quadNormal.normalize();
  26876. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26877. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26878. quadNormal.normalize();
  26879. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26880. if (hasRings) {
  26881. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26882. }
  26883. else {
  26884. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26885. }
  26886. uvs.push(faceUV[s + 1].x, v);
  26887. uvs.push(faceUV[s + 1].z, v);
  26888. if (hasRings) {
  26889. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26890. }
  26891. else {
  26892. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26893. }
  26894. uvs.push(faceUV[s + 2].x, v);
  26895. uvs.push(faceUV[s + 2].z, v);
  26896. if (faceColors) {
  26897. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26898. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26899. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26900. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26901. }
  26902. }
  26903. if (cs !== s) {
  26904. cs = s;
  26905. }
  26906. }
  26907. }
  26908. // indices
  26909. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26910. var s;
  26911. i = 0;
  26912. for (s = 0; s < subdivisions; s++) {
  26913. for (j = 0; j < tessellation; j++) {
  26914. var i0 = i * (e + 1) + j;
  26915. var i1 = (i + 1) * (e + 1) + j;
  26916. var i2 = i * (e + 1) + (j + 1);
  26917. var i3 = (i + 1) * (e + 1) + (j + 1);
  26918. indices.push(i0, i1, i2);
  26919. indices.push(i3, i2, i1);
  26920. }
  26921. if (arc !== 1 && enclose) {
  26922. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26923. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26924. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26925. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26926. }
  26927. i = (hasRings) ? (i + 2) : (i + 1);
  26928. }
  26929. // Caps
  26930. var createCylinderCap = function (isTop) {
  26931. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26932. if (radius === 0) {
  26933. return;
  26934. }
  26935. // Cap positions, normals & uvs
  26936. var angle;
  26937. var circleVector;
  26938. var i;
  26939. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26940. var c;
  26941. if (faceColors) {
  26942. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26943. }
  26944. // cap center
  26945. var vbase = positions.length / 3;
  26946. var offset = isTop ? height / 2 : -height / 2;
  26947. var center = new BABYLON.Vector3(0, offset, 0);
  26948. positions.push(center.x, center.y, center.z);
  26949. normals.push(0, isTop ? 1 : -1, 0);
  26950. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26951. if (faceColors) {
  26952. colors.push(c.r, c.g, c.b, c.a);
  26953. }
  26954. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26955. for (i = 0; i <= tessellation; i++) {
  26956. angle = Math.PI * 2 * i * arc / tessellation;
  26957. var cos = Math.cos(-angle);
  26958. var sin = Math.sin(-angle);
  26959. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26960. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26961. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26962. normals.push(0, isTop ? 1 : -1, 0);
  26963. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26964. if (faceColors) {
  26965. colors.push(c.r, c.g, c.b, c.a);
  26966. }
  26967. }
  26968. // Cap indices
  26969. for (i = 0; i < tessellation; i++) {
  26970. if (!isTop) {
  26971. indices.push(vbase);
  26972. indices.push(vbase + (i + 1));
  26973. indices.push(vbase + (i + 2));
  26974. }
  26975. else {
  26976. indices.push(vbase);
  26977. indices.push(vbase + (i + 2));
  26978. indices.push(vbase + (i + 1));
  26979. }
  26980. }
  26981. };
  26982. // add caps to geometry
  26983. createCylinderCap(false);
  26984. createCylinderCap(true);
  26985. // Sides
  26986. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26987. var vertexData = new VertexData();
  26988. vertexData.indices = indices;
  26989. vertexData.positions = positions;
  26990. vertexData.normals = normals;
  26991. vertexData.uvs = uvs;
  26992. if (faceColors) {
  26993. vertexData.colors = colors;
  26994. }
  26995. return vertexData;
  26996. };
  26997. VertexData.CreateTorus = function (options) {
  26998. var indices = [];
  26999. var positions = [];
  27000. var normals = [];
  27001. var uvs = [];
  27002. var diameter = options.diameter || 1;
  27003. var thickness = options.thickness || 0.5;
  27004. var tessellation = options.tessellation || 16;
  27005. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27006. var stride = tessellation + 1;
  27007. for (var i = 0; i <= tessellation; i++) {
  27008. var u = i / tessellation;
  27009. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27010. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27011. for (var j = 0; j <= tessellation; j++) {
  27012. var v = 1 - j / tessellation;
  27013. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27014. var dx = Math.cos(innerAngle);
  27015. var dy = Math.sin(innerAngle);
  27016. // Create a vertex.
  27017. var normal = new BABYLON.Vector3(dx, dy, 0);
  27018. var position = normal.scale(thickness / 2);
  27019. var textureCoordinate = new BABYLON.Vector2(u, v);
  27020. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27021. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27022. positions.push(position.x, position.y, position.z);
  27023. normals.push(normal.x, normal.y, normal.z);
  27024. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27025. // And create indices for two triangles.
  27026. var nextI = (i + 1) % stride;
  27027. var nextJ = (j + 1) % stride;
  27028. indices.push(i * stride + j);
  27029. indices.push(i * stride + nextJ);
  27030. indices.push(nextI * stride + j);
  27031. indices.push(i * stride + nextJ);
  27032. indices.push(nextI * stride + nextJ);
  27033. indices.push(nextI * stride + j);
  27034. }
  27035. }
  27036. // Sides
  27037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27038. // Result
  27039. var vertexData = new VertexData();
  27040. vertexData.indices = indices;
  27041. vertexData.positions = positions;
  27042. vertexData.normals = normals;
  27043. vertexData.uvs = uvs;
  27044. return vertexData;
  27045. };
  27046. VertexData.CreateLineSystem = function (options) {
  27047. var indices = [];
  27048. var positions = [];
  27049. var lines = options.lines;
  27050. var idx = 0;
  27051. for (var l = 0; l < lines.length; l++) {
  27052. var points = lines[l];
  27053. for (var index = 0; index < points.length; index++) {
  27054. positions.push(points[index].x, points[index].y, points[index].z);
  27055. if (index > 0) {
  27056. indices.push(idx - 1);
  27057. indices.push(idx);
  27058. }
  27059. idx++;
  27060. }
  27061. }
  27062. var vertexData = new VertexData();
  27063. vertexData.indices = indices;
  27064. vertexData.positions = positions;
  27065. return vertexData;
  27066. };
  27067. VertexData.CreateDashedLines = function (options) {
  27068. var dashSize = options.dashSize || 3;
  27069. var gapSize = options.gapSize || 1;
  27070. var dashNb = options.dashNb || 200;
  27071. var points = options.points;
  27072. var positions = new Array();
  27073. var indices = new Array();
  27074. var curvect = BABYLON.Vector3.Zero();
  27075. var lg = 0;
  27076. var nb = 0;
  27077. var shft = 0;
  27078. var dashshft = 0;
  27079. var curshft = 0;
  27080. var idx = 0;
  27081. var i = 0;
  27082. for (i = 0; i < points.length - 1; i++) {
  27083. points[i + 1].subtractToRef(points[i], curvect);
  27084. lg += curvect.length();
  27085. }
  27086. shft = lg / dashNb;
  27087. dashshft = dashSize * shft / (dashSize + gapSize);
  27088. for (i = 0; i < points.length - 1; i++) {
  27089. points[i + 1].subtractToRef(points[i], curvect);
  27090. nb = Math.floor(curvect.length() / shft);
  27091. curvect.normalize();
  27092. for (var j = 0; j < nb; j++) {
  27093. curshft = shft * j;
  27094. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27095. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27096. indices.push(idx, idx + 1);
  27097. idx += 2;
  27098. }
  27099. }
  27100. // Result
  27101. var vertexData = new VertexData();
  27102. vertexData.positions = positions;
  27103. vertexData.indices = indices;
  27104. return vertexData;
  27105. };
  27106. VertexData.CreateGround = function (options) {
  27107. var indices = [];
  27108. var positions = [];
  27109. var normals = [];
  27110. var uvs = [];
  27111. var row, col;
  27112. var width = options.width || 1;
  27113. var height = options.height || 1;
  27114. var subdivisions = options.subdivisions || 1;
  27115. for (row = 0; row <= subdivisions; row++) {
  27116. for (col = 0; col <= subdivisions; col++) {
  27117. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  27118. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27119. positions.push(position.x, position.y, position.z);
  27120. normals.push(normal.x, normal.y, normal.z);
  27121. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  27122. }
  27123. }
  27124. for (row = 0; row < subdivisions; row++) {
  27125. for (col = 0; col < subdivisions; col++) {
  27126. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27127. indices.push(col + 1 + row * (subdivisions + 1));
  27128. indices.push(col + row * (subdivisions + 1));
  27129. indices.push(col + (row + 1) * (subdivisions + 1));
  27130. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27131. indices.push(col + row * (subdivisions + 1));
  27132. }
  27133. }
  27134. // Result
  27135. var vertexData = new VertexData();
  27136. vertexData.indices = indices;
  27137. vertexData.positions = positions;
  27138. vertexData.normals = normals;
  27139. vertexData.uvs = uvs;
  27140. return vertexData;
  27141. };
  27142. VertexData.CreateTiledGround = function (options) {
  27143. var xmin = options.xmin;
  27144. var zmin = options.zmin;
  27145. var xmax = options.xmax;
  27146. var zmax = options.zmax;
  27147. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27148. var precision = options.precision || { w: 1, h: 1 };
  27149. var indices = [];
  27150. var positions = [];
  27151. var normals = [];
  27152. var uvs = [];
  27153. var row, col, tileRow, tileCol;
  27154. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  27155. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27156. precision.w = (precision.w < 1) ? 1 : precision.w;
  27157. precision.h = (precision.h < 1) ? 1 : precision.h;
  27158. var tileSize = {
  27159. 'w': (xmax - xmin) / subdivisions.w,
  27160. 'h': (zmax - zmin) / subdivisions.h
  27161. };
  27162. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27163. // Indices
  27164. var base = positions.length / 3;
  27165. var rowLength = precision.w + 1;
  27166. for (row = 0; row < precision.h; row++) {
  27167. for (col = 0; col < precision.w; col++) {
  27168. var square = [
  27169. base + col + row * rowLength,
  27170. base + (col + 1) + row * rowLength,
  27171. base + (col + 1) + (row + 1) * rowLength,
  27172. base + col + (row + 1) * rowLength
  27173. ];
  27174. indices.push(square[1]);
  27175. indices.push(square[2]);
  27176. indices.push(square[3]);
  27177. indices.push(square[0]);
  27178. indices.push(square[1]);
  27179. indices.push(square[3]);
  27180. }
  27181. }
  27182. // Position, normals and uvs
  27183. var position = BABYLON.Vector3.Zero();
  27184. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27185. for (row = 0; row <= precision.h; row++) {
  27186. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27187. for (col = 0; col <= precision.w; col++) {
  27188. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27189. position.y = 0;
  27190. positions.push(position.x, position.y, position.z);
  27191. normals.push(normal.x, normal.y, normal.z);
  27192. uvs.push(col / precision.w, row / precision.h);
  27193. }
  27194. }
  27195. }
  27196. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27197. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27198. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27199. }
  27200. }
  27201. // Result
  27202. var vertexData = new VertexData();
  27203. vertexData.indices = indices;
  27204. vertexData.positions = positions;
  27205. vertexData.normals = normals;
  27206. vertexData.uvs = uvs;
  27207. return vertexData;
  27208. };
  27209. VertexData.CreateGroundFromHeightMap = function (options) {
  27210. var indices = [];
  27211. var positions = [];
  27212. var normals = [];
  27213. var uvs = [];
  27214. var row, col;
  27215. // Vertices
  27216. for (row = 0; row <= options.subdivisions; row++) {
  27217. for (col = 0; col <= options.subdivisions; col++) {
  27218. 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));
  27219. // Compute height
  27220. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27221. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27222. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27223. var r = options.buffer[pos] / 255.0;
  27224. var g = options.buffer[pos + 1] / 255.0;
  27225. var b = options.buffer[pos + 2] / 255.0;
  27226. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27227. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27228. // Add vertex
  27229. positions.push(position.x, position.y, position.z);
  27230. normals.push(0, 0, 0);
  27231. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27232. }
  27233. }
  27234. // Indices
  27235. for (row = 0; row < options.subdivisions; row++) {
  27236. for (col = 0; col < options.subdivisions; col++) {
  27237. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27238. indices.push(col + 1 + row * (options.subdivisions + 1));
  27239. indices.push(col + row * (options.subdivisions + 1));
  27240. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27241. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27242. indices.push(col + row * (options.subdivisions + 1));
  27243. }
  27244. }
  27245. // Normals
  27246. VertexData.ComputeNormals(positions, indices, normals);
  27247. // Result
  27248. var vertexData = new VertexData();
  27249. vertexData.indices = indices;
  27250. vertexData.positions = positions;
  27251. vertexData.normals = normals;
  27252. vertexData.uvs = uvs;
  27253. return vertexData;
  27254. };
  27255. VertexData.CreatePlane = function (options) {
  27256. var indices = [];
  27257. var positions = [];
  27258. var normals = [];
  27259. var uvs = [];
  27260. var width = options.width || options.size || 1;
  27261. var height = options.height || options.size || 1;
  27262. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27263. // Vertices
  27264. var halfWidth = width / 2.0;
  27265. var halfHeight = height / 2.0;
  27266. positions.push(-halfWidth, -halfHeight, 0);
  27267. normals.push(0, 0, -1.0);
  27268. uvs.push(0.0, 0.0);
  27269. positions.push(halfWidth, -halfHeight, 0);
  27270. normals.push(0, 0, -1.0);
  27271. uvs.push(1.0, 0.0);
  27272. positions.push(halfWidth, halfHeight, 0);
  27273. normals.push(0, 0, -1.0);
  27274. uvs.push(1.0, 1.0);
  27275. positions.push(-halfWidth, halfHeight, 0);
  27276. normals.push(0, 0, -1.0);
  27277. uvs.push(0.0, 1.0);
  27278. // Indices
  27279. indices.push(0);
  27280. indices.push(1);
  27281. indices.push(2);
  27282. indices.push(0);
  27283. indices.push(2);
  27284. indices.push(3);
  27285. // Sides
  27286. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27287. // Result
  27288. var vertexData = new VertexData();
  27289. vertexData.indices = indices;
  27290. vertexData.positions = positions;
  27291. vertexData.normals = normals;
  27292. vertexData.uvs = uvs;
  27293. return vertexData;
  27294. };
  27295. VertexData.CreateDisc = function (options) {
  27296. var positions = [];
  27297. var indices = [];
  27298. var normals = [];
  27299. var uvs = [];
  27300. var radius = options.radius || 0.5;
  27301. var tessellation = options.tessellation || 64;
  27302. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27303. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27304. // positions and uvs
  27305. positions.push(0, 0, 0); // disc center first
  27306. uvs.push(0.5, 0.5);
  27307. var theta = Math.PI * 2 * arc;
  27308. var step = theta / tessellation;
  27309. for (var a = 0; a < theta; a += step) {
  27310. var x = Math.cos(a);
  27311. var y = Math.sin(a);
  27312. var u = (x + 1) / 2;
  27313. var v = (1 - y) / 2;
  27314. positions.push(radius * x, radius * y, 0);
  27315. uvs.push(u, v);
  27316. }
  27317. if (arc === 1) {
  27318. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27319. uvs.push(uvs[2], uvs[3]);
  27320. }
  27321. //indices
  27322. var vertexNb = positions.length / 3;
  27323. for (var i = 1; i < vertexNb - 1; i++) {
  27324. indices.push(i + 1, 0, i);
  27325. }
  27326. // result
  27327. VertexData.ComputeNormals(positions, indices, normals);
  27328. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27329. var vertexData = new VertexData();
  27330. vertexData.indices = indices;
  27331. vertexData.positions = positions;
  27332. vertexData.normals = normals;
  27333. vertexData.uvs = uvs;
  27334. return vertexData;
  27335. };
  27336. VertexData.CreateIcoSphere = function (options) {
  27337. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27338. var radius = options.radius || 1;
  27339. var flat = (options.flat === undefined) ? true : options.flat;
  27340. var subdivisions = options.subdivisions || 4;
  27341. var radiusX = options.radiusX || radius;
  27342. var radiusY = options.radiusY || radius;
  27343. var radiusZ = options.radiusZ || radius;
  27344. var t = (1 + Math.sqrt(5)) / 2;
  27345. // 12 vertex x,y,z
  27346. var ico_vertices = [
  27347. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27348. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27349. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27350. ];
  27351. // index of 3 vertex makes a face of icopshere
  27352. var ico_indices = [
  27353. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27354. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27355. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27356. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27357. ];
  27358. // vertex for uv have aliased position, not for UV
  27359. var vertices_unalias_id = [
  27360. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27361. // vertex alias
  27362. 0,
  27363. 2,
  27364. 3,
  27365. 3,
  27366. 3,
  27367. 4,
  27368. 7,
  27369. 8,
  27370. 9,
  27371. 9,
  27372. 10,
  27373. 11 // 23: B + 12
  27374. ];
  27375. // uv as integer step (not pixels !)
  27376. var ico_vertexuv = [
  27377. 5, 1, 3, 1, 6, 4, 0, 0,
  27378. 5, 3, 4, 2, 2, 2, 4, 0,
  27379. 2, 0, 1, 1, 6, 0, 6, 2,
  27380. // vertex alias (for same vertex on different faces)
  27381. 0, 4,
  27382. 3, 3,
  27383. 4, 4,
  27384. 3, 1,
  27385. 4, 2,
  27386. 4, 4,
  27387. 0, 2,
  27388. 1, 1,
  27389. 2, 2,
  27390. 3, 3,
  27391. 1, 3,
  27392. 2, 4 // 23: B + 12
  27393. ];
  27394. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27395. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27396. // First island of uv mapping
  27397. // v = 4h 3+ 2
  27398. // v = 3h 9+ 4
  27399. // v = 2h 9+ 5 B
  27400. // v = 1h 9 1 0
  27401. // v = 0h 3 8 7 A
  27402. // u = 0 1 2 3 4 5 6 *a
  27403. // Second island of uv mapping
  27404. // v = 4h 0+ B+ 4+
  27405. // v = 3h A+ 2+
  27406. // v = 2h 7+ 6 3+
  27407. // v = 1h 8+ 3+
  27408. // v = 0h
  27409. // u = 0 1 2 3 4 5 6 *a
  27410. // Face layout on texture UV mapping
  27411. // ============
  27412. // \ 4 /\ 16 / ======
  27413. // \ / \ / /\ 11 /
  27414. // \/ 7 \/ / \ /
  27415. // ======= / 10 \/
  27416. // /\ 17 /\ =======
  27417. // / \ / \ \ 15 /\
  27418. // / 8 \/ 12 \ \ / \
  27419. // ============ \/ 6 \
  27420. // \ 18 /\ ============
  27421. // \ / \ \ 5 /\ 0 /
  27422. // \/ 13 \ \ / \ /
  27423. // ======= \/ 1 \/
  27424. // =============
  27425. // /\ 19 /\ 2 /\
  27426. // / \ / \ / \
  27427. // / 14 \/ 9 \/ 3 \
  27428. // ===================
  27429. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27430. var ustep = 138 / 1024;
  27431. var vstep = 239 / 1024;
  27432. var uoffset = 60 / 1024;
  27433. var voffset = 26 / 1024;
  27434. // Second island should have margin, not to touch the first island
  27435. // avoid any borderline artefact in pixel rounding
  27436. var island_u_offset = -40 / 1024;
  27437. var island_v_offset = +20 / 1024;
  27438. // face is either island 0 or 1 :
  27439. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27440. var island = [
  27441. 0, 0, 0, 0, 1,
  27442. 0, 0, 1, 1, 0,
  27443. 0, 0, 1, 1, 0,
  27444. 0, 1, 1, 1, 0 // 15 - 19
  27445. ];
  27446. var indices = [];
  27447. var positions = [];
  27448. var normals = [];
  27449. var uvs = [];
  27450. var current_indice = 0;
  27451. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27452. var face_vertex_pos = new Array(3);
  27453. var face_vertex_uv = new Array(3);
  27454. var v012;
  27455. for (v012 = 0; v012 < 3; v012++) {
  27456. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27457. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27458. }
  27459. // create all with normals
  27460. for (var face = 0; face < 20; face++) {
  27461. // 3 vertex per face
  27462. for (v012 = 0; v012 < 3; v012++) {
  27463. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27464. var v_id = ico_indices[3 * face + v012];
  27465. // vertex have 3D position (x,y,z)
  27466. 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]);
  27467. // Normalize to get normal, then scale to radius
  27468. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27469. // uv Coordinates from vertex ID
  27470. 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);
  27471. }
  27472. // Subdivide the face (interpolate pos, norm, uv)
  27473. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27474. // - norm is linear interpolation of vertex corner normal
  27475. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27476. // - uv is linear interpolation
  27477. //
  27478. // Topology is as below for sub-divide by 2
  27479. // vertex shown as v0,v1,v2
  27480. // interp index is i1 to progress in range [v0,v1[
  27481. // interp index is i2 to progress in range [v0,v2[
  27482. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27483. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27484. //
  27485. //
  27486. // i2 v2
  27487. // ^ ^
  27488. // / / \
  27489. // / / \
  27490. // / / \
  27491. // / / (0,1) \
  27492. // / #---------\
  27493. // / / \ (0,0)'/ \
  27494. // / / \ / \
  27495. // / / \ / \
  27496. // / / (0,0) \ / (1,0) \
  27497. // / #---------#---------\
  27498. // v0 v1
  27499. //
  27500. // --------------------> i1
  27501. //
  27502. // interp of (i1,i2):
  27503. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27504. // along i1 : lerp(x0,x1, i1/(S-i2))
  27505. //
  27506. // centroid of triangle is needed to get help normal computation
  27507. // (c1,c2) are used for centroid location
  27508. var interp_vertex = function (i1, i2, c1, c2) {
  27509. // vertex is interpolated from
  27510. // - face_vertex_pos[0..2]
  27511. // - face_vertex_uv[0..2]
  27512. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27513. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27514. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27515. pos_interp.normalize();
  27516. var vertex_normal;
  27517. if (flat) {
  27518. // in flat mode, recalculate normal as face centroid normal
  27519. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27520. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27521. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27522. }
  27523. else {
  27524. // in smooth mode, recalculate normal from each single vertex position
  27525. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27526. }
  27527. // Vertex normal need correction due to X,Y,Z radius scaling
  27528. vertex_normal.x /= radiusX;
  27529. vertex_normal.y /= radiusY;
  27530. vertex_normal.z /= radiusZ;
  27531. vertex_normal.normalize();
  27532. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27533. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27534. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27535. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27536. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27537. uvs.push(uv_interp.x, uv_interp.y);
  27538. // push each vertex has member of a face
  27539. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27540. indices.push(current_indice);
  27541. current_indice++;
  27542. };
  27543. for (var i2 = 0; i2 < subdivisions; i2++) {
  27544. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27545. // face : (i1,i2) for /\ :
  27546. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27547. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27548. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27549. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27550. if (i1 + i2 + 1 < subdivisions) {
  27551. // face : (i1,i2)' for \/ :
  27552. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27553. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27554. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27555. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27556. }
  27557. }
  27558. }
  27559. }
  27560. // Sides
  27561. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27562. // Result
  27563. var vertexData = new VertexData();
  27564. vertexData.indices = indices;
  27565. vertexData.positions = positions;
  27566. vertexData.normals = normals;
  27567. vertexData.uvs = uvs;
  27568. return vertexData;
  27569. };
  27570. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27571. VertexData.CreatePolyhedron = function (options) {
  27572. // provided polyhedron types :
  27573. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27574. // 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)
  27575. var polyhedra = [];
  27576. 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]] };
  27577. 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]] };
  27578. polyhedra[2] = {
  27579. 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]],
  27580. 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]]
  27581. };
  27582. polyhedra[3] = {
  27583. 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]],
  27584. 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]]
  27585. };
  27586. polyhedra[4] = {
  27587. 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]],
  27588. 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]]
  27589. };
  27590. 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]] };
  27591. 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]] };
  27592. 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]] };
  27593. 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]] };
  27594. 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]] };
  27595. 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]] };
  27596. 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]] };
  27597. 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]] };
  27598. 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]] };
  27599. polyhedra[14] = {
  27600. 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]],
  27601. 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]]
  27602. };
  27603. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27604. var size = options.size;
  27605. var sizeX = options.sizeX || size || 1;
  27606. var sizeY = options.sizeY || size || 1;
  27607. var sizeZ = options.sizeZ || size || 1;
  27608. var data = options.custom || polyhedra[type];
  27609. var nbfaces = data.face.length;
  27610. var faceUV = options.faceUV || new Array(nbfaces);
  27611. var faceColors = options.faceColors;
  27612. var flat = (options.flat === undefined) ? true : options.flat;
  27613. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27614. var positions = [];
  27615. var indices = [];
  27616. var normals = [];
  27617. var uvs = [];
  27618. var colors = [];
  27619. var index = 0;
  27620. var faceIdx = 0; // face cursor in the array "indexes"
  27621. var indexes = [];
  27622. var i = 0;
  27623. var f = 0;
  27624. var u, v, ang, x, y, tmp;
  27625. // default face colors and UV if undefined
  27626. if (flat) {
  27627. for (f = 0; f < nbfaces; f++) {
  27628. if (faceColors && faceColors[f] === undefined) {
  27629. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27630. }
  27631. if (faceUV && faceUV[f] === undefined) {
  27632. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27633. }
  27634. }
  27635. }
  27636. if (!flat) {
  27637. for (i = 0; i < data.vertex.length; i++) {
  27638. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27639. uvs.push(0, 0);
  27640. }
  27641. for (f = 0; f < nbfaces; f++) {
  27642. for (i = 0; i < data.face[f].length - 2; i++) {
  27643. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27644. }
  27645. }
  27646. }
  27647. else {
  27648. for (f = 0; f < nbfaces; f++) {
  27649. var fl = data.face[f].length; // number of vertices of the current face
  27650. ang = 2 * Math.PI / fl;
  27651. x = 0.5 * Math.tan(ang / 2);
  27652. y = 0.5;
  27653. // positions, uvs, colors
  27654. for (i = 0; i < fl; i++) {
  27655. // positions
  27656. 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);
  27657. indexes.push(index);
  27658. index++;
  27659. // uvs
  27660. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27661. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27662. uvs.push(u, v);
  27663. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27664. y = x * Math.sin(ang) + y * Math.cos(ang);
  27665. x = tmp;
  27666. // colors
  27667. if (faceColors) {
  27668. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27669. }
  27670. }
  27671. // indices from indexes
  27672. for (i = 0; i < fl - 2; i++) {
  27673. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27674. }
  27675. faceIdx += fl;
  27676. }
  27677. }
  27678. VertexData.ComputeNormals(positions, indices, normals);
  27679. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27680. var vertexData = new VertexData();
  27681. vertexData.positions = positions;
  27682. vertexData.indices = indices;
  27683. vertexData.normals = normals;
  27684. vertexData.uvs = uvs;
  27685. if (faceColors && flat) {
  27686. vertexData.colors = colors;
  27687. }
  27688. return vertexData;
  27689. };
  27690. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27691. VertexData.CreateTorusKnot = function (options) {
  27692. var indices = [];
  27693. var positions = [];
  27694. var normals = [];
  27695. var uvs = [];
  27696. var radius = options.radius || 2;
  27697. var tube = options.tube || 0.5;
  27698. var radialSegments = options.radialSegments || 32;
  27699. var tubularSegments = options.tubularSegments || 32;
  27700. var p = options.p || 2;
  27701. var q = options.q || 3;
  27702. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27703. // Helper
  27704. var getPos = function (angle) {
  27705. var cu = Math.cos(angle);
  27706. var su = Math.sin(angle);
  27707. var quOverP = q / p * angle;
  27708. var cs = Math.cos(quOverP);
  27709. var tx = radius * (2 + cs) * 0.5 * cu;
  27710. var ty = radius * (2 + cs) * su * 0.5;
  27711. var tz = radius * Math.sin(quOverP) * 0.5;
  27712. return new BABYLON.Vector3(tx, ty, tz);
  27713. };
  27714. // Vertices
  27715. var i;
  27716. var j;
  27717. for (i = 0; i <= radialSegments; i++) {
  27718. var modI = i % radialSegments;
  27719. var u = modI / radialSegments * 2 * p * Math.PI;
  27720. var p1 = getPos(u);
  27721. var p2 = getPos(u + 0.01);
  27722. var tang = p2.subtract(p1);
  27723. var n = p2.add(p1);
  27724. var bitan = BABYLON.Vector3.Cross(tang, n);
  27725. n = BABYLON.Vector3.Cross(bitan, tang);
  27726. bitan.normalize();
  27727. n.normalize();
  27728. for (j = 0; j < tubularSegments; j++) {
  27729. var modJ = j % tubularSegments;
  27730. var v = modJ / tubularSegments * 2 * Math.PI;
  27731. var cx = -tube * Math.cos(v);
  27732. var cy = tube * Math.sin(v);
  27733. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27734. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27735. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27736. uvs.push(i / radialSegments);
  27737. uvs.push(j / tubularSegments);
  27738. }
  27739. }
  27740. for (i = 0; i < radialSegments; i++) {
  27741. for (j = 0; j < tubularSegments; j++) {
  27742. var jNext = (j + 1) % tubularSegments;
  27743. var a = i * tubularSegments + j;
  27744. var b = (i + 1) * tubularSegments + j;
  27745. var c = (i + 1) * tubularSegments + jNext;
  27746. var d = i * tubularSegments + jNext;
  27747. indices.push(d);
  27748. indices.push(b);
  27749. indices.push(a);
  27750. indices.push(d);
  27751. indices.push(c);
  27752. indices.push(b);
  27753. }
  27754. }
  27755. // Normals
  27756. VertexData.ComputeNormals(positions, indices, normals);
  27757. // Sides
  27758. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27759. // Result
  27760. var vertexData = new VertexData();
  27761. vertexData.indices = indices;
  27762. vertexData.positions = positions;
  27763. vertexData.normals = normals;
  27764. vertexData.uvs = uvs;
  27765. return vertexData;
  27766. };
  27767. // Tools
  27768. /**
  27769. * @param {any} - positions (number[] or Float32Array)
  27770. * @param {any} - indices (number[] or Uint16Array)
  27771. * @param {any} - normals (number[] or Float32Array)
  27772. */
  27773. VertexData.ComputeNormals = function (positions, indices, normals) {
  27774. var index = 0;
  27775. var p1p2x = 0.0;
  27776. var p1p2y = 0.0;
  27777. var p1p2z = 0.0;
  27778. var p3p2x = 0.0;
  27779. var p3p2y = 0.0;
  27780. var p3p2z = 0.0;
  27781. var faceNormalx = 0.0;
  27782. var faceNormaly = 0.0;
  27783. var faceNormalz = 0.0;
  27784. var length = 0.0;
  27785. var i1 = 0;
  27786. var i2 = 0;
  27787. var i3 = 0;
  27788. for (index = 0; index < positions.length; index++) {
  27789. normals[index] = 0.0;
  27790. }
  27791. // indice triplet = 1 face
  27792. var nbFaces = indices.length / 3;
  27793. for (index = 0; index < nbFaces; index++) {
  27794. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  27795. i2 = indices[index * 3 + 1];
  27796. i3 = indices[index * 3 + 2];
  27797. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  27798. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27799. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27800. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  27801. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27802. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27803. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  27804. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  27805. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  27806. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27807. length = (length === 0) ? 1.0 : length;
  27808. faceNormalx /= length; // normalize this normal
  27809. faceNormaly /= length;
  27810. faceNormalz /= length;
  27811. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  27812. normals[i1 * 3 + 1] += faceNormaly;
  27813. normals[i1 * 3 + 2] += faceNormalz;
  27814. normals[i2 * 3] += faceNormalx;
  27815. normals[i2 * 3 + 1] += faceNormaly;
  27816. normals[i2 * 3 + 2] += faceNormalz;
  27817. normals[i3 * 3] += faceNormalx;
  27818. normals[i3 * 3 + 1] += faceNormaly;
  27819. normals[i3 * 3 + 2] += faceNormalz;
  27820. }
  27821. // last normalization of each normal
  27822. for (index = 0; index < normals.length / 3; index++) {
  27823. faceNormalx = normals[index * 3];
  27824. faceNormaly = normals[index * 3 + 1];
  27825. faceNormalz = normals[index * 3 + 2];
  27826. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27827. length = (length === 0) ? 1.0 : length;
  27828. faceNormalx /= length;
  27829. faceNormaly /= length;
  27830. faceNormalz /= length;
  27831. normals[index * 3] = faceNormalx;
  27832. normals[index * 3 + 1] = faceNormaly;
  27833. normals[index * 3 + 2] = faceNormalz;
  27834. }
  27835. };
  27836. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27837. var li = indices.length;
  27838. var ln = normals.length;
  27839. var i;
  27840. var n;
  27841. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27842. switch (sideOrientation) {
  27843. case BABYLON.Mesh.FRONTSIDE:
  27844. // nothing changed
  27845. break;
  27846. case BABYLON.Mesh.BACKSIDE:
  27847. var tmp;
  27848. // indices
  27849. for (i = 0; i < li; i += 3) {
  27850. tmp = indices[i];
  27851. indices[i] = indices[i + 2];
  27852. indices[i + 2] = tmp;
  27853. }
  27854. // normals
  27855. for (n = 0; n < ln; n++) {
  27856. normals[n] = -normals[n];
  27857. }
  27858. break;
  27859. case BABYLON.Mesh.DOUBLESIDE:
  27860. // positions
  27861. var lp = positions.length;
  27862. var l = lp / 3;
  27863. for (var p = 0; p < lp; p++) {
  27864. positions[lp + p] = positions[p];
  27865. }
  27866. // indices
  27867. for (i = 0; i < li; i += 3) {
  27868. indices[i + li] = indices[i + 2] + l;
  27869. indices[i + 1 + li] = indices[i + 1] + l;
  27870. indices[i + 2 + li] = indices[i] + l;
  27871. }
  27872. // normals
  27873. for (n = 0; n < ln; n++) {
  27874. normals[ln + n] = -normals[n];
  27875. }
  27876. // uvs
  27877. var lu = uvs.length;
  27878. for (var u = 0; u < lu; u++) {
  27879. uvs[u + lu] = uvs[u];
  27880. }
  27881. break;
  27882. }
  27883. };
  27884. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27885. var vertexData = new VertexData();
  27886. // positions
  27887. var positions = parsedVertexData.positions;
  27888. if (positions) {
  27889. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27890. }
  27891. // normals
  27892. var normals = parsedVertexData.normals;
  27893. if (normals) {
  27894. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27895. }
  27896. // uvs
  27897. var uvs = parsedVertexData.uvs;
  27898. if (uvs) {
  27899. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27900. }
  27901. // uv2s
  27902. var uv2s = parsedVertexData.uv2s;
  27903. if (uv2s) {
  27904. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27905. }
  27906. // uv3s
  27907. var uv3s = parsedVertexData.uv3s;
  27908. if (uv3s) {
  27909. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27910. }
  27911. // uv4s
  27912. var uv4s = parsedVertexData.uv4s;
  27913. if (uv4s) {
  27914. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27915. }
  27916. // uv5s
  27917. var uv5s = parsedVertexData.uv5s;
  27918. if (uv5s) {
  27919. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27920. }
  27921. // uv6s
  27922. var uv6s = parsedVertexData.uv6s;
  27923. if (uv6s) {
  27924. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27925. }
  27926. // colors
  27927. var colors = parsedVertexData.colors;
  27928. if (colors) {
  27929. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27930. }
  27931. // matricesIndices
  27932. var matricesIndices = parsedVertexData.matricesIndices;
  27933. if (matricesIndices) {
  27934. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27935. }
  27936. // matricesWeights
  27937. var matricesWeights = parsedVertexData.matricesWeights;
  27938. if (matricesWeights) {
  27939. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27940. }
  27941. // indices
  27942. var indices = parsedVertexData.indices;
  27943. if (indices) {
  27944. vertexData.indices = indices;
  27945. }
  27946. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27947. };
  27948. return VertexData;
  27949. })();
  27950. BABYLON.VertexData = VertexData;
  27951. })(BABYLON || (BABYLON = {}));
  27952. var BABYLON;
  27953. (function (BABYLON) {
  27954. var Tags = (function () {
  27955. function Tags() {
  27956. }
  27957. Tags.EnableFor = function (obj) {
  27958. obj._tags = obj._tags || {};
  27959. obj.hasTags = function () {
  27960. return Tags.HasTags(obj);
  27961. };
  27962. obj.addTags = function (tagsString) {
  27963. return Tags.AddTagsTo(obj, tagsString);
  27964. };
  27965. obj.removeTags = function (tagsString) {
  27966. return Tags.RemoveTagsFrom(obj, tagsString);
  27967. };
  27968. obj.matchesTagsQuery = function (tagsQuery) {
  27969. return Tags.MatchesQuery(obj, tagsQuery);
  27970. };
  27971. };
  27972. Tags.DisableFor = function (obj) {
  27973. delete obj._tags;
  27974. delete obj.hasTags;
  27975. delete obj.addTags;
  27976. delete obj.removeTags;
  27977. delete obj.matchesTagsQuery;
  27978. };
  27979. Tags.HasTags = function (obj) {
  27980. if (!obj._tags) {
  27981. return false;
  27982. }
  27983. return !BABYLON.Tools.IsEmpty(obj._tags);
  27984. };
  27985. Tags.GetTags = function (obj, asString) {
  27986. if (asString === void 0) { asString = true; }
  27987. if (!obj._tags) {
  27988. return null;
  27989. }
  27990. if (asString) {
  27991. var tagsArray = [];
  27992. for (var tag in obj._tags) {
  27993. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  27994. tagsArray.push(tag);
  27995. }
  27996. }
  27997. return tagsArray.join(" ");
  27998. }
  27999. else {
  28000. return obj._tags;
  28001. }
  28002. };
  28003. // the tags 'true' and 'false' are reserved and cannot be used as tags
  28004. // a tag cannot start with '||', '&&', and '!'
  28005. // it cannot contain whitespaces
  28006. Tags.AddTagsTo = function (obj, tagsString) {
  28007. if (!tagsString) {
  28008. return;
  28009. }
  28010. if (typeof tagsString !== "string") {
  28011. return;
  28012. }
  28013. var tags = tagsString.split(" ");
  28014. for (var t in tags) {
  28015. Tags._AddTagTo(obj, tags[t]);
  28016. }
  28017. };
  28018. Tags._AddTagTo = function (obj, tag) {
  28019. tag = tag.trim();
  28020. if (tag === "" || tag === "true" || tag === "false") {
  28021. return;
  28022. }
  28023. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  28024. return;
  28025. }
  28026. Tags.EnableFor(obj);
  28027. obj._tags[tag] = true;
  28028. };
  28029. Tags.RemoveTagsFrom = function (obj, tagsString) {
  28030. if (!Tags.HasTags(obj)) {
  28031. return;
  28032. }
  28033. var tags = tagsString.split(" ");
  28034. for (var t in tags) {
  28035. Tags._RemoveTagFrom(obj, tags[t]);
  28036. }
  28037. };
  28038. Tags._RemoveTagFrom = function (obj, tag) {
  28039. delete obj._tags[tag];
  28040. };
  28041. Tags.MatchesQuery = function (obj, tagsQuery) {
  28042. if (tagsQuery === undefined) {
  28043. return true;
  28044. }
  28045. if (tagsQuery === "") {
  28046. return Tags.HasTags(obj);
  28047. }
  28048. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  28049. };
  28050. return Tags;
  28051. })();
  28052. BABYLON.Tags = Tags;
  28053. })(BABYLON || (BABYLON = {}));
  28054. var BABYLON;
  28055. (function (BABYLON) {
  28056. var Internals;
  28057. (function (Internals) {
  28058. var AndOrNotEvaluator = (function () {
  28059. function AndOrNotEvaluator() {
  28060. }
  28061. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  28062. if (!query.match(/\([^\(\)]*\)/g)) {
  28063. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  28064. }
  28065. else {
  28066. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  28067. // remove parenthesis
  28068. r = r.slice(1, r.length - 1);
  28069. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  28070. });
  28071. }
  28072. if (query === "true") {
  28073. return true;
  28074. }
  28075. if (query === "false") {
  28076. return false;
  28077. }
  28078. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  28079. };
  28080. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  28081. evaluateCallback = evaluateCallback || (function (r) {
  28082. return r === "true" ? true : false;
  28083. });
  28084. var result;
  28085. var or = parenthesisContent.split("||");
  28086. for (var i in or) {
  28087. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  28088. var and = ori.split("&&");
  28089. if (and.length > 1) {
  28090. for (var j = 0; j < and.length; ++j) {
  28091. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  28092. if (andj !== "true" && andj !== "false") {
  28093. if (andj[0] === "!") {
  28094. result = !evaluateCallback(andj.substring(1));
  28095. }
  28096. else {
  28097. result = evaluateCallback(andj);
  28098. }
  28099. }
  28100. else {
  28101. result = andj === "true" ? true : false;
  28102. }
  28103. if (!result) {
  28104. ori = "false";
  28105. break;
  28106. }
  28107. }
  28108. }
  28109. if (result || ori === "true") {
  28110. result = true;
  28111. break;
  28112. }
  28113. // result equals false (or undefined)
  28114. if (ori !== "true" && ori !== "false") {
  28115. if (ori[0] === "!") {
  28116. result = !evaluateCallback(ori.substring(1));
  28117. }
  28118. else {
  28119. result = evaluateCallback(ori);
  28120. }
  28121. }
  28122. else {
  28123. result = ori === "true" ? true : false;
  28124. }
  28125. }
  28126. // the whole parenthesis scope is replaced by 'true' or 'false'
  28127. return result ? "true" : "false";
  28128. };
  28129. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  28130. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  28131. // remove whitespaces
  28132. r = r.replace(/[\s]/g, function () { return ""; });
  28133. return r.length % 2 ? "!" : "";
  28134. });
  28135. booleanString = booleanString.trim();
  28136. if (booleanString === "!true") {
  28137. booleanString = "false";
  28138. }
  28139. else if (booleanString === "!false") {
  28140. booleanString = "true";
  28141. }
  28142. return booleanString;
  28143. };
  28144. return AndOrNotEvaluator;
  28145. })();
  28146. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  28147. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28148. })(BABYLON || (BABYLON = {}));
  28149. var BABYLON;
  28150. (function (BABYLON) {
  28151. var PostProcessRenderPass = (function () {
  28152. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  28153. this._enabled = true;
  28154. this._refCount = 0;
  28155. this._name = name;
  28156. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  28157. this.setRenderList(renderList);
  28158. this._renderTexture.onBeforeRender = beforeRender;
  28159. this._renderTexture.onAfterRender = afterRender;
  28160. this._scene = scene;
  28161. this._renderList = renderList;
  28162. }
  28163. // private
  28164. PostProcessRenderPass.prototype._incRefCount = function () {
  28165. if (this._refCount === 0) {
  28166. this._scene.customRenderTargets.push(this._renderTexture);
  28167. }
  28168. return ++this._refCount;
  28169. };
  28170. PostProcessRenderPass.prototype._decRefCount = function () {
  28171. this._refCount--;
  28172. if (this._refCount <= 0) {
  28173. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  28174. }
  28175. return this._refCount;
  28176. };
  28177. PostProcessRenderPass.prototype._update = function () {
  28178. this.setRenderList(this._renderList);
  28179. };
  28180. // public
  28181. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  28182. this._renderTexture.renderList = renderList;
  28183. };
  28184. PostProcessRenderPass.prototype.getRenderTexture = function () {
  28185. return this._renderTexture;
  28186. };
  28187. return PostProcessRenderPass;
  28188. })();
  28189. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  28190. })(BABYLON || (BABYLON = {}));
  28191. var BABYLON;
  28192. (function (BABYLON) {
  28193. var PostProcessRenderEffect = (function () {
  28194. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  28195. this._engine = engine;
  28196. this._name = name;
  28197. this._singleInstance = singleInstance || true;
  28198. this._getPostProcess = getPostProcess;
  28199. this._cameras = [];
  28200. this._indicesForCamera = [];
  28201. this._postProcesses = {};
  28202. this._renderPasses = {};
  28203. this._renderEffectAsPasses = {};
  28204. }
  28205. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  28206. get: function () {
  28207. for (var index in this._postProcesses) {
  28208. if (!this._postProcesses[index].isSupported) {
  28209. return false;
  28210. }
  28211. }
  28212. return true;
  28213. },
  28214. enumerable: true,
  28215. configurable: true
  28216. });
  28217. PostProcessRenderEffect.prototype._update = function () {
  28218. for (var renderPassName in this._renderPasses) {
  28219. this._renderPasses[renderPassName]._update();
  28220. }
  28221. };
  28222. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  28223. this._renderPasses[renderPass._name] = renderPass;
  28224. this._linkParameters();
  28225. };
  28226. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  28227. delete this._renderPasses[renderPass._name];
  28228. this._linkParameters();
  28229. };
  28230. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  28231. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  28232. this._linkParameters();
  28233. };
  28234. PostProcessRenderEffect.prototype.getPass = function (passName) {
  28235. for (var renderPassName in this._renderPasses) {
  28236. if (renderPassName === passName) {
  28237. return this._renderPasses[passName];
  28238. }
  28239. }
  28240. };
  28241. PostProcessRenderEffect.prototype.emptyPasses = function () {
  28242. this._renderPasses = {};
  28243. this._linkParameters();
  28244. };
  28245. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  28246. var cameraKey;
  28247. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28248. for (var i = 0; i < _cam.length; i++) {
  28249. var camera = _cam[i];
  28250. var cameraName = camera.name;
  28251. if (this._singleInstance) {
  28252. cameraKey = 0;
  28253. }
  28254. else {
  28255. cameraKey = cameraName;
  28256. }
  28257. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  28258. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  28259. if (!this._indicesForCamera[cameraName]) {
  28260. this._indicesForCamera[cameraName] = [];
  28261. }
  28262. this._indicesForCamera[cameraName].push(index);
  28263. if (this._cameras.indexOf(camera) === -1) {
  28264. this._cameras[cameraName] = camera;
  28265. }
  28266. for (var passName in this._renderPasses) {
  28267. this._renderPasses[passName]._incRefCount();
  28268. }
  28269. }
  28270. this._linkParameters();
  28271. };
  28272. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  28273. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28274. for (var i = 0; i < _cam.length; i++) {
  28275. var camera = _cam[i];
  28276. var cameraName = camera.name;
  28277. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28278. var index = this._cameras.indexOf(cameraName);
  28279. this._indicesForCamera.splice(index, 1);
  28280. this._cameras.splice(index, 1);
  28281. for (var passName in this._renderPasses) {
  28282. this._renderPasses[passName]._decRefCount();
  28283. }
  28284. }
  28285. };
  28286. PostProcessRenderEffect.prototype._enable = function (cameras) {
  28287. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28288. for (var i = 0; i < _cam.length; i++) {
  28289. var camera = _cam[i];
  28290. var cameraName = camera.name;
  28291. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  28292. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  28293. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  28294. }
  28295. }
  28296. for (var passName in this._renderPasses) {
  28297. this._renderPasses[passName]._incRefCount();
  28298. }
  28299. }
  28300. };
  28301. PostProcessRenderEffect.prototype._disable = function (cameras) {
  28302. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28303. for (var i = 0; i < _cam.length; i++) {
  28304. var camera = _cam[i];
  28305. var cameraName = camera.Name;
  28306. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28307. for (var passName in this._renderPasses) {
  28308. this._renderPasses[passName]._decRefCount();
  28309. }
  28310. }
  28311. };
  28312. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  28313. if (this._singleInstance) {
  28314. return this._postProcesses[0];
  28315. }
  28316. else {
  28317. return this._postProcesses[camera.name];
  28318. }
  28319. };
  28320. PostProcessRenderEffect.prototype._linkParameters = function () {
  28321. var _this = this;
  28322. for (var index in this._postProcesses) {
  28323. if (this.applyParameters) {
  28324. this.applyParameters(this._postProcesses[index]);
  28325. }
  28326. this._postProcesses[index].onBeforeRender = function (effect) {
  28327. _this._linkTextures(effect);
  28328. };
  28329. }
  28330. };
  28331. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  28332. for (var renderPassName in this._renderPasses) {
  28333. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  28334. }
  28335. for (var renderEffectName in this._renderEffectAsPasses) {
  28336. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  28337. }
  28338. };
  28339. return PostProcessRenderEffect;
  28340. })();
  28341. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  28342. })(BABYLON || (BABYLON = {}));
  28343. var BABYLON;
  28344. (function (BABYLON) {
  28345. var PostProcessRenderPipeline = (function () {
  28346. function PostProcessRenderPipeline(engine, name) {
  28347. this._engine = engine;
  28348. this._name = name;
  28349. this._renderEffects = {};
  28350. this._renderEffectsForIsolatedPass = {};
  28351. this._cameras = [];
  28352. }
  28353. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  28354. get: function () {
  28355. for (var renderEffectName in this._renderEffects) {
  28356. if (!this._renderEffects[renderEffectName].isSupported) {
  28357. return false;
  28358. }
  28359. }
  28360. return true;
  28361. },
  28362. enumerable: true,
  28363. configurable: true
  28364. });
  28365. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  28366. this._renderEffects[renderEffect._name] = renderEffect;
  28367. };
  28368. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  28369. var renderEffects = this._renderEffects[renderEffectName];
  28370. if (!renderEffects) {
  28371. return;
  28372. }
  28373. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28374. };
  28375. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  28376. var renderEffects = this._renderEffects[renderEffectName];
  28377. if (!renderEffects) {
  28378. return;
  28379. }
  28380. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28381. };
  28382. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  28383. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28384. var indicesToDelete = [];
  28385. var i;
  28386. for (i = 0; i < _cam.length; i++) {
  28387. var camera = _cam[i];
  28388. var cameraName = camera.name;
  28389. if (this._cameras.indexOf(camera) === -1) {
  28390. this._cameras[cameraName] = camera;
  28391. }
  28392. else if (unique) {
  28393. indicesToDelete.push(i);
  28394. }
  28395. }
  28396. for (i = 0; i < indicesToDelete.length; i++) {
  28397. cameras.splice(indicesToDelete[i], 1);
  28398. }
  28399. for (var renderEffectName in this._renderEffects) {
  28400. this._renderEffects[renderEffectName]._attachCameras(_cam);
  28401. }
  28402. };
  28403. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  28404. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28405. for (var renderEffectName in this._renderEffects) {
  28406. this._renderEffects[renderEffectName]._detachCameras(_cam);
  28407. }
  28408. for (var i = 0; i < _cam.length; i++) {
  28409. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  28410. }
  28411. };
  28412. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  28413. var _this = this;
  28414. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28415. var pass = null;
  28416. var renderEffectName;
  28417. for (renderEffectName in this._renderEffects) {
  28418. pass = this._renderEffects[renderEffectName].getPass(passName);
  28419. if (pass != null) {
  28420. break;
  28421. }
  28422. }
  28423. if (pass === null) {
  28424. return;
  28425. }
  28426. for (renderEffectName in this._renderEffects) {
  28427. this._renderEffects[renderEffectName]._disable(_cam);
  28428. }
  28429. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  28430. for (var i = 0; i < _cam.length; i++) {
  28431. var camera = _cam[i];
  28432. var cameraName = camera.name;
  28433. 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); });
  28434. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  28435. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  28436. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  28437. }
  28438. };
  28439. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  28440. var _this = this;
  28441. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28442. for (var i = 0; i < _cam.length; i++) {
  28443. var camera = _cam[i];
  28444. var cameraName = camera.name;
  28445. 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); });
  28446. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  28447. }
  28448. for (var renderEffectName in this._renderEffects) {
  28449. this._renderEffects[renderEffectName]._enable(_cam);
  28450. }
  28451. };
  28452. PostProcessRenderPipeline.prototype._update = function () {
  28453. for (var renderEffectName in this._renderEffects) {
  28454. this._renderEffects[renderEffectName]._update();
  28455. }
  28456. for (var i = 0; i < this._cameras.length; i++) {
  28457. var cameraName = this._cameras[i].name;
  28458. if (this._renderEffectsForIsolatedPass[cameraName]) {
  28459. this._renderEffectsForIsolatedPass[cameraName]._update();
  28460. }
  28461. }
  28462. };
  28463. PostProcessRenderPipeline.prototype.dispose = function () {
  28464. // Must be implemented by children
  28465. };
  28466. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  28467. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  28468. return PostProcessRenderPipeline;
  28469. })();
  28470. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  28471. })(BABYLON || (BABYLON = {}));
  28472. var BABYLON;
  28473. (function (BABYLON) {
  28474. var PostProcessRenderPipelineManager = (function () {
  28475. function PostProcessRenderPipelineManager() {
  28476. this._renderPipelines = {};
  28477. }
  28478. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  28479. this._renderPipelines[renderPipeline._name] = renderPipeline;
  28480. };
  28481. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  28482. var renderPipeline = this._renderPipelines[renderPipelineName];
  28483. if (!renderPipeline) {
  28484. return;
  28485. }
  28486. renderPipeline._attachCameras(cameras, unique);
  28487. };
  28488. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  28489. var renderPipeline = this._renderPipelines[renderPipelineName];
  28490. if (!renderPipeline) {
  28491. return;
  28492. }
  28493. renderPipeline._detachCameras(cameras);
  28494. };
  28495. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28496. var renderPipeline = this._renderPipelines[renderPipelineName];
  28497. if (!renderPipeline) {
  28498. return;
  28499. }
  28500. renderPipeline._enableEffect(renderEffectName, cameras);
  28501. };
  28502. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28503. var renderPipeline = this._renderPipelines[renderPipelineName];
  28504. if (!renderPipeline) {
  28505. return;
  28506. }
  28507. renderPipeline._disableEffect(renderEffectName, cameras);
  28508. };
  28509. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  28510. var renderPipeline = this._renderPipelines[renderPipelineName];
  28511. if (!renderPipeline) {
  28512. return;
  28513. }
  28514. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  28515. };
  28516. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  28517. var renderPipeline = this._renderPipelines[renderPipelineName];
  28518. if (!renderPipeline) {
  28519. return;
  28520. }
  28521. renderPipeline._disableDisplayOnlyPass(cameras);
  28522. };
  28523. PostProcessRenderPipelineManager.prototype.update = function () {
  28524. for (var renderPipelineName in this._renderPipelines) {
  28525. var pipeline = this._renderPipelines[renderPipelineName];
  28526. if (!pipeline.isSupported) {
  28527. pipeline.dispose();
  28528. delete this._renderPipelines[renderPipelineName];
  28529. }
  28530. else {
  28531. pipeline._update();
  28532. }
  28533. }
  28534. };
  28535. return PostProcessRenderPipelineManager;
  28536. })();
  28537. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  28538. })(BABYLON || (BABYLON = {}));
  28539. var BABYLON;
  28540. (function (BABYLON) {
  28541. var BoundingBoxRenderer = (function () {
  28542. function BoundingBoxRenderer(scene) {
  28543. this.frontColor = new BABYLON.Color3(1, 1, 1);
  28544. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  28545. this.showBackLines = true;
  28546. this.renderList = new BABYLON.SmartArray(32);
  28547. this._scene = scene;
  28548. }
  28549. BoundingBoxRenderer.prototype._prepareRessources = function () {
  28550. if (this._colorShader) {
  28551. return;
  28552. }
  28553. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  28554. attributes: ["position"],
  28555. uniforms: ["worldViewProjection", "color"]
  28556. });
  28557. var engine = this._scene.getEngine();
  28558. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  28559. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  28560. 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]);
  28561. };
  28562. BoundingBoxRenderer.prototype.reset = function () {
  28563. this.renderList.reset();
  28564. };
  28565. BoundingBoxRenderer.prototype.render = function () {
  28566. if (this.renderList.length === 0) {
  28567. return;
  28568. }
  28569. this._prepareRessources();
  28570. if (!this._colorShader.isReady()) {
  28571. return;
  28572. }
  28573. var engine = this._scene.getEngine();
  28574. engine.setDepthWrite(false);
  28575. this._colorShader._preBind();
  28576. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  28577. var boundingBox = this.renderList.data[boundingBoxIndex];
  28578. var min = boundingBox.minimum;
  28579. var max = boundingBox.maximum;
  28580. var diff = max.subtract(min);
  28581. var median = min.add(diff.scale(0.5));
  28582. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  28583. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  28584. .multiply(boundingBox.getWorldMatrix());
  28585. // VBOs
  28586. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  28587. if (this.showBackLines) {
  28588. // Back
  28589. engine.setDepthFunctionToGreaterOrEqual();
  28590. this._scene.resetCachedMaterial();
  28591. this._colorShader.setColor4("color", this.backColor.toColor4());
  28592. this._colorShader.bind(worldMatrix);
  28593. // Draw order
  28594. engine.draw(false, 0, 24);
  28595. }
  28596. // Front
  28597. engine.setDepthFunctionToLess();
  28598. this._scene.resetCachedMaterial();
  28599. this._colorShader.setColor4("color", this.frontColor.toColor4());
  28600. this._colorShader.bind(worldMatrix);
  28601. // Draw order
  28602. engine.draw(false, 0, 24);
  28603. }
  28604. this._colorShader.unbind();
  28605. engine.setDepthFunctionToLessOrEqual();
  28606. engine.setDepthWrite(true);
  28607. };
  28608. BoundingBoxRenderer.prototype.dispose = function () {
  28609. if (!this._colorShader) {
  28610. return;
  28611. }
  28612. this._colorShader.dispose();
  28613. this._vb.dispose();
  28614. this._scene.getEngine()._releaseBuffer(this._ib);
  28615. };
  28616. return BoundingBoxRenderer;
  28617. })();
  28618. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  28619. })(BABYLON || (BABYLON = {}));
  28620. var BABYLON;
  28621. (function (BABYLON) {
  28622. var Condition = (function () {
  28623. function Condition(actionManager) {
  28624. this._actionManager = actionManager;
  28625. }
  28626. Condition.prototype.isValid = function () {
  28627. return true;
  28628. };
  28629. Condition.prototype._getProperty = function (propertyPath) {
  28630. return this._actionManager._getProperty(propertyPath);
  28631. };
  28632. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  28633. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28634. };
  28635. return Condition;
  28636. })();
  28637. BABYLON.Condition = Condition;
  28638. var ValueCondition = (function (_super) {
  28639. __extends(ValueCondition, _super);
  28640. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  28641. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  28642. _super.call(this, actionManager);
  28643. this.propertyPath = propertyPath;
  28644. this.value = value;
  28645. this.operator = operator;
  28646. this._target = this._getEffectiveTarget(target, this.propertyPath);
  28647. this._property = this._getProperty(this.propertyPath);
  28648. }
  28649. Object.defineProperty(ValueCondition, "IsEqual", {
  28650. get: function () {
  28651. return ValueCondition._IsEqual;
  28652. },
  28653. enumerable: true,
  28654. configurable: true
  28655. });
  28656. Object.defineProperty(ValueCondition, "IsDifferent", {
  28657. get: function () {
  28658. return ValueCondition._IsDifferent;
  28659. },
  28660. enumerable: true,
  28661. configurable: true
  28662. });
  28663. Object.defineProperty(ValueCondition, "IsGreater", {
  28664. get: function () {
  28665. return ValueCondition._IsGreater;
  28666. },
  28667. enumerable: true,
  28668. configurable: true
  28669. });
  28670. Object.defineProperty(ValueCondition, "IsLesser", {
  28671. get: function () {
  28672. return ValueCondition._IsLesser;
  28673. },
  28674. enumerable: true,
  28675. configurable: true
  28676. });
  28677. // Methods
  28678. ValueCondition.prototype.isValid = function () {
  28679. switch (this.operator) {
  28680. case ValueCondition.IsGreater:
  28681. return this._target[this._property] > this.value;
  28682. case ValueCondition.IsLesser:
  28683. return this._target[this._property] < this.value;
  28684. case ValueCondition.IsEqual:
  28685. case ValueCondition.IsDifferent:
  28686. var check;
  28687. if (this.value.equals) {
  28688. check = this.value.equals(this._target[this._property]);
  28689. }
  28690. else {
  28691. check = this.value === this._target[this._property];
  28692. }
  28693. return this.operator === ValueCondition.IsEqual ? check : !check;
  28694. }
  28695. return false;
  28696. };
  28697. // Statics
  28698. ValueCondition._IsEqual = 0;
  28699. ValueCondition._IsDifferent = 1;
  28700. ValueCondition._IsGreater = 2;
  28701. ValueCondition._IsLesser = 3;
  28702. return ValueCondition;
  28703. })(Condition);
  28704. BABYLON.ValueCondition = ValueCondition;
  28705. var PredicateCondition = (function (_super) {
  28706. __extends(PredicateCondition, _super);
  28707. function PredicateCondition(actionManager, predicate) {
  28708. _super.call(this, actionManager);
  28709. this.predicate = predicate;
  28710. }
  28711. PredicateCondition.prototype.isValid = function () {
  28712. return this.predicate();
  28713. };
  28714. return PredicateCondition;
  28715. })(Condition);
  28716. BABYLON.PredicateCondition = PredicateCondition;
  28717. var StateCondition = (function (_super) {
  28718. __extends(StateCondition, _super);
  28719. function StateCondition(actionManager, target, value) {
  28720. _super.call(this, actionManager);
  28721. this.value = value;
  28722. this._target = target;
  28723. }
  28724. // Methods
  28725. StateCondition.prototype.isValid = function () {
  28726. return this._target.state === this.value;
  28727. };
  28728. return StateCondition;
  28729. })(Condition);
  28730. BABYLON.StateCondition = StateCondition;
  28731. })(BABYLON || (BABYLON = {}));
  28732. var BABYLON;
  28733. (function (BABYLON) {
  28734. var Action = (function () {
  28735. function Action(triggerOptions, condition) {
  28736. this.triggerOptions = triggerOptions;
  28737. if (triggerOptions.parameter) {
  28738. this.trigger = triggerOptions.trigger;
  28739. this._triggerParameter = triggerOptions.parameter;
  28740. }
  28741. else {
  28742. this.trigger = triggerOptions;
  28743. }
  28744. this._nextActiveAction = this;
  28745. this._condition = condition;
  28746. }
  28747. // Methods
  28748. Action.prototype._prepare = function () {
  28749. };
  28750. Action.prototype.getTriggerParameter = function () {
  28751. return this._triggerParameter;
  28752. };
  28753. Action.prototype._executeCurrent = function (evt) {
  28754. if (this._nextActiveAction._condition) {
  28755. var condition = this._nextActiveAction._condition;
  28756. var currentRenderId = this._actionManager.getScene().getRenderId();
  28757. // We cache the current evaluation for the current frame
  28758. if (condition._evaluationId === currentRenderId) {
  28759. if (!condition._currentResult) {
  28760. return;
  28761. }
  28762. }
  28763. else {
  28764. condition._evaluationId = currentRenderId;
  28765. if (!condition.isValid()) {
  28766. condition._currentResult = false;
  28767. return;
  28768. }
  28769. condition._currentResult = true;
  28770. }
  28771. }
  28772. this._nextActiveAction.execute(evt);
  28773. this.skipToNextActiveAction();
  28774. };
  28775. Action.prototype.execute = function (evt) {
  28776. };
  28777. Action.prototype.skipToNextActiveAction = function () {
  28778. if (this._nextActiveAction._child) {
  28779. if (!this._nextActiveAction._child._actionManager) {
  28780. this._nextActiveAction._child._actionManager = this._actionManager;
  28781. }
  28782. this._nextActiveAction = this._nextActiveAction._child;
  28783. }
  28784. else {
  28785. this._nextActiveAction = this;
  28786. }
  28787. };
  28788. Action.prototype.then = function (action) {
  28789. this._child = action;
  28790. action._actionManager = this._actionManager;
  28791. action._prepare();
  28792. return action;
  28793. };
  28794. Action.prototype._getProperty = function (propertyPath) {
  28795. return this._actionManager._getProperty(propertyPath);
  28796. };
  28797. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28798. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28799. };
  28800. return Action;
  28801. })();
  28802. BABYLON.Action = Action;
  28803. })(BABYLON || (BABYLON = {}));
  28804. var BABYLON;
  28805. (function (BABYLON) {
  28806. /**
  28807. * ActionEvent is the event beint sent when an action is triggered.
  28808. */
  28809. var ActionEvent = (function () {
  28810. /**
  28811. * @constructor
  28812. * @param source The mesh or sprite that triggered the action.
  28813. * @param pointerX The X mouse cursor position at the time of the event
  28814. * @param pointerY The Y mouse cursor position at the time of the event
  28815. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28816. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28817. */
  28818. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28819. this.source = source;
  28820. this.pointerX = pointerX;
  28821. this.pointerY = pointerY;
  28822. this.meshUnderPointer = meshUnderPointer;
  28823. this.sourceEvent = sourceEvent;
  28824. this.additionalData = additionalData;
  28825. }
  28826. /**
  28827. * Helper function to auto-create an ActionEvent from a source mesh.
  28828. * @param source The source mesh that triggered the event
  28829. * @param evt {Event} The original (browser) event
  28830. */
  28831. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28832. var scene = source.getScene();
  28833. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28834. };
  28835. /**
  28836. * Helper function to auto-create an ActionEvent from a source mesh.
  28837. * @param source The source sprite that triggered the event
  28838. * @param scene Scene associated with the sprite
  28839. * @param evt {Event} The original (browser) event
  28840. */
  28841. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  28842. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28843. };
  28844. /**
  28845. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28846. * @param scene the scene where the event occurred
  28847. * @param evt {Event} The original (browser) event
  28848. */
  28849. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28850. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28851. };
  28852. return ActionEvent;
  28853. })();
  28854. BABYLON.ActionEvent = ActionEvent;
  28855. /**
  28856. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28857. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28858. */
  28859. var ActionManager = (function () {
  28860. function ActionManager(scene) {
  28861. // Members
  28862. this.actions = new Array();
  28863. this._scene = scene;
  28864. scene._actionManagers.push(this);
  28865. }
  28866. Object.defineProperty(ActionManager, "NothingTrigger", {
  28867. get: function () {
  28868. return ActionManager._NothingTrigger;
  28869. },
  28870. enumerable: true,
  28871. configurable: true
  28872. });
  28873. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28874. get: function () {
  28875. return ActionManager._OnPickTrigger;
  28876. },
  28877. enumerable: true,
  28878. configurable: true
  28879. });
  28880. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28881. get: function () {
  28882. return ActionManager._OnLeftPickTrigger;
  28883. },
  28884. enumerable: true,
  28885. configurable: true
  28886. });
  28887. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28888. get: function () {
  28889. return ActionManager._OnRightPickTrigger;
  28890. },
  28891. enumerable: true,
  28892. configurable: true
  28893. });
  28894. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28895. get: function () {
  28896. return ActionManager._OnCenterPickTrigger;
  28897. },
  28898. enumerable: true,
  28899. configurable: true
  28900. });
  28901. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  28902. get: function () {
  28903. return ActionManager._OnPickDownTrigger;
  28904. },
  28905. enumerable: true,
  28906. configurable: true
  28907. });
  28908. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28909. get: function () {
  28910. return ActionManager._OnPickUpTrigger;
  28911. },
  28912. enumerable: true,
  28913. configurable: true
  28914. });
  28915. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  28916. /// This trigger will only be raised if you also declared a OnPickDown
  28917. get: function () {
  28918. return ActionManager._OnPickOutTrigger;
  28919. },
  28920. enumerable: true,
  28921. configurable: true
  28922. });
  28923. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  28924. get: function () {
  28925. return ActionManager._OnLongPressTrigger;
  28926. },
  28927. enumerable: true,
  28928. configurable: true
  28929. });
  28930. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28931. get: function () {
  28932. return ActionManager._OnPointerOverTrigger;
  28933. },
  28934. enumerable: true,
  28935. configurable: true
  28936. });
  28937. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28938. get: function () {
  28939. return ActionManager._OnPointerOutTrigger;
  28940. },
  28941. enumerable: true,
  28942. configurable: true
  28943. });
  28944. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28945. get: function () {
  28946. return ActionManager._OnEveryFrameTrigger;
  28947. },
  28948. enumerable: true,
  28949. configurable: true
  28950. });
  28951. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28952. get: function () {
  28953. return ActionManager._OnIntersectionEnterTrigger;
  28954. },
  28955. enumerable: true,
  28956. configurable: true
  28957. });
  28958. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28959. get: function () {
  28960. return ActionManager._OnIntersectionExitTrigger;
  28961. },
  28962. enumerable: true,
  28963. configurable: true
  28964. });
  28965. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28966. get: function () {
  28967. return ActionManager._OnKeyDownTrigger;
  28968. },
  28969. enumerable: true,
  28970. configurable: true
  28971. });
  28972. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28973. get: function () {
  28974. return ActionManager._OnKeyUpTrigger;
  28975. },
  28976. enumerable: true,
  28977. configurable: true
  28978. });
  28979. // Methods
  28980. ActionManager.prototype.dispose = function () {
  28981. var index = this._scene._actionManagers.indexOf(this);
  28982. if (index > -1) {
  28983. this._scene._actionManagers.splice(index, 1);
  28984. }
  28985. };
  28986. ActionManager.prototype.getScene = function () {
  28987. return this._scene;
  28988. };
  28989. /**
  28990. * Does this action manager handles actions of any of the given triggers
  28991. * @param {number[]} triggers - the triggers to be tested
  28992. * @return {boolean} whether one (or more) of the triggers is handeled
  28993. */
  28994. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28995. for (var index = 0; index < this.actions.length; index++) {
  28996. var action = this.actions[index];
  28997. if (triggers.indexOf(action.trigger) > -1) {
  28998. return true;
  28999. }
  29000. }
  29001. return false;
  29002. };
  29003. /**
  29004. * Does this action manager handles actions of a given trigger
  29005. * @param {number} trigger - the trigger to be tested
  29006. * @return {boolean} whether the trigger is handeled
  29007. */
  29008. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  29009. for (var index = 0; index < this.actions.length; index++) {
  29010. var action = this.actions[index];
  29011. if (action.trigger === trigger) {
  29012. return true;
  29013. }
  29014. }
  29015. return false;
  29016. };
  29017. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  29018. /**
  29019. * Does this action manager has pointer triggers
  29020. * @return {boolean} whether or not it has pointer triggers
  29021. */
  29022. get: function () {
  29023. for (var index = 0; index < this.actions.length; index++) {
  29024. var action = this.actions[index];
  29025. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  29026. return true;
  29027. }
  29028. }
  29029. return false;
  29030. },
  29031. enumerable: true,
  29032. configurable: true
  29033. });
  29034. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  29035. /**
  29036. * Does this action manager has pick triggers
  29037. * @return {boolean} whether or not it has pick triggers
  29038. */
  29039. get: function () {
  29040. for (var index = 0; index < this.actions.length; index++) {
  29041. var action = this.actions[index];
  29042. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  29043. return true;
  29044. }
  29045. }
  29046. return false;
  29047. },
  29048. enumerable: true,
  29049. configurable: true
  29050. });
  29051. /**
  29052. * Registers an action to this action manager
  29053. * @param {BABYLON.Action} action - the action to be registered
  29054. * @return {BABYLON.Action} the action amended (prepared) after registration
  29055. */
  29056. ActionManager.prototype.registerAction = function (action) {
  29057. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  29058. if (this.getScene().actionManager !== this) {
  29059. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  29060. return null;
  29061. }
  29062. }
  29063. this.actions.push(action);
  29064. action._actionManager = this;
  29065. action._prepare();
  29066. return action;
  29067. };
  29068. /**
  29069. * Process a specific trigger
  29070. * @param {number} trigger - the trigger to process
  29071. * @param evt {BABYLON.ActionEvent} the event details to be processed
  29072. */
  29073. ActionManager.prototype.processTrigger = function (trigger, evt) {
  29074. for (var index = 0; index < this.actions.length; index++) {
  29075. var action = this.actions[index];
  29076. if (action.trigger === trigger) {
  29077. if (trigger === ActionManager.OnKeyUpTrigger
  29078. || trigger === ActionManager.OnKeyDownTrigger) {
  29079. var parameter = action.getTriggerParameter();
  29080. if (parameter) {
  29081. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  29082. var actualkey = String.fromCharCode(unicode).toLowerCase();
  29083. if (actualkey !== parameter.toLowerCase()) {
  29084. continue;
  29085. }
  29086. }
  29087. }
  29088. action._executeCurrent(evt);
  29089. }
  29090. }
  29091. };
  29092. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  29093. var properties = propertyPath.split(".");
  29094. for (var index = 0; index < properties.length - 1; index++) {
  29095. target = target[properties[index]];
  29096. }
  29097. return target;
  29098. };
  29099. ActionManager.prototype._getProperty = function (propertyPath) {
  29100. var properties = propertyPath.split(".");
  29101. return properties[properties.length - 1];
  29102. };
  29103. ActionManager.Parse = function (parsedActions, object, scene) {
  29104. var actionManager = new BABYLON.ActionManager(scene);
  29105. if (object === null)
  29106. scene.actionManager = actionManager;
  29107. else
  29108. object.actionManager = actionManager;
  29109. // instanciate a new object
  29110. var instanciate = function (name, params) {
  29111. var newInstance = Object.create(BABYLON[name].prototype);
  29112. newInstance.constructor.apply(newInstance, params);
  29113. return newInstance;
  29114. };
  29115. var parseParameter = function (name, value, target, propertyPath) {
  29116. if (propertyPath === null) {
  29117. // String, boolean or float
  29118. var floatValue = parseFloat(value);
  29119. if (value === "true" || value === "false")
  29120. return value === "true";
  29121. else
  29122. return isNaN(floatValue) ? value : floatValue;
  29123. }
  29124. var effectiveTarget = propertyPath.split(".");
  29125. var values = value.split(",");
  29126. // Get effective Target
  29127. for (var i = 0; i < effectiveTarget.length; i++) {
  29128. target = target[effectiveTarget[i]];
  29129. }
  29130. // Return appropriate value with its type
  29131. if (typeof (target) === "boolean")
  29132. return values[0] === "true";
  29133. if (typeof (target) === "string")
  29134. return values[0];
  29135. // Parameters with multiple values such as Vector3 etc.
  29136. var split = new Array();
  29137. for (var i = 0; i < values.length; i++)
  29138. split.push(parseFloat(values[i]));
  29139. if (target instanceof BABYLON.Vector3)
  29140. return BABYLON.Vector3.FromArray(split);
  29141. if (target instanceof BABYLON.Vector4)
  29142. return BABYLON.Vector4.FromArray(split);
  29143. if (target instanceof BABYLON.Color3)
  29144. return BABYLON.Color3.FromArray(split);
  29145. if (target instanceof BABYLON.Color4)
  29146. return BABYLON.Color4.FromArray(split);
  29147. return parseFloat(values[0]);
  29148. };
  29149. // traverse graph per trigger
  29150. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  29151. if (combineArray === void 0) { combineArray = null; }
  29152. if (parsedAction.detached)
  29153. return;
  29154. var parameters = new Array();
  29155. var target = null;
  29156. var propertyPath = null;
  29157. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  29158. // Parameters
  29159. if (parsedAction.type === 2)
  29160. parameters.push(actionManager);
  29161. else
  29162. parameters.push(trigger);
  29163. if (combine) {
  29164. var actions = new Array();
  29165. for (var j = 0; j < parsedAction.combine.length; j++) {
  29166. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  29167. }
  29168. parameters.push(actions);
  29169. }
  29170. else {
  29171. for (var i = 0; i < parsedAction.properties.length; i++) {
  29172. var value = parsedAction.properties[i].value;
  29173. var name = parsedAction.properties[i].name;
  29174. var targetType = parsedAction.properties[i].targetType;
  29175. if (name === "target")
  29176. if (targetType !== null && targetType === "SceneProperties")
  29177. value = target = scene;
  29178. else
  29179. value = target = scene.getNodeByName(value);
  29180. else if (name === "parent")
  29181. value = scene.getNodeByName(value);
  29182. else if (name === "sound")
  29183. value = scene.getSoundByName(value);
  29184. else if (name !== "propertyPath") {
  29185. if (parsedAction.type === 2 && name === "operator")
  29186. value = BABYLON.ValueCondition[value];
  29187. else
  29188. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  29189. }
  29190. else {
  29191. propertyPath = value;
  29192. }
  29193. parameters.push(value);
  29194. }
  29195. }
  29196. if (combineArray === null) {
  29197. parameters.push(condition);
  29198. }
  29199. else {
  29200. parameters.push(null);
  29201. }
  29202. // If interpolate value action
  29203. if (parsedAction.name === "InterpolateValueAction") {
  29204. var param = parameters[parameters.length - 2];
  29205. parameters[parameters.length - 1] = param;
  29206. parameters[parameters.length - 2] = condition;
  29207. }
  29208. // Action or condition(s) and not CombineAction
  29209. var newAction = instanciate(parsedAction.name, parameters);
  29210. if (newAction instanceof BABYLON.Condition && condition !== null) {
  29211. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  29212. if (action)
  29213. action.then(nothing);
  29214. else
  29215. actionManager.registerAction(nothing);
  29216. action = nothing;
  29217. }
  29218. if (combineArray === null) {
  29219. if (newAction instanceof BABYLON.Condition) {
  29220. condition = newAction;
  29221. newAction = action;
  29222. }
  29223. else {
  29224. condition = null;
  29225. if (action)
  29226. action.then(newAction);
  29227. else
  29228. actionManager.registerAction(newAction);
  29229. }
  29230. }
  29231. else {
  29232. combineArray.push(newAction);
  29233. }
  29234. for (var i = 0; i < parsedAction.children.length; i++)
  29235. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  29236. };
  29237. // triggers
  29238. for (var i = 0; i < parsedActions.children.length; i++) {
  29239. var triggerParams;
  29240. var trigger = parsedActions.children[i];
  29241. if (trigger.properties.length > 0) {
  29242. var param = trigger.properties[0].value;
  29243. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  29244. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  29245. }
  29246. else
  29247. triggerParams = BABYLON.ActionManager[trigger.name];
  29248. for (var j = 0; j < trigger.children.length; j++) {
  29249. if (!trigger.detached)
  29250. traverse(trigger.children[j], triggerParams, null, null);
  29251. }
  29252. }
  29253. };
  29254. // Statics
  29255. ActionManager._NothingTrigger = 0;
  29256. ActionManager._OnPickTrigger = 1;
  29257. ActionManager._OnLeftPickTrigger = 2;
  29258. ActionManager._OnRightPickTrigger = 3;
  29259. ActionManager._OnCenterPickTrigger = 4;
  29260. ActionManager._OnPickDownTrigger = 5;
  29261. ActionManager._OnPickUpTrigger = 6;
  29262. ActionManager._OnLongPressTrigger = 7;
  29263. ActionManager._OnPointerOverTrigger = 8;
  29264. ActionManager._OnPointerOutTrigger = 9;
  29265. ActionManager._OnEveryFrameTrigger = 10;
  29266. ActionManager._OnIntersectionEnterTrigger = 11;
  29267. ActionManager._OnIntersectionExitTrigger = 12;
  29268. ActionManager._OnKeyDownTrigger = 13;
  29269. ActionManager._OnKeyUpTrigger = 14;
  29270. ActionManager._OnPickOutTrigger = 15;
  29271. ActionManager.DragMovementThreshold = 10; // in pixels
  29272. ActionManager.LongPressDelay = 500; // in milliseconds
  29273. return ActionManager;
  29274. })();
  29275. BABYLON.ActionManager = ActionManager;
  29276. })(BABYLON || (BABYLON = {}));
  29277. var BABYLON;
  29278. (function (BABYLON) {
  29279. var InterpolateValueAction = (function (_super) {
  29280. __extends(InterpolateValueAction, _super);
  29281. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  29282. if (duration === void 0) { duration = 1000; }
  29283. _super.call(this, triggerOptions, condition);
  29284. this.propertyPath = propertyPath;
  29285. this.value = value;
  29286. this.duration = duration;
  29287. this.stopOtherAnimations = stopOtherAnimations;
  29288. this.onInterpolationDone = onInterpolationDone;
  29289. this._target = target;
  29290. }
  29291. InterpolateValueAction.prototype._prepare = function () {
  29292. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29293. this._property = this._getProperty(this.propertyPath);
  29294. };
  29295. InterpolateValueAction.prototype.execute = function () {
  29296. var scene = this._actionManager.getScene();
  29297. var keys = [
  29298. {
  29299. frame: 0,
  29300. value: this._target[this._property]
  29301. }, {
  29302. frame: 100,
  29303. value: this.value
  29304. }
  29305. ];
  29306. var dataType;
  29307. if (typeof this.value === "number") {
  29308. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  29309. }
  29310. else if (this.value instanceof BABYLON.Color3) {
  29311. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  29312. }
  29313. else if (this.value instanceof BABYLON.Vector3) {
  29314. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  29315. }
  29316. else if (this.value instanceof BABYLON.Matrix) {
  29317. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  29318. }
  29319. else if (this.value instanceof BABYLON.Quaternion) {
  29320. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  29321. }
  29322. else {
  29323. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  29324. return;
  29325. }
  29326. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  29327. animation.setKeys(keys);
  29328. if (this.stopOtherAnimations) {
  29329. scene.stopAnimation(this._target);
  29330. }
  29331. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  29332. };
  29333. return InterpolateValueAction;
  29334. })(BABYLON.Action);
  29335. BABYLON.InterpolateValueAction = InterpolateValueAction;
  29336. })(BABYLON || (BABYLON = {}));
  29337. var BABYLON;
  29338. (function (BABYLON) {
  29339. var SwitchBooleanAction = (function (_super) {
  29340. __extends(SwitchBooleanAction, _super);
  29341. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  29342. _super.call(this, triggerOptions, condition);
  29343. this.propertyPath = propertyPath;
  29344. this._target = target;
  29345. }
  29346. SwitchBooleanAction.prototype._prepare = function () {
  29347. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29348. this._property = this._getProperty(this.propertyPath);
  29349. };
  29350. SwitchBooleanAction.prototype.execute = function () {
  29351. this._target[this._property] = !this._target[this._property];
  29352. };
  29353. return SwitchBooleanAction;
  29354. })(BABYLON.Action);
  29355. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  29356. var SetStateAction = (function (_super) {
  29357. __extends(SetStateAction, _super);
  29358. function SetStateAction(triggerOptions, target, value, condition) {
  29359. _super.call(this, triggerOptions, condition);
  29360. this.value = value;
  29361. this._target = target;
  29362. }
  29363. SetStateAction.prototype.execute = function () {
  29364. this._target.state = this.value;
  29365. };
  29366. return SetStateAction;
  29367. })(BABYLON.Action);
  29368. BABYLON.SetStateAction = SetStateAction;
  29369. var SetValueAction = (function (_super) {
  29370. __extends(SetValueAction, _super);
  29371. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  29372. _super.call(this, triggerOptions, condition);
  29373. this.propertyPath = propertyPath;
  29374. this.value = value;
  29375. this._target = target;
  29376. }
  29377. SetValueAction.prototype._prepare = function () {
  29378. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29379. this._property = this._getProperty(this.propertyPath);
  29380. };
  29381. SetValueAction.prototype.execute = function () {
  29382. this._target[this._property] = this.value;
  29383. };
  29384. return SetValueAction;
  29385. })(BABYLON.Action);
  29386. BABYLON.SetValueAction = SetValueAction;
  29387. var IncrementValueAction = (function (_super) {
  29388. __extends(IncrementValueAction, _super);
  29389. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  29390. _super.call(this, triggerOptions, condition);
  29391. this.propertyPath = propertyPath;
  29392. this.value = value;
  29393. this._target = target;
  29394. }
  29395. IncrementValueAction.prototype._prepare = function () {
  29396. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29397. this._property = this._getProperty(this.propertyPath);
  29398. if (typeof this._target[this._property] !== "number") {
  29399. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  29400. }
  29401. };
  29402. IncrementValueAction.prototype.execute = function () {
  29403. this._target[this._property] += this.value;
  29404. };
  29405. return IncrementValueAction;
  29406. })(BABYLON.Action);
  29407. BABYLON.IncrementValueAction = IncrementValueAction;
  29408. var PlayAnimationAction = (function (_super) {
  29409. __extends(PlayAnimationAction, _super);
  29410. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  29411. _super.call(this, triggerOptions, condition);
  29412. this.from = from;
  29413. this.to = to;
  29414. this.loop = loop;
  29415. this._target = target;
  29416. }
  29417. PlayAnimationAction.prototype._prepare = function () {
  29418. };
  29419. PlayAnimationAction.prototype.execute = function () {
  29420. var scene = this._actionManager.getScene();
  29421. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  29422. };
  29423. return PlayAnimationAction;
  29424. })(BABYLON.Action);
  29425. BABYLON.PlayAnimationAction = PlayAnimationAction;
  29426. var StopAnimationAction = (function (_super) {
  29427. __extends(StopAnimationAction, _super);
  29428. function StopAnimationAction(triggerOptions, target, condition) {
  29429. _super.call(this, triggerOptions, condition);
  29430. this._target = target;
  29431. }
  29432. StopAnimationAction.prototype._prepare = function () {
  29433. };
  29434. StopAnimationAction.prototype.execute = function () {
  29435. var scene = this._actionManager.getScene();
  29436. scene.stopAnimation(this._target);
  29437. };
  29438. return StopAnimationAction;
  29439. })(BABYLON.Action);
  29440. BABYLON.StopAnimationAction = StopAnimationAction;
  29441. var DoNothingAction = (function (_super) {
  29442. __extends(DoNothingAction, _super);
  29443. function DoNothingAction(triggerOptions, condition) {
  29444. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  29445. _super.call(this, triggerOptions, condition);
  29446. }
  29447. DoNothingAction.prototype.execute = function () {
  29448. };
  29449. return DoNothingAction;
  29450. })(BABYLON.Action);
  29451. BABYLON.DoNothingAction = DoNothingAction;
  29452. var CombineAction = (function (_super) {
  29453. __extends(CombineAction, _super);
  29454. function CombineAction(triggerOptions, children, condition) {
  29455. _super.call(this, triggerOptions, condition);
  29456. this.children = children;
  29457. }
  29458. CombineAction.prototype._prepare = function () {
  29459. for (var index = 0; index < this.children.length; index++) {
  29460. this.children[index]._actionManager = this._actionManager;
  29461. this.children[index]._prepare();
  29462. }
  29463. };
  29464. CombineAction.prototype.execute = function (evt) {
  29465. for (var index = 0; index < this.children.length; index++) {
  29466. this.children[index].execute(evt);
  29467. }
  29468. };
  29469. return CombineAction;
  29470. })(BABYLON.Action);
  29471. BABYLON.CombineAction = CombineAction;
  29472. var ExecuteCodeAction = (function (_super) {
  29473. __extends(ExecuteCodeAction, _super);
  29474. function ExecuteCodeAction(triggerOptions, func, condition) {
  29475. _super.call(this, triggerOptions, condition);
  29476. this.func = func;
  29477. }
  29478. ExecuteCodeAction.prototype.execute = function (evt) {
  29479. this.func(evt);
  29480. };
  29481. return ExecuteCodeAction;
  29482. })(BABYLON.Action);
  29483. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  29484. var SetParentAction = (function (_super) {
  29485. __extends(SetParentAction, _super);
  29486. function SetParentAction(triggerOptions, target, parent, condition) {
  29487. _super.call(this, triggerOptions, condition);
  29488. this._target = target;
  29489. this._parent = parent;
  29490. }
  29491. SetParentAction.prototype._prepare = function () {
  29492. };
  29493. SetParentAction.prototype.execute = function () {
  29494. if (this._target.parent === this._parent) {
  29495. return;
  29496. }
  29497. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  29498. invertParentWorldMatrix.invert();
  29499. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  29500. this._target.parent = this._parent;
  29501. };
  29502. return SetParentAction;
  29503. })(BABYLON.Action);
  29504. BABYLON.SetParentAction = SetParentAction;
  29505. var PlaySoundAction = (function (_super) {
  29506. __extends(PlaySoundAction, _super);
  29507. function PlaySoundAction(triggerOptions, sound, condition) {
  29508. _super.call(this, triggerOptions, condition);
  29509. this._sound = sound;
  29510. }
  29511. PlaySoundAction.prototype._prepare = function () {
  29512. };
  29513. PlaySoundAction.prototype.execute = function () {
  29514. if (this._sound !== undefined)
  29515. this._sound.play();
  29516. };
  29517. return PlaySoundAction;
  29518. })(BABYLON.Action);
  29519. BABYLON.PlaySoundAction = PlaySoundAction;
  29520. var StopSoundAction = (function (_super) {
  29521. __extends(StopSoundAction, _super);
  29522. function StopSoundAction(triggerOptions, sound, condition) {
  29523. _super.call(this, triggerOptions, condition);
  29524. this._sound = sound;
  29525. }
  29526. StopSoundAction.prototype._prepare = function () {
  29527. };
  29528. StopSoundAction.prototype.execute = function () {
  29529. if (this._sound !== undefined)
  29530. this._sound.stop();
  29531. };
  29532. return StopSoundAction;
  29533. })(BABYLON.Action);
  29534. BABYLON.StopSoundAction = StopSoundAction;
  29535. })(BABYLON || (BABYLON = {}));
  29536. var BABYLON;
  29537. (function (BABYLON) {
  29538. var Geometry = (function () {
  29539. function Geometry(id, scene, vertexData, updatable, mesh) {
  29540. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29541. this._totalVertices = 0;
  29542. this._isDisposed = false;
  29543. this.id = id;
  29544. this._engine = scene.getEngine();
  29545. this._meshes = [];
  29546. this._scene = scene;
  29547. //Init vertex buffer cache
  29548. this._vertexBuffers = {};
  29549. this._indices = [];
  29550. // vertexData
  29551. if (vertexData) {
  29552. this.setAllVerticesData(vertexData, updatable);
  29553. }
  29554. else {
  29555. this._totalVertices = 0;
  29556. this._indices = [];
  29557. }
  29558. // applyToMesh
  29559. if (mesh) {
  29560. this.applyToMesh(mesh);
  29561. mesh.computeWorldMatrix(true);
  29562. }
  29563. }
  29564. Object.defineProperty(Geometry.prototype, "extend", {
  29565. get: function () {
  29566. return this._extend;
  29567. },
  29568. enumerable: true,
  29569. configurable: true
  29570. });
  29571. Geometry.prototype.getScene = function () {
  29572. return this._scene;
  29573. };
  29574. Geometry.prototype.getEngine = function () {
  29575. return this._engine;
  29576. };
  29577. Geometry.prototype.isReady = function () {
  29578. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29579. };
  29580. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29581. vertexData.applyToGeometry(this, updatable);
  29582. this.notifyUpdate();
  29583. };
  29584. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29585. if (this._vertexBuffers[kind]) {
  29586. this._vertexBuffers[kind].dispose();
  29587. }
  29588. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29589. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29590. stride = this._vertexBuffers[kind].getStrideSize();
  29591. this._totalVertices = data.length / stride;
  29592. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29593. var meshes = this._meshes;
  29594. var numOfMeshes = meshes.length;
  29595. for (var index = 0; index < numOfMeshes; index++) {
  29596. var mesh = meshes[index];
  29597. mesh._resetPointsArrayCache();
  29598. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29599. mesh._createGlobalSubMesh();
  29600. mesh.computeWorldMatrix(true);
  29601. }
  29602. }
  29603. this.notifyUpdate(kind);
  29604. };
  29605. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29606. var vertexBuffer = this.getVertexBuffer(kind);
  29607. if (!vertexBuffer) {
  29608. return;
  29609. }
  29610. vertexBuffer.updateDirectly(data, offset);
  29611. this.notifyUpdate(kind);
  29612. };
  29613. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29614. var vertexBuffer = this.getVertexBuffer(kind);
  29615. if (!vertexBuffer) {
  29616. return;
  29617. }
  29618. vertexBuffer.update(data);
  29619. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29620. var stride = vertexBuffer.getStrideSize();
  29621. this._totalVertices = data.length / stride;
  29622. if (updateExtends) {
  29623. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29624. }
  29625. var meshes = this._meshes;
  29626. var numOfMeshes = meshes.length;
  29627. for (var index = 0; index < numOfMeshes; index++) {
  29628. var mesh = meshes[index];
  29629. mesh._resetPointsArrayCache();
  29630. if (updateExtends) {
  29631. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29632. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29633. var subMesh = mesh.subMeshes[subIndex];
  29634. subMesh.refreshBoundingInfo();
  29635. }
  29636. }
  29637. }
  29638. }
  29639. this.notifyUpdate(kind);
  29640. };
  29641. Geometry.prototype.getTotalVertices = function () {
  29642. if (!this.isReady()) {
  29643. return 0;
  29644. }
  29645. return this._totalVertices;
  29646. };
  29647. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  29648. var vertexBuffer = this.getVertexBuffer(kind);
  29649. if (!vertexBuffer) {
  29650. return null;
  29651. }
  29652. var orig = vertexBuffer.getData();
  29653. if (!copyWhenShared || this._meshes.length === 1) {
  29654. return orig;
  29655. }
  29656. else {
  29657. var len = orig.length;
  29658. var copy = [];
  29659. for (var i = 0; i < len; i++) {
  29660. copy.push(orig[i]);
  29661. }
  29662. return copy;
  29663. }
  29664. };
  29665. Geometry.prototype.getVertexBuffer = function (kind) {
  29666. if (!this.isReady()) {
  29667. return null;
  29668. }
  29669. return this._vertexBuffers[kind];
  29670. };
  29671. Geometry.prototype.getVertexBuffers = function () {
  29672. if (!this.isReady()) {
  29673. return null;
  29674. }
  29675. return this._vertexBuffers;
  29676. };
  29677. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29678. if (!this._vertexBuffers) {
  29679. if (this._delayInfo) {
  29680. return this._delayInfo.indexOf(kind) !== -1;
  29681. }
  29682. return false;
  29683. }
  29684. return this._vertexBuffers[kind] !== undefined;
  29685. };
  29686. Geometry.prototype.getVerticesDataKinds = function () {
  29687. var result = [];
  29688. var kind;
  29689. if (!this._vertexBuffers && this._delayInfo) {
  29690. for (kind in this._delayInfo) {
  29691. result.push(kind);
  29692. }
  29693. }
  29694. else {
  29695. for (kind in this._vertexBuffers) {
  29696. result.push(kind);
  29697. }
  29698. }
  29699. return result;
  29700. };
  29701. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29702. if (this._indexBuffer) {
  29703. this._engine._releaseBuffer(this._indexBuffer);
  29704. }
  29705. this._indices = indices;
  29706. if (this._meshes.length !== 0 && this._indices) {
  29707. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29708. }
  29709. if (totalVertices !== undefined) {
  29710. this._totalVertices = totalVertices;
  29711. }
  29712. var meshes = this._meshes;
  29713. var numOfMeshes = meshes.length;
  29714. for (var index = 0; index < numOfMeshes; index++) {
  29715. meshes[index]._createGlobalSubMesh();
  29716. }
  29717. this.notifyUpdate();
  29718. };
  29719. Geometry.prototype.getTotalIndices = function () {
  29720. if (!this.isReady()) {
  29721. return 0;
  29722. }
  29723. return this._indices.length;
  29724. };
  29725. Geometry.prototype.getIndices = function (copyWhenShared) {
  29726. if (!this.isReady()) {
  29727. return null;
  29728. }
  29729. var orig = this._indices;
  29730. if (!copyWhenShared || this._meshes.length === 1) {
  29731. return orig;
  29732. }
  29733. else {
  29734. var len = orig.length;
  29735. var copy = [];
  29736. for (var i = 0; i < len; i++) {
  29737. copy.push(orig[i]);
  29738. }
  29739. return copy;
  29740. }
  29741. };
  29742. Geometry.prototype.getIndexBuffer = function () {
  29743. if (!this.isReady()) {
  29744. return null;
  29745. }
  29746. return this._indexBuffer;
  29747. };
  29748. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29749. var meshes = this._meshes;
  29750. var index = meshes.indexOf(mesh);
  29751. if (index === -1) {
  29752. return;
  29753. }
  29754. for (var kind in this._vertexBuffers) {
  29755. this._vertexBuffers[kind].dispose();
  29756. }
  29757. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  29758. this._indexBuffer = null;
  29759. }
  29760. meshes.splice(index, 1);
  29761. mesh._geometry = null;
  29762. if (meshes.length === 0 && shouldDispose) {
  29763. this.dispose();
  29764. }
  29765. };
  29766. Geometry.prototype.applyToMesh = function (mesh) {
  29767. if (mesh._geometry === this) {
  29768. return;
  29769. }
  29770. var previousGeometry = mesh._geometry;
  29771. if (previousGeometry) {
  29772. previousGeometry.releaseForMesh(mesh);
  29773. }
  29774. var meshes = this._meshes;
  29775. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29776. mesh._geometry = this;
  29777. this._scene.pushGeometry(this);
  29778. meshes.push(mesh);
  29779. if (this.isReady()) {
  29780. this._applyToMesh(mesh);
  29781. }
  29782. else {
  29783. mesh._boundingInfo = this._boundingInfo;
  29784. }
  29785. };
  29786. Geometry.prototype._applyToMesh = function (mesh) {
  29787. var numOfMeshes = this._meshes.length;
  29788. // vertexBuffers
  29789. for (var kind in this._vertexBuffers) {
  29790. if (numOfMeshes === 1) {
  29791. this._vertexBuffers[kind].create();
  29792. }
  29793. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  29794. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29795. mesh._resetPointsArrayCache();
  29796. if (!this._extend) {
  29797. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  29798. }
  29799. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29800. mesh._createGlobalSubMesh();
  29801. //bounding info was just created again, world matrix should be applied again.
  29802. mesh._updateBoundingInfo();
  29803. }
  29804. }
  29805. // indexBuffer
  29806. if (numOfMeshes === 1 && this._indices) {
  29807. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29808. }
  29809. if (this._indexBuffer) {
  29810. this._indexBuffer.references = numOfMeshes;
  29811. }
  29812. };
  29813. Geometry.prototype.notifyUpdate = function (kind) {
  29814. if (this.onGeometryUpdated) {
  29815. this.onGeometryUpdated(this, kind);
  29816. }
  29817. };
  29818. Geometry.prototype.load = function (scene, onLoaded) {
  29819. var _this = this;
  29820. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29821. return;
  29822. }
  29823. if (this.isReady()) {
  29824. if (onLoaded) {
  29825. onLoaded();
  29826. }
  29827. return;
  29828. }
  29829. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29830. scene._addPendingData(this);
  29831. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29832. _this._delayLoadingFunction(JSON.parse(data), _this);
  29833. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29834. _this._delayInfo = [];
  29835. scene._removePendingData(_this);
  29836. var meshes = _this._meshes;
  29837. var numOfMeshes = meshes.length;
  29838. for (var index = 0; index < numOfMeshes; index++) {
  29839. _this._applyToMesh(meshes[index]);
  29840. }
  29841. if (onLoaded) {
  29842. onLoaded();
  29843. }
  29844. }, function () { }, scene.database);
  29845. };
  29846. Geometry.prototype.isDisposed = function () {
  29847. return this._isDisposed;
  29848. };
  29849. Geometry.prototype.dispose = function () {
  29850. var meshes = this._meshes;
  29851. var numOfMeshes = meshes.length;
  29852. var index;
  29853. for (index = 0; index < numOfMeshes; index++) {
  29854. this.releaseForMesh(meshes[index]);
  29855. }
  29856. this._meshes = [];
  29857. for (var kind in this._vertexBuffers) {
  29858. this._vertexBuffers[kind].dispose();
  29859. }
  29860. this._vertexBuffers = [];
  29861. this._totalVertices = 0;
  29862. if (this._indexBuffer) {
  29863. this._engine._releaseBuffer(this._indexBuffer);
  29864. }
  29865. this._indexBuffer = null;
  29866. this._indices = [];
  29867. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29868. this.delayLoadingFile = null;
  29869. this._delayLoadingFunction = null;
  29870. this._delayInfo = [];
  29871. this._boundingInfo = null;
  29872. this._scene.removeGeometry(this);
  29873. this._isDisposed = true;
  29874. };
  29875. Geometry.prototype.copy = function (id) {
  29876. var vertexData = new BABYLON.VertexData();
  29877. vertexData.indices = [];
  29878. var indices = this.getIndices();
  29879. for (var index = 0; index < indices.length; index++) {
  29880. vertexData.indices.push(indices[index]);
  29881. }
  29882. var updatable = false;
  29883. var stopChecking = false;
  29884. var kind;
  29885. for (kind in this._vertexBuffers) {
  29886. // using slice() to make a copy of the array and not just reference it
  29887. var data = this.getVerticesData(kind);
  29888. if (data instanceof Float32Array) {
  29889. vertexData.set(new Float32Array(data), kind);
  29890. }
  29891. else {
  29892. vertexData.set(data.slice(0), kind);
  29893. }
  29894. if (!stopChecking) {
  29895. updatable = this.getVertexBuffer(kind).isUpdatable();
  29896. stopChecking = !updatable;
  29897. }
  29898. }
  29899. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29900. geometry.delayLoadState = this.delayLoadState;
  29901. geometry.delayLoadingFile = this.delayLoadingFile;
  29902. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29903. for (kind in this._delayInfo) {
  29904. geometry._delayInfo = geometry._delayInfo || [];
  29905. geometry._delayInfo.push(kind);
  29906. }
  29907. // Bounding info
  29908. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29909. return geometry;
  29910. };
  29911. Geometry.prototype.serialize = function () {
  29912. var serializationObject = {};
  29913. serializationObject.id = this.id;
  29914. if (BABYLON.Tags.HasTags(this)) {
  29915. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29916. }
  29917. return serializationObject;
  29918. };
  29919. Geometry.prototype.serializeVerticeData = function () {
  29920. var serializationObject = this.serialize();
  29921. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29922. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29923. }
  29924. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29925. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29926. }
  29927. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29928. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29929. }
  29930. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29931. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29932. }
  29933. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29934. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29935. }
  29936. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29937. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29938. }
  29939. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29940. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29941. }
  29942. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29943. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29944. }
  29945. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29946. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29947. }
  29948. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29949. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29950. serializationObject.matricesIndices._isExpanded = true;
  29951. }
  29952. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29953. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29954. }
  29955. serializationObject.indices = this.getIndices();
  29956. return serializationObject;
  29957. };
  29958. // Statics
  29959. Geometry.ExtractFromMesh = function (mesh, id) {
  29960. var geometry = mesh._geometry;
  29961. if (!geometry) {
  29962. return null;
  29963. }
  29964. return geometry.copy(id);
  29965. };
  29966. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29967. // be aware Math.random() could cause collisions
  29968. Geometry.RandomId = function () {
  29969. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  29970. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  29971. return v.toString(16);
  29972. });
  29973. };
  29974. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29975. var scene = mesh.getScene();
  29976. // Geometry
  29977. var geometryId = parsedGeometry.geometryId;
  29978. if (geometryId) {
  29979. var geometry = scene.getGeometryByID(geometryId);
  29980. if (geometry) {
  29981. geometry.applyToMesh(mesh);
  29982. }
  29983. }
  29984. else if (parsedGeometry instanceof ArrayBuffer) {
  29985. var binaryInfo = mesh._binaryInfo;
  29986. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29987. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29988. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29989. }
  29990. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29991. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29992. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29993. }
  29994. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29995. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29996. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29997. }
  29998. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29999. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30000. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30001. }
  30002. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30003. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30004. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30005. }
  30006. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30007. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30008. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30009. }
  30010. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30011. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30012. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30013. }
  30014. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30015. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30016. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30017. }
  30018. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30019. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30020. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30021. }
  30022. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30023. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30024. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30025. }
  30026. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30027. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30028. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30029. }
  30030. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  30031. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  30032. mesh.setIndices(indicesData);
  30033. }
  30034. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  30035. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  30036. mesh.subMeshes = [];
  30037. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  30038. var materialIndex = subMeshesData[(i * 5) + 0];
  30039. var verticesStart = subMeshesData[(i * 5) + 1];
  30040. var verticesCount = subMeshesData[(i * 5) + 2];
  30041. var indexStart = subMeshesData[(i * 5) + 3];
  30042. var indexCount = subMeshesData[(i * 5) + 4];
  30043. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  30044. }
  30045. }
  30046. }
  30047. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  30048. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  30049. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  30050. if (parsedGeometry.uvs) {
  30051. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  30052. }
  30053. if (parsedGeometry.uvs2) {
  30054. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  30055. }
  30056. if (parsedGeometry.uvs3) {
  30057. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  30058. }
  30059. if (parsedGeometry.uvs4) {
  30060. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  30061. }
  30062. if (parsedGeometry.uvs5) {
  30063. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  30064. }
  30065. if (parsedGeometry.uvs6) {
  30066. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  30067. }
  30068. if (parsedGeometry.colors) {
  30069. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  30070. }
  30071. if (parsedGeometry.matricesIndices) {
  30072. if (!parsedGeometry.matricesIndices._isExpanded) {
  30073. var floatIndices = [];
  30074. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30075. var matricesIndex = parsedGeometry.matricesIndices[i];
  30076. floatIndices.push(matricesIndex & 0x000000FF);
  30077. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30078. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30079. floatIndices.push(matricesIndex >> 24);
  30080. }
  30081. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  30082. }
  30083. else {
  30084. delete parsedGeometry.matricesIndices._isExpanded;
  30085. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  30086. }
  30087. }
  30088. if (parsedGeometry.matricesIndicesExtra) {
  30089. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30090. var floatIndices = [];
  30091. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30092. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30093. floatIndices.push(matricesIndex & 0x000000FF);
  30094. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30095. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30096. floatIndices.push(matricesIndex >> 24);
  30097. }
  30098. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  30099. }
  30100. else {
  30101. delete parsedGeometry.matricesIndices._isExpanded;
  30102. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  30103. }
  30104. }
  30105. if (parsedGeometry.matricesWeights) {
  30106. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  30107. }
  30108. if (parsedGeometry.matricesWeightsExtra) {
  30109. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  30110. }
  30111. mesh.setIndices(parsedGeometry.indices);
  30112. }
  30113. // SubMeshes
  30114. if (parsedGeometry.subMeshes) {
  30115. mesh.subMeshes = [];
  30116. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30117. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30118. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30119. }
  30120. }
  30121. // Flat shading
  30122. if (mesh._shouldGenerateFlatShading) {
  30123. mesh.convertToFlatShadedMesh();
  30124. delete mesh._shouldGenerateFlatShading;
  30125. }
  30126. // Update
  30127. mesh.computeWorldMatrix(true);
  30128. // Octree
  30129. if (scene['_selectionOctree']) {
  30130. scene['_selectionOctree'].addMesh(mesh);
  30131. }
  30132. };
  30133. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  30134. if (scene.getGeometryByID(parsedVertexData.id)) {
  30135. return null; // null since geometry could be something else than a box...
  30136. }
  30137. var geometry = new Geometry(parsedVertexData.id, scene);
  30138. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  30139. if (parsedVertexData.delayLoadingFile) {
  30140. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30141. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  30142. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  30143. geometry._delayInfo = [];
  30144. if (parsedVertexData.hasUVs) {
  30145. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30146. }
  30147. if (parsedVertexData.hasUVs2) {
  30148. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30149. }
  30150. if (parsedVertexData.hasUVs3) {
  30151. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30152. }
  30153. if (parsedVertexData.hasUVs4) {
  30154. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30155. }
  30156. if (parsedVertexData.hasUVs5) {
  30157. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30158. }
  30159. if (parsedVertexData.hasUVs6) {
  30160. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30161. }
  30162. if (parsedVertexData.hasColors) {
  30163. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30164. }
  30165. if (parsedVertexData.hasMatricesIndices) {
  30166. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30167. }
  30168. if (parsedVertexData.hasMatricesWeights) {
  30169. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30170. }
  30171. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  30172. }
  30173. else {
  30174. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  30175. }
  30176. scene.pushGeometry(geometry, true);
  30177. return geometry;
  30178. };
  30179. return Geometry;
  30180. })();
  30181. BABYLON.Geometry = Geometry;
  30182. /////// Primitives //////////////////////////////////////////////
  30183. var Geometry;
  30184. (function (Geometry) {
  30185. var Primitives;
  30186. (function (Primitives) {
  30187. /// Abstract class
  30188. var _Primitive = (function (_super) {
  30189. __extends(_Primitive, _super);
  30190. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  30191. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  30192. this._canBeRegenerated = _canBeRegenerated;
  30193. this._beingRegenerated = true;
  30194. this.regenerate();
  30195. this._beingRegenerated = false;
  30196. }
  30197. _Primitive.prototype.canBeRegenerated = function () {
  30198. return this._canBeRegenerated;
  30199. };
  30200. _Primitive.prototype.regenerate = function () {
  30201. if (!this._canBeRegenerated) {
  30202. return;
  30203. }
  30204. this._beingRegenerated = true;
  30205. this.setAllVerticesData(this._regenerateVertexData(), false);
  30206. this._beingRegenerated = false;
  30207. };
  30208. _Primitive.prototype.asNewGeometry = function (id) {
  30209. return _super.prototype.copy.call(this, id);
  30210. };
  30211. // overrides
  30212. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  30213. if (!this._beingRegenerated) {
  30214. return;
  30215. }
  30216. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  30217. };
  30218. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  30219. if (!this._beingRegenerated) {
  30220. return;
  30221. }
  30222. _super.prototype.setVerticesData.call(this, kind, data, false);
  30223. };
  30224. // to override
  30225. // protected
  30226. _Primitive.prototype._regenerateVertexData = function () {
  30227. throw new Error("Abstract method");
  30228. };
  30229. _Primitive.prototype.copy = function (id) {
  30230. throw new Error("Must be overriden in sub-classes.");
  30231. };
  30232. _Primitive.prototype.serialize = function () {
  30233. var serializationObject = _super.prototype.serialize.call(this);
  30234. serializationObject.canBeRegenerated = this.canBeRegenerated();
  30235. return serializationObject;
  30236. };
  30237. return _Primitive;
  30238. })(Geometry);
  30239. Primitives._Primitive = _Primitive;
  30240. var Ribbon = (function (_super) {
  30241. __extends(Ribbon, _super);
  30242. // Members
  30243. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  30244. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30245. _super.call(this, id, scene, canBeRegenerated, mesh);
  30246. this.pathArray = pathArray;
  30247. this.closeArray = closeArray;
  30248. this.closePath = closePath;
  30249. this.offset = offset;
  30250. this.side = side;
  30251. }
  30252. Ribbon.prototype._regenerateVertexData = function () {
  30253. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  30254. };
  30255. Ribbon.prototype.copy = function (id) {
  30256. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  30257. };
  30258. return Ribbon;
  30259. })(_Primitive);
  30260. Primitives.Ribbon = Ribbon;
  30261. var Box = (function (_super) {
  30262. __extends(Box, _super);
  30263. // Members
  30264. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  30265. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30266. _super.call(this, id, scene, canBeRegenerated, mesh);
  30267. this.size = size;
  30268. this.side = side;
  30269. }
  30270. Box.prototype._regenerateVertexData = function () {
  30271. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  30272. };
  30273. Box.prototype.copy = function (id) {
  30274. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30275. };
  30276. Box.prototype.serialize = function () {
  30277. var serializationObject = _super.prototype.serialize.call(this);
  30278. serializationObject.size = this.size;
  30279. return serializationObject;
  30280. };
  30281. Box.Parse = function (parsedBox, scene) {
  30282. if (scene.getGeometryByID(parsedBox.id)) {
  30283. return null; // null since geometry could be something else than a box...
  30284. }
  30285. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  30286. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30287. scene.pushGeometry(box, true);
  30288. return box;
  30289. };
  30290. return Box;
  30291. })(_Primitive);
  30292. Primitives.Box = Box;
  30293. var Sphere = (function (_super) {
  30294. __extends(Sphere, _super);
  30295. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30296. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30297. _super.call(this, id, scene, canBeRegenerated, mesh);
  30298. this.segments = segments;
  30299. this.diameter = diameter;
  30300. this.side = side;
  30301. }
  30302. Sphere.prototype._regenerateVertexData = function () {
  30303. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30304. };
  30305. Sphere.prototype.copy = function (id) {
  30306. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30307. };
  30308. Sphere.prototype.serialize = function () {
  30309. var serializationObject = _super.prototype.serialize.call(this);
  30310. serializationObject.segments = this.segments;
  30311. serializationObject.diameter = this.diameter;
  30312. return serializationObject;
  30313. };
  30314. Sphere.Parse = function (parsedSphere, scene) {
  30315. if (scene.getGeometryByID(parsedSphere.id)) {
  30316. return null; // null since geometry could be something else than a sphere...
  30317. }
  30318. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30319. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30320. scene.pushGeometry(sphere, true);
  30321. return sphere;
  30322. };
  30323. return Sphere;
  30324. })(_Primitive);
  30325. Primitives.Sphere = Sphere;
  30326. var Disc = (function (_super) {
  30327. __extends(Disc, _super);
  30328. // Members
  30329. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30330. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30331. _super.call(this, id, scene, canBeRegenerated, mesh);
  30332. this.radius = radius;
  30333. this.tessellation = tessellation;
  30334. this.side = side;
  30335. }
  30336. Disc.prototype._regenerateVertexData = function () {
  30337. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30338. };
  30339. Disc.prototype.copy = function (id) {
  30340. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30341. };
  30342. return Disc;
  30343. })(_Primitive);
  30344. Primitives.Disc = Disc;
  30345. var Cylinder = (function (_super) {
  30346. __extends(Cylinder, _super);
  30347. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30348. if (subdivisions === void 0) { subdivisions = 1; }
  30349. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30350. _super.call(this, id, scene, canBeRegenerated, mesh);
  30351. this.height = height;
  30352. this.diameterTop = diameterTop;
  30353. this.diameterBottom = diameterBottom;
  30354. this.tessellation = tessellation;
  30355. this.subdivisions = subdivisions;
  30356. this.side = side;
  30357. }
  30358. Cylinder.prototype._regenerateVertexData = function () {
  30359. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30360. };
  30361. Cylinder.prototype.copy = function (id) {
  30362. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30363. };
  30364. Cylinder.prototype.serialize = function () {
  30365. var serializationObject = _super.prototype.serialize.call(this);
  30366. serializationObject.height = this.height;
  30367. serializationObject.diameterTop = this.diameterTop;
  30368. serializationObject.diameterBottom = this.diameterBottom;
  30369. serializationObject.tessellation = this.tessellation;
  30370. return serializationObject;
  30371. };
  30372. Cylinder.Parse = function (parsedCylinder, scene) {
  30373. if (scene.getGeometryByID(parsedCylinder.id)) {
  30374. return null; // null since geometry could be something else than a cylinder...
  30375. }
  30376. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30377. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30378. scene.pushGeometry(cylinder, true);
  30379. return cylinder;
  30380. };
  30381. return Cylinder;
  30382. })(_Primitive);
  30383. Primitives.Cylinder = Cylinder;
  30384. var Torus = (function (_super) {
  30385. __extends(Torus, _super);
  30386. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30387. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30388. _super.call(this, id, scene, canBeRegenerated, mesh);
  30389. this.diameter = diameter;
  30390. this.thickness = thickness;
  30391. this.tessellation = tessellation;
  30392. this.side = side;
  30393. }
  30394. Torus.prototype._regenerateVertexData = function () {
  30395. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30396. };
  30397. Torus.prototype.copy = function (id) {
  30398. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30399. };
  30400. Torus.prototype.serialize = function () {
  30401. var serializationObject = _super.prototype.serialize.call(this);
  30402. serializationObject.diameter = this.diameter;
  30403. serializationObject.thickness = this.thickness;
  30404. serializationObject.tessellation = this.tessellation;
  30405. return serializationObject;
  30406. };
  30407. Torus.Parse = function (parsedTorus, scene) {
  30408. if (scene.getGeometryByID(parsedTorus.id)) {
  30409. return null; // null since geometry could be something else than a torus...
  30410. }
  30411. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30412. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30413. scene.pushGeometry(torus, true);
  30414. return torus;
  30415. };
  30416. return Torus;
  30417. })(_Primitive);
  30418. Primitives.Torus = Torus;
  30419. var Ground = (function (_super) {
  30420. __extends(Ground, _super);
  30421. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30422. _super.call(this, id, scene, canBeRegenerated, mesh);
  30423. this.width = width;
  30424. this.height = height;
  30425. this.subdivisions = subdivisions;
  30426. }
  30427. Ground.prototype._regenerateVertexData = function () {
  30428. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30429. };
  30430. Ground.prototype.copy = function (id) {
  30431. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30432. };
  30433. Ground.prototype.serialize = function () {
  30434. var serializationObject = _super.prototype.serialize.call(this);
  30435. serializationObject.width = this.width;
  30436. serializationObject.height = this.height;
  30437. serializationObject.subdivisions = this.subdivisions;
  30438. return serializationObject;
  30439. };
  30440. Ground.Parse = function (parsedGround, scene) {
  30441. if (scene.getGeometryByID(parsedGround.id)) {
  30442. return null; // null since geometry could be something else than a ground...
  30443. }
  30444. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30445. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30446. scene.pushGeometry(ground, true);
  30447. return ground;
  30448. };
  30449. return Ground;
  30450. })(_Primitive);
  30451. Primitives.Ground = Ground;
  30452. var TiledGround = (function (_super) {
  30453. __extends(TiledGround, _super);
  30454. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30455. _super.call(this, id, scene, canBeRegenerated, mesh);
  30456. this.xmin = xmin;
  30457. this.zmin = zmin;
  30458. this.xmax = xmax;
  30459. this.zmax = zmax;
  30460. this.subdivisions = subdivisions;
  30461. this.precision = precision;
  30462. }
  30463. TiledGround.prototype._regenerateVertexData = function () {
  30464. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30465. };
  30466. TiledGround.prototype.copy = function (id) {
  30467. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30468. };
  30469. return TiledGround;
  30470. })(_Primitive);
  30471. Primitives.TiledGround = TiledGround;
  30472. var Plane = (function (_super) {
  30473. __extends(Plane, _super);
  30474. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30475. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30476. _super.call(this, id, scene, canBeRegenerated, mesh);
  30477. this.size = size;
  30478. this.side = side;
  30479. }
  30480. Plane.prototype._regenerateVertexData = function () {
  30481. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30482. };
  30483. Plane.prototype.copy = function (id) {
  30484. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30485. };
  30486. Plane.prototype.serialize = function () {
  30487. var serializationObject = _super.prototype.serialize.call(this);
  30488. serializationObject.size = this.size;
  30489. return serializationObject;
  30490. };
  30491. Plane.Parse = function (parsedPlane, scene) {
  30492. if (scene.getGeometryByID(parsedPlane.id)) {
  30493. return null; // null since geometry could be something else than a ground...
  30494. }
  30495. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30496. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30497. scene.pushGeometry(plane, true);
  30498. return plane;
  30499. };
  30500. return Plane;
  30501. })(_Primitive);
  30502. Primitives.Plane = Plane;
  30503. var TorusKnot = (function (_super) {
  30504. __extends(TorusKnot, _super);
  30505. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30506. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30507. _super.call(this, id, scene, canBeRegenerated, mesh);
  30508. this.radius = radius;
  30509. this.tube = tube;
  30510. this.radialSegments = radialSegments;
  30511. this.tubularSegments = tubularSegments;
  30512. this.p = p;
  30513. this.q = q;
  30514. this.side = side;
  30515. }
  30516. TorusKnot.prototype._regenerateVertexData = function () {
  30517. 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 });
  30518. };
  30519. TorusKnot.prototype.copy = function (id) {
  30520. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30521. };
  30522. TorusKnot.prototype.serialize = function () {
  30523. var serializationObject = _super.prototype.serialize.call(this);
  30524. serializationObject.radius = this.radius;
  30525. serializationObject.tube = this.tube;
  30526. serializationObject.radialSegments = this.radialSegments;
  30527. serializationObject.tubularSegments = this.tubularSegments;
  30528. serializationObject.p = this.p;
  30529. serializationObject.q = this.q;
  30530. return serializationObject;
  30531. };
  30532. ;
  30533. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30534. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30535. return null; // null since geometry could be something else than a ground...
  30536. }
  30537. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30538. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30539. scene.pushGeometry(torusKnot, true);
  30540. return torusKnot;
  30541. };
  30542. return TorusKnot;
  30543. })(_Primitive);
  30544. Primitives.TorusKnot = TorusKnot;
  30545. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30546. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30547. })(BABYLON || (BABYLON = {}));
  30548. var BABYLON;
  30549. (function (BABYLON) {
  30550. var GroundMesh = (function (_super) {
  30551. __extends(GroundMesh, _super);
  30552. function GroundMesh(name, scene) {
  30553. _super.call(this, name, scene);
  30554. this.generateOctree = false;
  30555. this._worldInverse = new BABYLON.Matrix();
  30556. }
  30557. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  30558. get: function () {
  30559. return this._subdivisions;
  30560. },
  30561. enumerable: true,
  30562. configurable: true
  30563. });
  30564. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  30565. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  30566. this._subdivisions = chunksCount;
  30567. this.subdivide(this._subdivisions);
  30568. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  30569. };
  30570. /**
  30571. * Returns a height (y) value in the Worl system :
  30572. * the ground altitude at the coordinates (x, z) expressed in the World system.
  30573. * Returns the ground y position if (x, z) are outside the ground surface.
  30574. * Not pertinent if the ground is rotated.
  30575. */
  30576. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  30577. // express x and y in the ground local system
  30578. x -= this.position.x;
  30579. z -= this.position.z;
  30580. x /= this.scaling.x;
  30581. z /= this.scaling.z;
  30582. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  30583. return this.position.y;
  30584. }
  30585. if (!this._heightQuads || this._heightQuads.length == 0) {
  30586. this._initHeightQuads();
  30587. this._computeHeightQuads();
  30588. }
  30589. var facet = this._getFacetAt(x, z);
  30590. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  30591. // return y in the World system
  30592. return y * this.scaling.y + this.position.y;
  30593. };
  30594. /**
  30595. * Returns a normalized vector (Vector3) orthogonal to the ground
  30596. * at the ground coordinates (x, z) expressed in the World system.
  30597. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  30598. * Not pertinent if the ground is rotated.
  30599. */
  30600. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  30601. var normal = new BABYLON.Vector3(0, 1, 0);
  30602. this.getNormalAtCoordinatesToRef(x, z, normal);
  30603. return normal;
  30604. };
  30605. /**
  30606. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  30607. * at the ground coordinates (x, z) expressed in the World system.
  30608. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  30609. * Not pertinent if the ground is rotated.
  30610. */
  30611. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  30612. // express x and y in the ground local system
  30613. x -= this.position.x;
  30614. z -= this.position.z;
  30615. x /= this.scaling.x;
  30616. z /= this.scaling.z;
  30617. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  30618. return;
  30619. }
  30620. if (!this._heightQuads || this._heightQuads.length == 0) {
  30621. this._initHeightQuads();
  30622. this._computeHeightQuads();
  30623. }
  30624. var facet = this._getFacetAt(x, z);
  30625. ref.x = facet.x;
  30626. ref.y = facet.y;
  30627. ref.z = facet.z;
  30628. };
  30629. /**
  30630. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  30631. * if the ground has been updated.
  30632. * This can be used in the render loop
  30633. */
  30634. GroundMesh.prototype.updateCoordinateHeights = function () {
  30635. if (!this._heightQuads || this._heightQuads.length == 0) {
  30636. this._initHeightQuads();
  30637. }
  30638. this._computeHeightQuads();
  30639. };
  30640. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  30641. GroundMesh.prototype._getFacetAt = function (x, z) {
  30642. // retrieve col and row from x, z coordinates in the ground local system
  30643. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  30644. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  30645. var quad = this._heightQuads[row * this._subdivisions + col];
  30646. var facet;
  30647. if (z < quad.slope.x * x + quad.slope.y) {
  30648. facet = quad.facet1;
  30649. }
  30650. else {
  30651. facet = quad.facet2;
  30652. }
  30653. return facet;
  30654. };
  30655. // Creates and populates the heightMap array with "facet" elements :
  30656. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  30657. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  30658. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  30659. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  30660. GroundMesh.prototype._initHeightQuads = function () {
  30661. this._heightQuads = new Array();
  30662. for (var row = 0; row < this._subdivisions; row++) {
  30663. for (var col = 0; col < this._subdivisions; col++) {
  30664. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  30665. this._heightQuads[row * this._subdivisions + col] = quad;
  30666. }
  30667. }
  30668. };
  30669. // Compute each quad element values and update the the heightMap array :
  30670. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  30671. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  30672. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  30673. GroundMesh.prototype._computeHeightQuads = function () {
  30674. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30675. var v1 = BABYLON.Tmp.Vector3[0];
  30676. var v2 = BABYLON.Tmp.Vector3[1];
  30677. var v3 = BABYLON.Tmp.Vector3[2];
  30678. var v4 = BABYLON.Tmp.Vector3[3];
  30679. var v1v2 = BABYLON.Tmp.Vector3[4];
  30680. var v1v3 = BABYLON.Tmp.Vector3[5];
  30681. var v1v4 = BABYLON.Tmp.Vector3[6];
  30682. var norm1 = BABYLON.Tmp.Vector3[7];
  30683. var norm2 = BABYLON.Tmp.Vector3[8];
  30684. var i = 0;
  30685. var j = 0;
  30686. var k = 0;
  30687. var cd = 0; // 2D slope coefficient : z = cd * x + h
  30688. var h = 0;
  30689. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  30690. var d2 = 0;
  30691. for (var row = 0; row < this._subdivisions; row++) {
  30692. for (var col = 0; col < this._subdivisions; col++) {
  30693. i = col * 3;
  30694. j = row * (this._subdivisions + 1) * 3;
  30695. k = (row + 1) * (this._subdivisions + 1) * 3;
  30696. v1.x = positions[j + i];
  30697. v1.y = positions[j + i + 1];
  30698. v1.z = positions[j + i + 2];
  30699. v2.x = positions[j + i + 3];
  30700. v2.y = positions[j + i + 4];
  30701. v2.z = positions[j + i + 5];
  30702. v3.x = positions[k + i];
  30703. v3.y = positions[k + i + 1];
  30704. v3.z = positions[k + i + 2];
  30705. v4.x = positions[k + i + 3];
  30706. v4.y = positions[k + i + 4];
  30707. v4.z = positions[k + i + 5];
  30708. // 2D slope V1V4
  30709. cd = (v4.z - v1.z) / (v4.x - v1.x);
  30710. h = v1.z - cd * v1.x; // v1 belongs to the slope
  30711. // facet equations :
  30712. // we compute each facet normal vector
  30713. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  30714. // we compute the value d by applying the equation to v1 which belongs to the plane
  30715. // then we store the facet equation in a Vector4
  30716. v2.subtractToRef(v1, v1v2);
  30717. v3.subtractToRef(v1, v1v3);
  30718. v4.subtractToRef(v1, v1v4);
  30719. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  30720. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  30721. norm1.normalize();
  30722. norm2.normalize();
  30723. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  30724. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  30725. var quad = this._heightQuads[row * this._subdivisions + col];
  30726. quad.slope.copyFromFloats(cd, h);
  30727. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  30728. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  30729. }
  30730. }
  30731. };
  30732. return GroundMesh;
  30733. })(BABYLON.Mesh);
  30734. BABYLON.GroundMesh = GroundMesh;
  30735. })(BABYLON || (BABYLON = {}));
  30736. var BABYLON;
  30737. (function (BABYLON) {
  30738. var LinesMesh = (function (_super) {
  30739. __extends(LinesMesh, _super);
  30740. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  30741. if (parent === void 0) { parent = null; }
  30742. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  30743. this.color = new BABYLON.Color3(1, 1, 1);
  30744. this.alpha = 1;
  30745. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  30746. attributes: ["position"],
  30747. uniforms: ["worldViewProjection", "color"],
  30748. needAlphaBlending: true
  30749. });
  30750. }
  30751. Object.defineProperty(LinesMesh.prototype, "material", {
  30752. get: function () {
  30753. return this._colorShader;
  30754. },
  30755. enumerable: true,
  30756. configurable: true
  30757. });
  30758. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  30759. get: function () {
  30760. return false;
  30761. },
  30762. enumerable: true,
  30763. configurable: true
  30764. });
  30765. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  30766. get: function () {
  30767. return false;
  30768. },
  30769. enumerable: true,
  30770. configurable: true
  30771. });
  30772. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  30773. var engine = this.getScene().getEngine();
  30774. var indexToBind = this._geometry.getIndexBuffer();
  30775. // VBOs
  30776. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  30777. // Color
  30778. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  30779. };
  30780. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  30781. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  30782. return;
  30783. }
  30784. var engine = this.getScene().getEngine();
  30785. // Draw order
  30786. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  30787. };
  30788. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  30789. return null;
  30790. };
  30791. LinesMesh.prototype.dispose = function (doNotRecurse) {
  30792. this._colorShader.dispose();
  30793. _super.prototype.dispose.call(this, doNotRecurse);
  30794. };
  30795. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  30796. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  30797. };
  30798. return LinesMesh;
  30799. })(BABYLON.Mesh);
  30800. BABYLON.LinesMesh = LinesMesh;
  30801. })(BABYLON || (BABYLON = {}));
  30802. var BABYLON;
  30803. (function (BABYLON) {
  30804. var DebugLayer = (function () {
  30805. function DebugLayer(scene) {
  30806. var _this = this;
  30807. this._transformationMatrix = BABYLON.Matrix.Identity();
  30808. this._enabled = false;
  30809. this._labelsEnabled = false;
  30810. this._displayStatistics = true;
  30811. this._displayTree = false;
  30812. this._displayLogs = false;
  30813. this._skeletonViewers = new Array();
  30814. this._identityMatrix = BABYLON.Matrix.Identity();
  30815. this.axisRatio = 0.02;
  30816. this.accentColor = "orange";
  30817. this._scene = scene;
  30818. this._syncPositions = function () {
  30819. var engine = _this._scene.getEngine();
  30820. var canvasRect = engine.getRenderingCanvasClientRect();
  30821. if (_this._showUI) {
  30822. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30823. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30824. _this._statsDiv.style.width = "400px";
  30825. _this._statsDiv.style.height = "auto";
  30826. _this._statsSubsetDiv.style.maxHeight = "240px";
  30827. _this._optionsDiv.style.left = "0px";
  30828. _this._optionsDiv.style.top = "10px";
  30829. _this._optionsDiv.style.width = "200px";
  30830. _this._optionsDiv.style.height = "auto";
  30831. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30832. _this._logDiv.style.left = "0px";
  30833. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30834. _this._logDiv.style.width = "600px";
  30835. _this._logDiv.style.height = "160px";
  30836. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30837. _this._treeDiv.style.top = "10px";
  30838. _this._treeDiv.style.width = "300px";
  30839. _this._treeDiv.style.height = "auto";
  30840. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30841. }
  30842. _this._globalDiv.style.left = canvasRect.left + "px";
  30843. _this._globalDiv.style.top = canvasRect.top + "px";
  30844. _this._drawingCanvas.style.left = "0px";
  30845. _this._drawingCanvas.style.top = "0px";
  30846. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30847. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30848. var devicePixelRatio = window.devicePixelRatio || 1;
  30849. var context = _this._drawingContext;
  30850. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30851. context.mozBackingStorePixelRatio ||
  30852. context.msBackingStorePixelRatio ||
  30853. context.oBackingStorePixelRatio ||
  30854. context.backingStorePixelRatio || 1;
  30855. _this._ratio = devicePixelRatio / backingStoreRatio;
  30856. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30857. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30858. };
  30859. this._onCanvasClick = function (evt) {
  30860. _this._clickPosition = {
  30861. x: evt.clientX * _this._ratio,
  30862. y: evt.clientY * _this._ratio
  30863. };
  30864. };
  30865. this._syncUI = function () {
  30866. if (_this._showUI) {
  30867. if (_this._displayStatistics) {
  30868. _this._displayStats();
  30869. _this._statsDiv.style.display = "";
  30870. }
  30871. else {
  30872. _this._statsDiv.style.display = "none";
  30873. }
  30874. if (_this._displayLogs) {
  30875. _this._logDiv.style.display = "";
  30876. }
  30877. else {
  30878. _this._logDiv.style.display = "none";
  30879. }
  30880. if (_this._displayTree) {
  30881. _this._treeDiv.style.display = "";
  30882. if (_this._needToRefreshMeshesTree) {
  30883. _this._needToRefreshMeshesTree = false;
  30884. _this._refreshMeshesTreeContent();
  30885. }
  30886. }
  30887. else {
  30888. _this._treeDiv.style.display = "none";
  30889. }
  30890. }
  30891. };
  30892. this._syncData = function () {
  30893. if (_this._labelsEnabled || !_this._showUI) {
  30894. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30895. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30896. var engine = _this._scene.getEngine();
  30897. var viewport = _this._camera.viewport;
  30898. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  30899. // Meshes
  30900. var meshes = _this._camera.getActiveMeshes();
  30901. var index;
  30902. var projectedPosition;
  30903. for (index = 0; index < meshes.length; index++) {
  30904. var mesh = meshes.data[index];
  30905. var position = mesh.getBoundingInfo().boundingSphere.center;
  30906. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30907. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30908. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30909. }
  30910. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30911. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30912. }
  30913. }
  30914. // Cameras
  30915. var cameras = _this._scene.cameras;
  30916. for (index = 0; index < cameras.length; index++) {
  30917. var camera = cameras[index];
  30918. if (camera === _this._camera) {
  30919. continue;
  30920. }
  30921. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30922. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30923. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30924. _this._camera.detachControl(engine.getRenderingCanvas());
  30925. _this._camera = camera;
  30926. _this._camera.attachControl(engine.getRenderingCanvas());
  30927. }, function () { return "purple"; });
  30928. }
  30929. }
  30930. // Lights
  30931. var lights = _this._scene.lights;
  30932. for (index = 0; index < lights.length; index++) {
  30933. var light = lights[index];
  30934. if (light.position) {
  30935. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30936. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30937. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30938. light.setEnabled(!light.isEnabled());
  30939. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30940. }
  30941. }
  30942. }
  30943. }
  30944. _this._clickPosition = undefined;
  30945. };
  30946. }
  30947. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30948. while (this._treeSubsetDiv.hasChildNodes()) {
  30949. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30950. }
  30951. // Add meshes
  30952. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30953. sortedArray.sort(function (a, b) {
  30954. if (a.name === b.name) {
  30955. return 0;
  30956. }
  30957. return (a.name > b.name) ? 1 : -1;
  30958. });
  30959. for (var index = 0; index < sortedArray.length; index++) {
  30960. var mesh = sortedArray[index];
  30961. if (!mesh.isEnabled()) {
  30962. continue;
  30963. }
  30964. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30965. m.isVisible = element.checked;
  30966. }, mesh);
  30967. }
  30968. };
  30969. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30970. this._drawingContext.beginPath();
  30971. this._drawingContext.moveTo(zero.x, zero.y);
  30972. this._drawingContext.lineTo(unit.x, unit.y);
  30973. this._drawingContext.strokeStyle = color;
  30974. this._drawingContext.lineWidth = 4;
  30975. this._drawingContext.stroke();
  30976. this._drawingContext.font = "normal 14px Segoe UI";
  30977. this._drawingContext.fillStyle = color;
  30978. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30979. };
  30980. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30981. var position = mesh.getBoundingInfo().boundingSphere.center;
  30982. var worldMatrix = mesh.getWorldMatrix();
  30983. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30984. var unit = (unprojectedVector.subtract(position)).length();
  30985. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30986. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30987. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30988. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30989. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30990. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30991. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30992. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30993. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30994. };
  30995. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30996. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30997. this._drawingContext.font = "normal 12px Segoe UI";
  30998. var textMetrics = this._drawingContext.measureText(text);
  30999. var centerX = projectedPosition.x - textMetrics.width / 2;
  31000. var centerY = projectedPosition.y;
  31001. var clientRect = this._drawingCanvas.getBoundingClientRect();
  31002. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  31003. onClick();
  31004. }
  31005. this._drawingContext.beginPath();
  31006. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  31007. this._drawingContext.fillStyle = getFillStyle();
  31008. this._drawingContext.globalAlpha = 0.5;
  31009. this._drawingContext.fill();
  31010. this._drawingContext.globalAlpha = 1.0;
  31011. this._drawingContext.strokeStyle = '#FFFFFF';
  31012. this._drawingContext.lineWidth = 1;
  31013. this._drawingContext.stroke();
  31014. this._drawingContext.fillStyle = "#FFFFFF";
  31015. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  31016. this._drawingContext.beginPath();
  31017. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  31018. this._drawingContext.fill();
  31019. }
  31020. };
  31021. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  31022. if (!this._clickPosition) {
  31023. return false;
  31024. }
  31025. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  31026. return false;
  31027. }
  31028. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  31029. return false;
  31030. }
  31031. return true;
  31032. };
  31033. DebugLayer.prototype.isVisible = function () {
  31034. return this._enabled;
  31035. };
  31036. DebugLayer.prototype.hide = function () {
  31037. if (!this._enabled) {
  31038. return;
  31039. }
  31040. this._enabled = false;
  31041. var engine = this._scene.getEngine();
  31042. this._scene.unregisterBeforeRender(this._syncData);
  31043. this._scene.unregisterAfterRender(this._syncUI);
  31044. this._rootElement.removeChild(this._globalDiv);
  31045. this._scene.forceShowBoundingBoxes = false;
  31046. this._scene.forceWireframe = false;
  31047. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  31048. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  31049. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  31050. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  31051. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  31052. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  31053. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  31054. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  31055. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  31056. this._scene.shadowsEnabled = true;
  31057. this._scene.particlesEnabled = true;
  31058. this._scene.postProcessesEnabled = true;
  31059. this._scene.collisionsEnabled = true;
  31060. this._scene.lightsEnabled = true;
  31061. this._scene.texturesEnabled = true;
  31062. this._scene.lensFlaresEnabled = true;
  31063. this._scene.proceduralTexturesEnabled = true;
  31064. this._scene.renderTargetsEnabled = true;
  31065. this._scene.probesEnabled = true;
  31066. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  31067. this._clearSkeletonViewers();
  31068. };
  31069. DebugLayer.prototype._clearSkeletonViewers = function () {
  31070. for (var index = 0; index < this._skeletonViewers.length; index++) {
  31071. this._skeletonViewers[index].dispose();
  31072. }
  31073. this._skeletonViewers = [];
  31074. };
  31075. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  31076. if (showUI === void 0) { showUI = true; }
  31077. if (camera === void 0) { camera = null; }
  31078. if (rootElement === void 0) { rootElement = null; }
  31079. if (this._enabled) {
  31080. return;
  31081. }
  31082. this._enabled = true;
  31083. if (camera) {
  31084. this._camera = camera;
  31085. }
  31086. else {
  31087. this._camera = this._scene.activeCamera;
  31088. }
  31089. this._showUI = showUI;
  31090. var engine = this._scene.getEngine();
  31091. this._globalDiv = document.createElement("div");
  31092. this._rootElement = rootElement || document.body;
  31093. this._rootElement.appendChild(this._globalDiv);
  31094. this._generateDOMelements();
  31095. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  31096. this._syncPositions();
  31097. this._scene.registerBeforeRender(this._syncData);
  31098. this._scene.registerAfterRender(this._syncUI);
  31099. };
  31100. DebugLayer.prototype._clearLabels = function () {
  31101. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  31102. for (var index = 0; index < this._scene.meshes.length; index++) {
  31103. var mesh = this._scene.meshes[index];
  31104. mesh.renderOverlay = false;
  31105. }
  31106. };
  31107. DebugLayer.prototype._generateheader = function (root, text) {
  31108. var header = document.createElement("div");
  31109. header.innerHTML = text + "&nbsp;";
  31110. header.style.textAlign = "right";
  31111. header.style.width = "100%";
  31112. header.style.color = "white";
  31113. header.style.backgroundColor = "Black";
  31114. header.style.padding = "5px 5px 4px 0px";
  31115. header.style.marginLeft = "-5px";
  31116. header.style.fontWeight = "bold";
  31117. root.appendChild(header);
  31118. };
  31119. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  31120. var label = document.createElement("label");
  31121. label.innerHTML = title;
  31122. label.style.color = color;
  31123. root.appendChild(label);
  31124. root.appendChild(document.createElement("br"));
  31125. };
  31126. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  31127. if (tag === void 0) { tag = null; }
  31128. var label = document.createElement("label");
  31129. var boundingBoxesCheckbox = document.createElement("input");
  31130. boundingBoxesCheckbox.type = "checkbox";
  31131. boundingBoxesCheckbox.checked = initialState;
  31132. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  31133. task(evt.target, tag);
  31134. });
  31135. label.appendChild(boundingBoxesCheckbox);
  31136. var container = document.createElement("span");
  31137. var leftPart = document.createElement("span");
  31138. var rightPart = document.createElement("span");
  31139. rightPart.style.cssFloat = "right";
  31140. leftPart.innerHTML = leftTitle;
  31141. rightPart.innerHTML = rightTitle;
  31142. rightPart.style.fontSize = "12px";
  31143. rightPart.style.maxWidth = "200px";
  31144. container.appendChild(leftPart);
  31145. container.appendChild(rightPart);
  31146. label.appendChild(container);
  31147. root.appendChild(label);
  31148. root.appendChild(document.createElement("br"));
  31149. };
  31150. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  31151. if (tag === void 0) { tag = null; }
  31152. var label = document.createElement("label");
  31153. var checkBox = document.createElement("input");
  31154. checkBox.type = "checkbox";
  31155. checkBox.checked = initialState;
  31156. checkBox.addEventListener("change", function (evt) {
  31157. task(evt.target, tag);
  31158. });
  31159. label.appendChild(checkBox);
  31160. label.appendChild(document.createTextNode(title));
  31161. root.appendChild(label);
  31162. root.appendChild(document.createElement("br"));
  31163. };
  31164. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  31165. if (tag === void 0) { tag = null; }
  31166. var button = document.createElement("button");
  31167. button.innerHTML = title;
  31168. button.style.height = "24px";
  31169. button.style.width = "150px";
  31170. button.style.marginBottom = "5px";
  31171. button.style.color = "#444444";
  31172. button.style.border = "1px solid white";
  31173. button.className = "debugLayerButton";
  31174. button.addEventListener("click", function (evt) {
  31175. task(evt.target, tag);
  31176. });
  31177. root.appendChild(button);
  31178. root.appendChild(document.createElement("br"));
  31179. };
  31180. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  31181. if (tag === void 0) { tag = null; }
  31182. var label = document.createElement("label");
  31183. var boundingBoxesRadio = document.createElement("input");
  31184. boundingBoxesRadio.type = "radio";
  31185. boundingBoxesRadio.name = name;
  31186. boundingBoxesRadio.checked = initialState;
  31187. boundingBoxesRadio.addEventListener("change", function (evt) {
  31188. task(evt.target, tag);
  31189. });
  31190. label.appendChild(boundingBoxesRadio);
  31191. label.appendChild(document.createTextNode(title));
  31192. root.appendChild(label);
  31193. root.appendChild(document.createElement("br"));
  31194. };
  31195. DebugLayer.prototype._generateDOMelements = function () {
  31196. var _this = this;
  31197. this._globalDiv.id = "DebugLayer";
  31198. this._globalDiv.style.position = "absolute";
  31199. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  31200. this._globalDiv.style.fontSize = "14px";
  31201. this._globalDiv.style.color = "white";
  31202. // Drawing canvas
  31203. this._drawingCanvas = document.createElement("canvas");
  31204. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  31205. this._drawingCanvas.style.position = "absolute";
  31206. this._drawingCanvas.style.pointerEvents = "none";
  31207. this._drawingCanvas.style.backgroundColor = "transparent";
  31208. this._drawingContext = this._drawingCanvas.getContext("2d");
  31209. this._globalDiv.appendChild(this._drawingCanvas);
  31210. if (this._showUI) {
  31211. var background = "rgba(128, 128, 128, 0.4)";
  31212. var border = "rgb(180, 180, 180) solid 1px";
  31213. // Stats
  31214. this._statsDiv = document.createElement("div");
  31215. this._statsDiv.id = "DebugLayerStats";
  31216. this._statsDiv.style.border = border;
  31217. this._statsDiv.style.position = "absolute";
  31218. this._statsDiv.style.background = background;
  31219. this._statsDiv.style.padding = "0px 0px 0px 5px";
  31220. this._generateheader(this._statsDiv, "STATISTICS");
  31221. this._statsSubsetDiv = document.createElement("div");
  31222. this._statsSubsetDiv.style.paddingTop = "5px";
  31223. this._statsSubsetDiv.style.paddingBottom = "5px";
  31224. this._statsSubsetDiv.style.overflowY = "auto";
  31225. this._statsDiv.appendChild(this._statsSubsetDiv);
  31226. // Tree
  31227. this._treeDiv = document.createElement("div");
  31228. this._treeDiv.id = "DebugLayerTree";
  31229. this._treeDiv.style.border = border;
  31230. this._treeDiv.style.position = "absolute";
  31231. this._treeDiv.style.background = background;
  31232. this._treeDiv.style.padding = "0px 0px 0px 5px";
  31233. this._treeDiv.style.display = "none";
  31234. this._generateheader(this._treeDiv, "MESHES TREE");
  31235. this._treeSubsetDiv = document.createElement("div");
  31236. this._treeSubsetDiv.style.paddingTop = "5px";
  31237. this._treeSubsetDiv.style.paddingRight = "5px";
  31238. this._treeSubsetDiv.style.overflowY = "auto";
  31239. this._treeSubsetDiv.style.maxHeight = "300px";
  31240. this._treeDiv.appendChild(this._treeSubsetDiv);
  31241. this._needToRefreshMeshesTree = true;
  31242. // Logs
  31243. this._logDiv = document.createElement("div");
  31244. this._logDiv.style.border = border;
  31245. this._logDiv.id = "DebugLayerLogs";
  31246. this._logDiv.style.position = "absolute";
  31247. this._logDiv.style.background = background;
  31248. this._logDiv.style.padding = "0px 0px 0px 5px";
  31249. this._logDiv.style.display = "none";
  31250. this._generateheader(this._logDiv, "LOGS");
  31251. this._logSubsetDiv = document.createElement("div");
  31252. this._logSubsetDiv.style.height = "127px";
  31253. this._logSubsetDiv.style.paddingTop = "5px";
  31254. this._logSubsetDiv.style.overflowY = "auto";
  31255. this._logSubsetDiv.style.fontSize = "12px";
  31256. this._logSubsetDiv.style.fontFamily = "consolas";
  31257. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31258. this._logDiv.appendChild(this._logSubsetDiv);
  31259. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31260. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31261. };
  31262. // Options
  31263. this._optionsDiv = document.createElement("div");
  31264. this._optionsDiv.id = "DebugLayerOptions";
  31265. this._optionsDiv.style.border = border;
  31266. this._optionsDiv.style.position = "absolute";
  31267. this._optionsDiv.style.background = background;
  31268. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31269. this._optionsDiv.style.overflowY = "auto";
  31270. this._generateheader(this._optionsDiv, "OPTIONS");
  31271. this._optionsSubsetDiv = document.createElement("div");
  31272. this._optionsSubsetDiv.style.paddingTop = "5px";
  31273. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31274. this._optionsSubsetDiv.style.overflowY = "auto";
  31275. this._optionsSubsetDiv.style.maxHeight = "200px";
  31276. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31277. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31278. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31279. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31280. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31281. _this._displayTree = element.checked;
  31282. _this._needToRefreshMeshesTree = true;
  31283. });
  31284. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31285. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31286. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31287. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31288. _this._labelsEnabled = element.checked;
  31289. if (!_this._labelsEnabled) {
  31290. _this._clearLabels();
  31291. }
  31292. });
  31293. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31294. if (element.checked) {
  31295. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31296. }
  31297. else {
  31298. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31299. }
  31300. });
  31301. ;
  31302. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31303. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31304. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31305. if (element.checked) {
  31306. _this._scene.forceWireframe = false;
  31307. _this._scene.forcePointsCloud = false;
  31308. }
  31309. });
  31310. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31311. if (element.checked) {
  31312. _this._scene.forceWireframe = true;
  31313. _this._scene.forcePointsCloud = false;
  31314. }
  31315. });
  31316. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31317. if (element.checked) {
  31318. _this._scene.forceWireframe = false;
  31319. _this._scene.forcePointsCloud = true;
  31320. }
  31321. });
  31322. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31323. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31324. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31325. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31326. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31327. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31328. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31329. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31330. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31331. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  31332. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  31333. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31334. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31335. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31336. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31337. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31338. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31339. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31340. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31341. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31342. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31343. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  31344. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31345. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31346. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31347. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31348. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31349. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31350. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  31351. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31352. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31353. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31354. if (element.checked) {
  31355. _this._scene.headphone = true;
  31356. }
  31357. });
  31358. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31359. if (element.checked) {
  31360. _this._scene.headphone = false;
  31361. }
  31362. });
  31363. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31364. _this._scene.audioEnabled = !element.checked;
  31365. });
  31366. }
  31367. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31368. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  31369. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  31370. if (!element.checked) {
  31371. _this._clearSkeletonViewers();
  31372. return;
  31373. }
  31374. for (var index = 0; index < _this._scene.meshes.length; index++) {
  31375. var mesh = _this._scene.meshes[index];
  31376. if (mesh.skeleton) {
  31377. var found = false;
  31378. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  31379. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  31380. found = true;
  31381. break;
  31382. }
  31383. }
  31384. if (found) {
  31385. continue;
  31386. }
  31387. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  31388. viewer.isEnabled = true;
  31389. _this._skeletonViewers.push(viewer);
  31390. }
  31391. }
  31392. });
  31393. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31394. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31395. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31396. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  31397. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  31398. if (_this._camera) {
  31399. console.log(_this._camera);
  31400. }
  31401. else {
  31402. console.warn("No camera defined, or debug layer created before camera creation!");
  31403. }
  31404. });
  31405. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31406. this._globalDiv.appendChild(this._statsDiv);
  31407. this._globalDiv.appendChild(this._logDiv);
  31408. this._globalDiv.appendChild(this._optionsDiv);
  31409. this._globalDiv.appendChild(this._treeDiv);
  31410. }
  31411. };
  31412. DebugLayer.prototype._displayStats = function () {
  31413. var scene = this._scene;
  31414. var engine = scene.getEngine();
  31415. var glInfo = engine.getGlInfo();
  31416. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31417. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31418. + "<b>Count</b><br>"
  31419. + "Total meshes: " + scene.meshes.length + "<br>"
  31420. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31421. + "Total materials: " + scene.materials.length + "<br>"
  31422. + "Total textures: " + scene.textures.length + "<br>"
  31423. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31424. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31425. + "Active bones: " + scene.getActiveBones() + "<br>"
  31426. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31427. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  31428. + "<b>Duration</b><br>"
  31429. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31430. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31431. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31432. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31433. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31434. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31435. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  31436. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  31437. + "</div>"
  31438. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31439. + "<b>Extensions</b><br>"
  31440. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31441. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31442. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31443. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  31444. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31445. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  31446. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  31447. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  31448. + "</div><br>"
  31449. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31450. + "<b>Caps.</b><br>"
  31451. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31452. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31453. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  31454. + "<b>Info</b><br>"
  31455. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  31456. + glInfo.version + "<br>"
  31457. + "</div><br>"
  31458. + glInfo.renderer + "<br>";
  31459. if (this.customStatsFunction) {
  31460. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31461. }
  31462. };
  31463. return DebugLayer;
  31464. })();
  31465. BABYLON.DebugLayer = DebugLayer;
  31466. })(BABYLON || (BABYLON = {}));
  31467. var BABYLON;
  31468. (function (BABYLON) {
  31469. var DefaultLoadingScreen = (function () {
  31470. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  31471. var _this = this;
  31472. if (_loadingText === void 0) { _loadingText = ""; }
  31473. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  31474. this._renderingCanvas = _renderingCanvas;
  31475. this._loadingText = _loadingText;
  31476. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  31477. // Resize
  31478. this._resizeLoadingUI = function () {
  31479. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  31480. _this._loadingDiv.style.position = "absolute";
  31481. _this._loadingDiv.style.left = canvasRect.left + "px";
  31482. _this._loadingDiv.style.top = canvasRect.top + "px";
  31483. _this._loadingDiv.style.width = canvasRect.width + "px";
  31484. _this._loadingDiv.style.height = canvasRect.height + "px";
  31485. };
  31486. }
  31487. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  31488. var _this = this;
  31489. if (this._loadingDiv) {
  31490. // Do not add a loading screen if there is already one
  31491. return;
  31492. }
  31493. this._loadingDiv = document.createElement("div");
  31494. this._loadingDiv.id = "babylonjsLoadingDiv";
  31495. this._loadingDiv.style.opacity = "0";
  31496. this._loadingDiv.style.transition = "opacity 1.5s ease";
  31497. // Loading text
  31498. this._loadingTextDiv = document.createElement("div");
  31499. this._loadingTextDiv.style.position = "absolute";
  31500. this._loadingTextDiv.style.left = "0";
  31501. this._loadingTextDiv.style.top = "50%";
  31502. this._loadingTextDiv.style.marginTop = "80px";
  31503. this._loadingTextDiv.style.width = "100%";
  31504. this._loadingTextDiv.style.height = "20px";
  31505. this._loadingTextDiv.style.fontFamily = "Arial";
  31506. this._loadingTextDiv.style.fontSize = "14px";
  31507. this._loadingTextDiv.style.color = "white";
  31508. this._loadingTextDiv.style.textAlign = "center";
  31509. this._loadingTextDiv.innerHTML = "Loading";
  31510. this._loadingDiv.appendChild(this._loadingTextDiv);
  31511. //set the predefined text
  31512. this._loadingTextDiv.innerHTML = this._loadingText;
  31513. // Loading img
  31514. var imgBack = new Image();
  31515. 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==";
  31516. imgBack.style.position = "absolute";
  31517. imgBack.style.left = "50%";
  31518. imgBack.style.top = "50%";
  31519. imgBack.style.marginLeft = "-50px";
  31520. imgBack.style.marginTop = "-50px";
  31521. imgBack.style.transition = "transform 1.0s ease";
  31522. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  31523. var deg = 360;
  31524. var onTransitionEnd = function () {
  31525. deg += 360;
  31526. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  31527. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  31528. };
  31529. imgBack.addEventListener("transitionend", onTransitionEnd);
  31530. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  31531. this._loadingDiv.appendChild(imgBack);
  31532. // front image
  31533. var imgFront = new Image();
  31534. 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=";
  31535. imgFront.style.position = "absolute";
  31536. imgFront.style.left = "50%";
  31537. imgFront.style.top = "50%";
  31538. imgFront.style.marginLeft = "-50px";
  31539. imgFront.style.marginTop = "-50px";
  31540. this._loadingDiv.appendChild(imgFront);
  31541. this._resizeLoadingUI();
  31542. window.addEventListener("resize", this._resizeLoadingUI);
  31543. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  31544. document.body.appendChild(this._loadingDiv);
  31545. setTimeout(function () {
  31546. _this._loadingDiv.style.opacity = "1";
  31547. imgBack.style.transform = "rotateZ(360deg)";
  31548. imgBack.style.webkitTransform = "rotateZ(360deg)";
  31549. }, 0);
  31550. };
  31551. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  31552. var _this = this;
  31553. if (!this._loadingDiv) {
  31554. return;
  31555. }
  31556. var onTransitionEnd = function () {
  31557. if (!_this._loadingDiv) {
  31558. return;
  31559. }
  31560. document.body.removeChild(_this._loadingDiv);
  31561. window.removeEventListener("resize", _this._resizeLoadingUI);
  31562. _this._loadingDiv = null;
  31563. };
  31564. this._loadingDiv.style.opacity = "0";
  31565. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  31566. };
  31567. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  31568. set: function (text) {
  31569. this._loadingText = text;
  31570. if (this._loadingTextDiv) {
  31571. this._loadingTextDiv.innerHTML = this._loadingText;
  31572. }
  31573. },
  31574. enumerable: true,
  31575. configurable: true
  31576. });
  31577. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  31578. get: function () {
  31579. return this._loadingDivBackgroundColor;
  31580. },
  31581. set: function (color) {
  31582. this._loadingDivBackgroundColor = color;
  31583. if (!this._loadingDiv) {
  31584. return;
  31585. }
  31586. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. return DefaultLoadingScreen;
  31592. })();
  31593. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  31594. })(BABYLON || (BABYLON = {}));
  31595. var BABYLON;
  31596. (function (BABYLON) {
  31597. var AudioEngine = (function () {
  31598. function AudioEngine() {
  31599. this._audioContext = null;
  31600. this._audioContextInitialized = false;
  31601. this.canUseWebAudio = false;
  31602. this.WarnedWebAudioUnsupported = false;
  31603. this.unlocked = false;
  31604. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  31605. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  31606. this.canUseWebAudio = true;
  31607. }
  31608. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  31609. this._unlockiOSaudio();
  31610. }
  31611. else {
  31612. this.unlocked = true;
  31613. }
  31614. }
  31615. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  31616. get: function () {
  31617. if (!this._audioContextInitialized) {
  31618. this._initializeAudioContext();
  31619. }
  31620. return this._audioContext;
  31621. },
  31622. enumerable: true,
  31623. configurable: true
  31624. });
  31625. AudioEngine.prototype._unlockiOSaudio = function () {
  31626. var _this = this;
  31627. var unlockaudio = function () {
  31628. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  31629. var source = _this.audioContext.createBufferSource();
  31630. source.buffer = buffer;
  31631. source.connect(_this.audioContext.destination);
  31632. source.start(0);
  31633. setTimeout(function () {
  31634. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  31635. _this.unlocked = true;
  31636. window.removeEventListener('touchend', unlockaudio, false);
  31637. if (_this.onAudioUnlocked) {
  31638. _this.onAudioUnlocked();
  31639. }
  31640. }
  31641. }, 0);
  31642. };
  31643. window.addEventListener('touchend', unlockaudio, false);
  31644. };
  31645. AudioEngine.prototype._initializeAudioContext = function () {
  31646. try {
  31647. if (this.canUseWebAudio) {
  31648. this._audioContext = new AudioContext();
  31649. // create a global volume gain node
  31650. this.masterGain = this._audioContext.createGain();
  31651. this.masterGain.gain.value = 1;
  31652. this.masterGain.connect(this._audioContext.destination);
  31653. this._audioContextInitialized = true;
  31654. }
  31655. }
  31656. catch (e) {
  31657. this.canUseWebAudio = false;
  31658. BABYLON.Tools.Error("Web Audio: " + e.message);
  31659. }
  31660. };
  31661. AudioEngine.prototype.dispose = function () {
  31662. if (this.canUseWebAudio && this._audioContextInitialized) {
  31663. if (this._connectedAnalyser) {
  31664. this._connectedAnalyser.stopDebugCanvas();
  31665. this._connectedAnalyser.dispose();
  31666. this.masterGain.disconnect();
  31667. this.masterGain.connect(this._audioContext.destination);
  31668. this._connectedAnalyser = null;
  31669. }
  31670. this.masterGain.gain.value = 1;
  31671. }
  31672. this.WarnedWebAudioUnsupported = false;
  31673. };
  31674. AudioEngine.prototype.getGlobalVolume = function () {
  31675. if (this.canUseWebAudio && this._audioContextInitialized) {
  31676. return this.masterGain.gain.value;
  31677. }
  31678. else {
  31679. return -1;
  31680. }
  31681. };
  31682. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  31683. if (this.canUseWebAudio && this._audioContextInitialized) {
  31684. this.masterGain.gain.value = newVolume;
  31685. }
  31686. };
  31687. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  31688. if (this._connectedAnalyser) {
  31689. this._connectedAnalyser.stopDebugCanvas();
  31690. }
  31691. if (this.canUseWebAudio && this._audioContextInitialized) {
  31692. this._connectedAnalyser = analyser;
  31693. this.masterGain.disconnect();
  31694. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  31695. }
  31696. };
  31697. return AudioEngine;
  31698. })();
  31699. BABYLON.AudioEngine = AudioEngine;
  31700. })(BABYLON || (BABYLON = {}));
  31701. var BABYLON;
  31702. (function (BABYLON) {
  31703. var Sound = (function () {
  31704. /**
  31705. * Create a sound and attach it to a scene
  31706. * @param name Name of your sound
  31707. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  31708. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  31709. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  31710. */
  31711. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  31712. var _this = this;
  31713. this.autoplay = false;
  31714. this.loop = false;
  31715. this.useCustomAttenuation = false;
  31716. this.spatialSound = false;
  31717. this.refDistance = 1;
  31718. this.rolloffFactor = 1;
  31719. this.maxDistance = 100;
  31720. this.distanceModel = "linear";
  31721. this._panningModel = "equalpower";
  31722. this._playbackRate = 1;
  31723. this._streaming = false;
  31724. this._startTime = 0;
  31725. this._startOffset = 0;
  31726. this._position = BABYLON.Vector3.Zero();
  31727. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  31728. this._volume = 1;
  31729. this._isLoaded = false;
  31730. this._isReadyToPlay = false;
  31731. this.isPlaying = false;
  31732. this.isPaused = false;
  31733. this._isDirectional = false;
  31734. // Used if you'd like to create a directional sound.
  31735. // If not set, the sound will be omnidirectional
  31736. this._coneInnerAngle = 360;
  31737. this._coneOuterAngle = 360;
  31738. this._coneOuterGain = 0;
  31739. this._isOutputConnected = false;
  31740. this.name = name;
  31741. this._scene = scene;
  31742. this._readyToPlayCallback = readyToPlayCallback;
  31743. // Default custom attenuation function is a linear attenuation
  31744. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  31745. if (currentDistance < maxDistance) {
  31746. return currentVolume * (1 - currentDistance / maxDistance);
  31747. }
  31748. else {
  31749. return 0;
  31750. }
  31751. };
  31752. if (options) {
  31753. this.autoplay = options.autoplay || false;
  31754. this.loop = options.loop || false;
  31755. // if volume === 0, we need another way to check this option
  31756. if (options.volume !== undefined) {
  31757. this._volume = options.volume;
  31758. }
  31759. this.spatialSound = options.spatialSound || false;
  31760. this.maxDistance = options.maxDistance || 100;
  31761. this.useCustomAttenuation = options.useCustomAttenuation || false;
  31762. this.rolloffFactor = options.rolloffFactor || 1;
  31763. this.refDistance = options.refDistance || 1;
  31764. this.distanceModel = options.distanceModel || "linear";
  31765. this._playbackRate = options.playbackRate || 1;
  31766. this._streaming = options.streaming || false;
  31767. }
  31768. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31769. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  31770. this._soundGain.gain.value = this._volume;
  31771. this._inputAudioNode = this._soundGain;
  31772. this._ouputAudioNode = this._soundGain;
  31773. if (this.spatialSound) {
  31774. this._createSpatialParameters();
  31775. }
  31776. this._scene.mainSoundTrack.AddSound(this);
  31777. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  31778. if (urlOrArrayBuffer) {
  31779. // If it's an URL
  31780. if (typeof (urlOrArrayBuffer) === "string") {
  31781. // Loading sound using XHR2
  31782. if (!this._streaming) {
  31783. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  31784. }
  31785. else {
  31786. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  31787. this._htmlAudioElement.controls = false;
  31788. this._htmlAudioElement.loop = this.loop;
  31789. this._htmlAudioElement.crossOrigin = "anonymous";
  31790. this._htmlAudioElement.preload = "auto";
  31791. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  31792. _this._isReadyToPlay = true;
  31793. if (_this.autoplay) {
  31794. _this.play();
  31795. }
  31796. if (_this._readyToPlayCallback) {
  31797. _this._readyToPlayCallback();
  31798. }
  31799. });
  31800. document.body.appendChild(this._htmlAudioElement);
  31801. }
  31802. }
  31803. else {
  31804. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  31805. if (urlOrArrayBuffer.byteLength > 0) {
  31806. this._soundLoaded(urlOrArrayBuffer);
  31807. }
  31808. }
  31809. else {
  31810. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  31811. }
  31812. }
  31813. }
  31814. }
  31815. else {
  31816. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  31817. this._scene.mainSoundTrack.AddSound(this);
  31818. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  31819. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  31820. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  31821. }
  31822. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  31823. if (this._readyToPlayCallback) {
  31824. window.setTimeout(function () {
  31825. _this._readyToPlayCallback();
  31826. }, 1000);
  31827. }
  31828. }
  31829. }
  31830. Sound.prototype.dispose = function () {
  31831. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  31832. if (this.isPlaying) {
  31833. this.stop();
  31834. }
  31835. this._isReadyToPlay = false;
  31836. if (this.soundTrackId === -1) {
  31837. this._scene.mainSoundTrack.RemoveSound(this);
  31838. }
  31839. else {
  31840. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  31841. }
  31842. if (this._soundGain) {
  31843. this._soundGain.disconnect();
  31844. this._soundGain = null;
  31845. }
  31846. if (this._soundPanner) {
  31847. this._soundPanner.disconnect();
  31848. this._soundPanner = null;
  31849. }
  31850. if (this._soundSource) {
  31851. this._soundSource.disconnect();
  31852. this._soundSource = null;
  31853. }
  31854. this._audioBuffer = null;
  31855. if (this._htmlAudioElement) {
  31856. this._htmlAudioElement.pause();
  31857. this._htmlAudioElement.src = "";
  31858. document.body.removeChild(this._htmlAudioElement);
  31859. }
  31860. if (this._connectedMesh) {
  31861. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  31862. this._connectedMesh = null;
  31863. }
  31864. }
  31865. };
  31866. Sound.prototype._soundLoaded = function (audioData) {
  31867. var _this = this;
  31868. this._isLoaded = true;
  31869. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  31870. _this._audioBuffer = buffer;
  31871. _this._isReadyToPlay = true;
  31872. if (_this.autoplay) {
  31873. _this.play();
  31874. }
  31875. if (_this._readyToPlayCallback) {
  31876. _this._readyToPlayCallback();
  31877. }
  31878. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  31879. };
  31880. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  31881. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31882. this._audioBuffer = audioBuffer;
  31883. this._isReadyToPlay = true;
  31884. }
  31885. };
  31886. Sound.prototype.updateOptions = function (options) {
  31887. if (options) {
  31888. this.loop = options.loop || this.loop;
  31889. this.maxDistance = options.maxDistance || this.maxDistance;
  31890. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  31891. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  31892. this.refDistance = options.refDistance || this.refDistance;
  31893. this.distanceModel = options.distanceModel || this.distanceModel;
  31894. this._playbackRate = options.playbackRate || this._playbackRate;
  31895. this._updateSpatialParameters();
  31896. if (this.isPlaying) {
  31897. if (this._streaming) {
  31898. this._htmlAudioElement.playbackRate = this._playbackRate;
  31899. }
  31900. else {
  31901. this._soundSource.playbackRate.value = this._playbackRate;
  31902. }
  31903. }
  31904. }
  31905. };
  31906. Sound.prototype._createSpatialParameters = function () {
  31907. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31908. if (this._scene.headphone) {
  31909. this._panningModel = "HRTF";
  31910. }
  31911. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  31912. this._updateSpatialParameters();
  31913. this._soundPanner.connect(this._ouputAudioNode);
  31914. this._inputAudioNode = this._soundPanner;
  31915. }
  31916. };
  31917. Sound.prototype._updateSpatialParameters = function () {
  31918. if (this.spatialSound) {
  31919. if (this.useCustomAttenuation) {
  31920. // Tricks to disable in a way embedded Web Audio attenuation
  31921. this._soundPanner.distanceModel = "linear";
  31922. this._soundPanner.maxDistance = Number.MAX_VALUE;
  31923. this._soundPanner.refDistance = 1;
  31924. this._soundPanner.rolloffFactor = 1;
  31925. this._soundPanner.panningModel = this._panningModel;
  31926. }
  31927. else {
  31928. this._soundPanner.distanceModel = this.distanceModel;
  31929. this._soundPanner.maxDistance = this.maxDistance;
  31930. this._soundPanner.refDistance = this.refDistance;
  31931. this._soundPanner.rolloffFactor = this.rolloffFactor;
  31932. this._soundPanner.panningModel = this._panningModel;
  31933. }
  31934. }
  31935. };
  31936. Sound.prototype.switchPanningModelToHRTF = function () {
  31937. this._panningModel = "HRTF";
  31938. this._switchPanningModel();
  31939. };
  31940. Sound.prototype.switchPanningModelToEqualPower = function () {
  31941. this._panningModel = "equalpower";
  31942. this._switchPanningModel();
  31943. };
  31944. Sound.prototype._switchPanningModel = function () {
  31945. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31946. this._soundPanner.panningModel = this._panningModel;
  31947. }
  31948. };
  31949. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  31950. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31951. if (this._isOutputConnected) {
  31952. this._ouputAudioNode.disconnect();
  31953. }
  31954. this._ouputAudioNode.connect(soundTrackAudioNode);
  31955. this._isOutputConnected = true;
  31956. }
  31957. };
  31958. /**
  31959. * Transform this sound into a directional source
  31960. * @param coneInnerAngle Size of the inner cone in degree
  31961. * @param coneOuterAngle Size of the outer cone in degree
  31962. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  31963. */
  31964. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  31965. if (coneOuterAngle < coneInnerAngle) {
  31966. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  31967. return;
  31968. }
  31969. this._coneInnerAngle = coneInnerAngle;
  31970. this._coneOuterAngle = coneOuterAngle;
  31971. this._coneOuterGain = coneOuterGain;
  31972. this._isDirectional = true;
  31973. if (this.isPlaying && this.loop) {
  31974. this.stop();
  31975. this.play();
  31976. }
  31977. };
  31978. Sound.prototype.setPosition = function (newPosition) {
  31979. this._position = newPosition;
  31980. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31981. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31982. }
  31983. };
  31984. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  31985. this._localDirection = newLocalDirection;
  31986. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  31987. this._updateDirection();
  31988. }
  31989. };
  31990. Sound.prototype._updateDirection = function () {
  31991. var mat = this._connectedMesh.getWorldMatrix();
  31992. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  31993. direction.normalize();
  31994. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  31995. };
  31996. Sound.prototype.updateDistanceFromListener = function () {
  31997. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  31998. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  31999. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  32000. }
  32001. };
  32002. Sound.prototype.setAttenuationFunction = function (callback) {
  32003. this._customAttenuationFunction = callback;
  32004. };
  32005. /**
  32006. * Play the sound
  32007. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  32008. */
  32009. Sound.prototype.play = function (time) {
  32010. var _this = this;
  32011. if (this._isReadyToPlay && this._scene.audioEnabled) {
  32012. try {
  32013. if (this._startOffset < 0) {
  32014. time = -this._startOffset;
  32015. this._startOffset = 0;
  32016. }
  32017. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  32018. if (!this._soundSource || !this._streamingSource) {
  32019. if (this.spatialSound) {
  32020. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  32021. if (this._isDirectional) {
  32022. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  32023. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  32024. this._soundPanner.coneOuterGain = this._coneOuterGain;
  32025. if (this._connectedMesh) {
  32026. this._updateDirection();
  32027. }
  32028. else {
  32029. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  32030. }
  32031. }
  32032. }
  32033. }
  32034. if (this._streaming) {
  32035. if (!this._streamingSource) {
  32036. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  32037. this._htmlAudioElement.onended = function () { _this._onended(); };
  32038. this._htmlAudioElement.playbackRate = this._playbackRate;
  32039. }
  32040. this._streamingSource.disconnect();
  32041. this._streamingSource.connect(this._inputAudioNode);
  32042. this._htmlAudioElement.play();
  32043. }
  32044. else {
  32045. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  32046. this._soundSource.buffer = this._audioBuffer;
  32047. this._soundSource.connect(this._inputAudioNode);
  32048. this._soundSource.loop = this.loop;
  32049. this._soundSource.playbackRate.value = this._playbackRate;
  32050. this._soundSource.onended = function () { _this._onended(); };
  32051. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  32052. }
  32053. this._startTime = startTime;
  32054. this.isPlaying = true;
  32055. this.isPaused = false;
  32056. }
  32057. catch (ex) {
  32058. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  32059. }
  32060. }
  32061. };
  32062. Sound.prototype._onended = function () {
  32063. this.isPlaying = false;
  32064. if (this.onended) {
  32065. this.onended();
  32066. }
  32067. };
  32068. /**
  32069. * Stop the sound
  32070. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  32071. */
  32072. Sound.prototype.stop = function (time) {
  32073. if (this.isPlaying) {
  32074. if (this._streaming) {
  32075. this._htmlAudioElement.pause();
  32076. // Test needed for Firefox or it will generate an Invalid State Error
  32077. if (this._htmlAudioElement.currentTime > 0) {
  32078. this._htmlAudioElement.currentTime = 0;
  32079. }
  32080. }
  32081. else {
  32082. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  32083. this._soundSource.stop(stopTime);
  32084. if (!this.isPaused) {
  32085. this._startOffset = 0;
  32086. }
  32087. }
  32088. this.isPlaying = false;
  32089. }
  32090. };
  32091. Sound.prototype.pause = function () {
  32092. if (this.isPlaying) {
  32093. this.isPaused = true;
  32094. if (this._streaming) {
  32095. this._htmlAudioElement.pause();
  32096. }
  32097. else {
  32098. this.stop(0);
  32099. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  32100. }
  32101. }
  32102. };
  32103. Sound.prototype.setVolume = function (newVolume, time) {
  32104. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32105. if (time) {
  32106. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  32107. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  32108. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  32109. }
  32110. else {
  32111. this._soundGain.gain.value = newVolume;
  32112. }
  32113. }
  32114. this._volume = newVolume;
  32115. };
  32116. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  32117. this._playbackRate = newPlaybackRate;
  32118. if (this.isPlaying) {
  32119. if (this._streaming) {
  32120. this._htmlAudioElement.playbackRate = this._playbackRate;
  32121. }
  32122. else {
  32123. this._soundSource.playbackRate.value = this._playbackRate;
  32124. }
  32125. }
  32126. };
  32127. Sound.prototype.getVolume = function () {
  32128. return this._volume;
  32129. };
  32130. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  32131. var _this = this;
  32132. if (this._connectedMesh) {
  32133. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  32134. this._registerFunc = null;
  32135. }
  32136. this._connectedMesh = meshToConnectTo;
  32137. if (!this.spatialSound) {
  32138. this.spatialSound = true;
  32139. this._createSpatialParameters();
  32140. if (this.isPlaying && this.loop) {
  32141. this.stop();
  32142. this.play();
  32143. }
  32144. }
  32145. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  32146. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  32147. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  32148. };
  32149. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  32150. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  32151. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  32152. this._updateDirection();
  32153. }
  32154. };
  32155. Sound.prototype.clone = function () {
  32156. var _this = this;
  32157. if (!this._streaming) {
  32158. var setBufferAndRun = function () {
  32159. if (_this._isReadyToPlay) {
  32160. clonedSound._audioBuffer = _this.getAudioBuffer();
  32161. clonedSound._isReadyToPlay = true;
  32162. if (clonedSound.autoplay) {
  32163. clonedSound.play();
  32164. }
  32165. }
  32166. else {
  32167. window.setTimeout(setBufferAndRun, 300);
  32168. }
  32169. };
  32170. var currentOptions = {
  32171. autoplay: this.autoplay, loop: this.loop,
  32172. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  32173. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  32174. refDistance: this.refDistance, distanceModel: this.distanceModel
  32175. };
  32176. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  32177. if (this.useCustomAttenuation) {
  32178. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  32179. }
  32180. clonedSound.setPosition(this._position);
  32181. clonedSound.setPlaybackRate(this._playbackRate);
  32182. setBufferAndRun();
  32183. return clonedSound;
  32184. }
  32185. else {
  32186. return null;
  32187. }
  32188. };
  32189. Sound.prototype.getAudioBuffer = function () {
  32190. return this._audioBuffer;
  32191. };
  32192. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  32193. var soundName = parsedSound.name;
  32194. var soundUrl;
  32195. if (parsedSound.url) {
  32196. soundUrl = rootUrl + parsedSound.url;
  32197. }
  32198. else {
  32199. soundUrl = rootUrl + soundName;
  32200. }
  32201. var options = {
  32202. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  32203. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  32204. rolloffFactor: parsedSound.rolloffFactor,
  32205. refDistance: parsedSound.refDistance,
  32206. distanceModel: parsedSound.distanceModel,
  32207. playbackRate: parsedSound.playbackRate
  32208. };
  32209. var newSound;
  32210. if (!sourceSound) {
  32211. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  32212. scene._addPendingData(newSound);
  32213. }
  32214. else {
  32215. var setBufferAndRun = function () {
  32216. if (sourceSound._isReadyToPlay) {
  32217. newSound._audioBuffer = sourceSound.getAudioBuffer();
  32218. newSound._isReadyToPlay = true;
  32219. if (newSound.autoplay) {
  32220. newSound.play();
  32221. }
  32222. }
  32223. else {
  32224. window.setTimeout(setBufferAndRun, 300);
  32225. }
  32226. };
  32227. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  32228. setBufferAndRun();
  32229. }
  32230. if (parsedSound.position) {
  32231. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  32232. newSound.setPosition(soundPosition);
  32233. }
  32234. if (parsedSound.isDirectional) {
  32235. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  32236. if (parsedSound.localDirectionToMesh) {
  32237. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  32238. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  32239. }
  32240. }
  32241. if (parsedSound.connectedMeshId) {
  32242. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  32243. if (connectedMesh) {
  32244. newSound.attachToMesh(connectedMesh);
  32245. }
  32246. }
  32247. return newSound;
  32248. };
  32249. return Sound;
  32250. })();
  32251. BABYLON.Sound = Sound;
  32252. })(BABYLON || (BABYLON = {}));
  32253. var BABYLON;
  32254. (function (BABYLON) {
  32255. var SoundTrack = (function () {
  32256. function SoundTrack(scene, options) {
  32257. this.id = -1;
  32258. this._isMainTrack = false;
  32259. this._isInitialized = false;
  32260. this._scene = scene;
  32261. this.soundCollection = new Array();
  32262. this._options = options;
  32263. if (!this._isMainTrack) {
  32264. this._scene.soundTracks.push(this);
  32265. this.id = this._scene.soundTracks.length - 1;
  32266. }
  32267. }
  32268. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  32269. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32270. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  32271. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  32272. if (this._options) {
  32273. if (this._options.volume) {
  32274. this._outputAudioNode.gain.value = this._options.volume;
  32275. }
  32276. if (this._options.mainTrack) {
  32277. this._isMainTrack = this._options.mainTrack;
  32278. }
  32279. }
  32280. this._isInitialized = true;
  32281. }
  32282. };
  32283. SoundTrack.prototype.dispose = function () {
  32284. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32285. if (this._connectedAnalyser) {
  32286. this._connectedAnalyser.stopDebugCanvas();
  32287. }
  32288. while (this.soundCollection.length) {
  32289. this.soundCollection[0].dispose();
  32290. }
  32291. if (this._outputAudioNode) {
  32292. this._outputAudioNode.disconnect();
  32293. }
  32294. this._outputAudioNode = null;
  32295. }
  32296. };
  32297. SoundTrack.prototype.AddSound = function (sound) {
  32298. if (!this._isInitialized) {
  32299. this._initializeSoundTrackAudioGraph();
  32300. }
  32301. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32302. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  32303. }
  32304. if (sound.soundTrackId) {
  32305. if (sound.soundTrackId === -1) {
  32306. this._scene.mainSoundTrack.RemoveSound(sound);
  32307. }
  32308. else {
  32309. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  32310. }
  32311. }
  32312. this.soundCollection.push(sound);
  32313. sound.soundTrackId = this.id;
  32314. };
  32315. SoundTrack.prototype.RemoveSound = function (sound) {
  32316. var index = this.soundCollection.indexOf(sound);
  32317. if (index !== -1) {
  32318. this.soundCollection.splice(index, 1);
  32319. }
  32320. };
  32321. SoundTrack.prototype.setVolume = function (newVolume) {
  32322. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32323. this._outputAudioNode.gain.value = newVolume;
  32324. }
  32325. };
  32326. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  32327. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32328. for (var i = 0; i < this.soundCollection.length; i++) {
  32329. this.soundCollection[i].switchPanningModelToHRTF();
  32330. }
  32331. }
  32332. };
  32333. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  32334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32335. for (var i = 0; i < this.soundCollection.length; i++) {
  32336. this.soundCollection[i].switchPanningModelToEqualPower();
  32337. }
  32338. }
  32339. };
  32340. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  32341. if (this._connectedAnalyser) {
  32342. this._connectedAnalyser.stopDebugCanvas();
  32343. }
  32344. this._connectedAnalyser = analyser;
  32345. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32346. this._outputAudioNode.disconnect();
  32347. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  32348. }
  32349. };
  32350. return SoundTrack;
  32351. })();
  32352. BABYLON.SoundTrack = SoundTrack;
  32353. })(BABYLON || (BABYLON = {}));
  32354. var BABYLON;
  32355. (function (BABYLON) {
  32356. var SIMDVector3 = (function () {
  32357. function SIMDVector3() {
  32358. }
  32359. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  32360. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  32361. var m0 = SIMD.float32x4.load(transformation.m, 0);
  32362. var m1 = SIMD.float32x4.load(transformation.m, 4);
  32363. var m2 = SIMD.float32x4.load(transformation.m, 8);
  32364. var m3 = SIMD.float32x4.load(transformation.m, 12);
  32365. 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));
  32366. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  32367. SIMD.float32x4.storeXYZ(result._data, 0, r);
  32368. };
  32369. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  32370. var v0 = SIMD.float32x4.splat(x);
  32371. var v1 = SIMD.float32x4.splat(y);
  32372. var v2 = SIMD.float32x4.splat(z);
  32373. var m0 = SIMD.float32x4.load(transformation.m, 0);
  32374. var m1 = SIMD.float32x4.load(transformation.m, 4);
  32375. var m2 = SIMD.float32x4.load(transformation.m, 8);
  32376. var m3 = SIMD.float32x4.load(transformation.m, 12);
  32377. 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));
  32378. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  32379. SIMD.float32x4.storeXYZ(result._data, 0, r);
  32380. };
  32381. return SIMDVector3;
  32382. })();
  32383. BABYLON.SIMDVector3 = SIMDVector3;
  32384. var SIMDMatrix = (function () {
  32385. function SIMDMatrix() {
  32386. }
  32387. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  32388. if (offset === void 0) { offset = 0; }
  32389. var tm = this.m;
  32390. var om = other.m;
  32391. var om0 = SIMD.float32x4.load(om, 0);
  32392. var om1 = SIMD.float32x4.load(om, 4);
  32393. var om2 = SIMD.float32x4.load(om, 8);
  32394. var om3 = SIMD.float32x4.load(om, 12);
  32395. var tm0 = SIMD.float32x4.load(tm, 0);
  32396. 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)))));
  32397. var tm1 = SIMD.float32x4.load(tm, 4);
  32398. 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)))));
  32399. var tm2 = SIMD.float32x4.load(tm, 8);
  32400. 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)))));
  32401. var tm3 = SIMD.float32x4.load(tm, 12);
  32402. 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)))));
  32403. };
  32404. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  32405. var src = this.m;
  32406. var dest = other.m;
  32407. var row0, row1, row2, row3;
  32408. var tmp1;
  32409. var minor0, minor1, minor2, minor3;
  32410. var det;
  32411. // Load the 4 rows
  32412. var src0 = SIMD.float32x4.load(src, 0);
  32413. var src1 = SIMD.float32x4.load(src, 4);
  32414. var src2 = SIMD.float32x4.load(src, 8);
  32415. var src3 = SIMD.float32x4.load(src, 12);
  32416. // Transpose the source matrix. Sort of. Not a true transpose operation
  32417. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  32418. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  32419. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  32420. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  32421. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  32422. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  32423. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  32424. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  32425. // This is a true transposition, but it will lead to an incorrect result
  32426. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  32427. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  32428. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  32429. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  32430. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  32431. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  32432. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  32433. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  32434. // ----
  32435. tmp1 = SIMD.float32x4.mul(row2, row3);
  32436. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32437. minor0 = SIMD.float32x4.mul(row1, tmp1);
  32438. minor1 = SIMD.float32x4.mul(row0, tmp1);
  32439. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32440. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  32441. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  32442. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  32443. // ----
  32444. tmp1 = SIMD.float32x4.mul(row1, row2);
  32445. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32446. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  32447. minor3 = SIMD.float32x4.mul(row0, tmp1);
  32448. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32449. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  32450. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  32451. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  32452. // ----
  32453. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  32454. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32455. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  32456. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  32457. minor2 = SIMD.float32x4.mul(row0, tmp1);
  32458. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32459. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  32460. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  32461. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  32462. // ----
  32463. tmp1 = SIMD.float32x4.mul(row0, row1);
  32464. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32465. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  32466. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  32467. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32468. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  32469. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  32470. // ----
  32471. tmp1 = SIMD.float32x4.mul(row0, row3);
  32472. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32473. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  32474. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  32475. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32476. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  32477. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  32478. // ----
  32479. tmp1 = SIMD.float32x4.mul(row0, row2);
  32480. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32481. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  32482. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  32483. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32484. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  32485. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  32486. // Compute determinant
  32487. det = SIMD.float32x4.mul(row0, minor0);
  32488. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  32489. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  32490. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  32491. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  32492. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  32493. // These shuffles aren't necessary if the faulty transposition is done
  32494. // up at the top of this function.
  32495. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  32496. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  32497. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  32498. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  32499. // Compute final values by multiplying with 1/det
  32500. minor0 = SIMD.float32x4.mul(det, minor0);
  32501. minor1 = SIMD.float32x4.mul(det, minor1);
  32502. minor2 = SIMD.float32x4.mul(det, minor2);
  32503. minor3 = SIMD.float32x4.mul(det, minor3);
  32504. SIMD.float32x4.store(dest, 0, minor0);
  32505. SIMD.float32x4.store(dest, 4, minor1);
  32506. SIMD.float32x4.store(dest, 8, minor2);
  32507. SIMD.float32x4.store(dest, 12, minor3);
  32508. return this;
  32509. };
  32510. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  32511. var out = result.m;
  32512. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  32513. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  32514. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  32515. // cc.kmVec3Subtract(f, pCenter, pEye);
  32516. var f = SIMD.float32x4.sub(center, eye);
  32517. // cc.kmVec3Normalize(f, f);
  32518. var tmp = SIMD.float32x4.mul(f, f);
  32519. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32520. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32521. // cc.kmVec3Assign(up, pUp);
  32522. // cc.kmVec3Normalize(up, up);
  32523. tmp = SIMD.float32x4.mul(up, up);
  32524. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32525. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32526. // cc.kmVec3Cross(s, f, up);
  32527. 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)));
  32528. // cc.kmVec3Normalize(s, s);
  32529. tmp = SIMD.float32x4.mul(s, s);
  32530. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32531. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32532. // cc.kmVec3Cross(u, s, f);
  32533. 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)));
  32534. // cc.kmVec3Normalize(s, s);
  32535. tmp = SIMD.float32x4.mul(s, s);
  32536. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32537. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32538. var zero = SIMD.float32x4.splat(0.0);
  32539. s = SIMD.float32x4.neg(s);
  32540. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  32541. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  32542. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  32543. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  32544. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  32545. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  32546. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  32547. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  32548. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  32549. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  32550. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  32551. var b3 = SIMD.float32x4.neg(eye);
  32552. b3 = SIMD.float32x4.withW(b3, 1.0);
  32553. 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)))));
  32554. 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)))));
  32555. 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)))));
  32556. 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)))));
  32557. };
  32558. return SIMDMatrix;
  32559. })();
  32560. BABYLON.SIMDMatrix = SIMDMatrix;
  32561. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  32562. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  32563. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  32564. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  32565. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  32566. var SIMDHelper = (function () {
  32567. function SIMDHelper() {
  32568. }
  32569. Object.defineProperty(SIMDHelper, "IsEnabled", {
  32570. get: function () {
  32571. return SIMDHelper._isEnabled;
  32572. },
  32573. enumerable: true,
  32574. configurable: true
  32575. });
  32576. SIMDHelper.DisableSIMD = function () {
  32577. // Replace functions
  32578. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  32579. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  32580. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  32581. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  32582. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  32583. SIMDHelper._isEnabled = false;
  32584. };
  32585. SIMDHelper.EnableSIMD = function () {
  32586. if (window.SIMD === undefined) {
  32587. return;
  32588. }
  32589. // Replace functions
  32590. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  32591. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  32592. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  32593. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  32594. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  32595. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  32596. get: function () { return this._data[0]; },
  32597. set: function (value) {
  32598. if (!this._data) {
  32599. this._data = new Float32Array(3);
  32600. }
  32601. this._data[0] = value;
  32602. }
  32603. });
  32604. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  32605. get: function () { return this._data[1]; },
  32606. set: function (value) {
  32607. this._data[1] = value;
  32608. }
  32609. });
  32610. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  32611. get: function () { return this._data[2]; },
  32612. set: function (value) {
  32613. this._data[2] = value;
  32614. }
  32615. });
  32616. SIMDHelper._isEnabled = true;
  32617. };
  32618. SIMDHelper._isEnabled = false;
  32619. return SIMDHelper;
  32620. })();
  32621. BABYLON.SIMDHelper = SIMDHelper;
  32622. })(BABYLON || (BABYLON = {}));
  32623. var BABYLON;
  32624. (function (BABYLON) {
  32625. var ShaderMaterial = (function (_super) {
  32626. __extends(ShaderMaterial, _super);
  32627. function ShaderMaterial(name, scene, shaderPath, options) {
  32628. _super.call(this, name, scene);
  32629. this._textures = {};
  32630. this._floats = {};
  32631. this._floatsArrays = {};
  32632. this._colors3 = {};
  32633. this._colors4 = {};
  32634. this._vectors2 = {};
  32635. this._vectors3 = {};
  32636. this._vectors4 = {};
  32637. this._matrices = {};
  32638. this._matrices3x3 = {};
  32639. this._matrices2x2 = {};
  32640. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  32641. this._shaderPath = shaderPath;
  32642. options.needAlphaBlending = options.needAlphaBlending || false;
  32643. options.needAlphaTesting = options.needAlphaTesting || false;
  32644. options.attributes = options.attributes || ["position", "normal", "uv"];
  32645. options.uniforms = options.uniforms || ["worldViewProjection"];
  32646. options.samplers = options.samplers || [];
  32647. options.defines = options.defines || [];
  32648. this._options = options;
  32649. }
  32650. ShaderMaterial.prototype.needAlphaBlending = function () {
  32651. return this._options.needAlphaBlending;
  32652. };
  32653. ShaderMaterial.prototype.needAlphaTesting = function () {
  32654. return this._options.needAlphaTesting;
  32655. };
  32656. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  32657. if (this._options.uniforms.indexOf(uniformName) === -1) {
  32658. this._options.uniforms.push(uniformName);
  32659. }
  32660. };
  32661. ShaderMaterial.prototype.setTexture = function (name, texture) {
  32662. if (this._options.samplers.indexOf(name) === -1) {
  32663. this._options.samplers.push(name);
  32664. }
  32665. this._textures[name] = texture;
  32666. return this;
  32667. };
  32668. ShaderMaterial.prototype.setFloat = function (name, value) {
  32669. this._checkUniform(name);
  32670. this._floats[name] = value;
  32671. return this;
  32672. };
  32673. ShaderMaterial.prototype.setFloats = function (name, value) {
  32674. this._checkUniform(name);
  32675. this._floatsArrays[name] = value;
  32676. return this;
  32677. };
  32678. ShaderMaterial.prototype.setColor3 = function (name, value) {
  32679. this._checkUniform(name);
  32680. this._colors3[name] = value;
  32681. return this;
  32682. };
  32683. ShaderMaterial.prototype.setColor4 = function (name, value) {
  32684. this._checkUniform(name);
  32685. this._colors4[name] = value;
  32686. return this;
  32687. };
  32688. ShaderMaterial.prototype.setVector2 = function (name, value) {
  32689. this._checkUniform(name);
  32690. this._vectors2[name] = value;
  32691. return this;
  32692. };
  32693. ShaderMaterial.prototype.setVector3 = function (name, value) {
  32694. this._checkUniform(name);
  32695. this._vectors3[name] = value;
  32696. return this;
  32697. };
  32698. ShaderMaterial.prototype.setVector4 = function (name, value) {
  32699. this._checkUniform(name);
  32700. this._vectors4[name] = value;
  32701. return this;
  32702. };
  32703. ShaderMaterial.prototype.setMatrix = function (name, value) {
  32704. this._checkUniform(name);
  32705. this._matrices[name] = value;
  32706. return this;
  32707. };
  32708. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  32709. this._checkUniform(name);
  32710. this._matrices3x3[name] = value;
  32711. return this;
  32712. };
  32713. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  32714. this._checkUniform(name);
  32715. this._matrices2x2[name] = value;
  32716. return this;
  32717. };
  32718. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  32719. var scene = this.getScene();
  32720. var engine = scene.getEngine();
  32721. if (!this.checkReadyOnEveryCall) {
  32722. if (this._renderId === scene.getRenderId()) {
  32723. return true;
  32724. }
  32725. }
  32726. // Instances
  32727. var defines = [];
  32728. var fallbacks = new BABYLON.EffectFallbacks();
  32729. if (useInstances) {
  32730. defines.push("#define INSTANCES");
  32731. }
  32732. for (var index = 0; index < this._options.defines.length; index++) {
  32733. defines.push(this._options.defines[index]);
  32734. }
  32735. // Bones
  32736. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  32737. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32738. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32739. fallbacks.addCPUSkinningFallback(0, mesh);
  32740. }
  32741. // Alpha test
  32742. if (engine.getAlphaTesting()) {
  32743. defines.push("#define ALPHATEST");
  32744. }
  32745. var previousEffect = this._effect;
  32746. var join = defines.join("\n");
  32747. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  32748. if (!this._effect.isReady()) {
  32749. return false;
  32750. }
  32751. if (previousEffect !== this._effect) {
  32752. scene.resetCachedMaterial();
  32753. }
  32754. this._renderId = scene.getRenderId();
  32755. return true;
  32756. };
  32757. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32758. var scene = this.getScene();
  32759. if (this._options.uniforms.indexOf("world") !== -1) {
  32760. this._effect.setMatrix("world", world);
  32761. }
  32762. if (this._options.uniforms.indexOf("worldView") !== -1) {
  32763. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  32764. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  32765. }
  32766. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  32767. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  32768. }
  32769. };
  32770. ShaderMaterial.prototype.bind = function (world, mesh) {
  32771. // Std values
  32772. this.bindOnlyWorldMatrix(world);
  32773. if (this.getScene().getCachedMaterial() !== this) {
  32774. if (this._options.uniforms.indexOf("view") !== -1) {
  32775. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  32776. }
  32777. if (this._options.uniforms.indexOf("projection") !== -1) {
  32778. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  32779. }
  32780. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  32781. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32782. }
  32783. // Bones
  32784. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  32785. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32786. }
  32787. // Texture
  32788. for (var name in this._textures) {
  32789. this._effect.setTexture(name, this._textures[name]);
  32790. }
  32791. // Float
  32792. for (name in this._floats) {
  32793. this._effect.setFloat(name, this._floats[name]);
  32794. }
  32795. // Float s
  32796. for (name in this._floatsArrays) {
  32797. this._effect.setArray(name, this._floatsArrays[name]);
  32798. }
  32799. // Color3
  32800. for (name in this._colors3) {
  32801. this._effect.setColor3(name, this._colors3[name]);
  32802. }
  32803. // Color4
  32804. for (name in this._colors4) {
  32805. var color = this._colors4[name];
  32806. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  32807. }
  32808. // Vector2
  32809. for (name in this._vectors2) {
  32810. this._effect.setVector2(name, this._vectors2[name]);
  32811. }
  32812. // Vector3
  32813. for (name in this._vectors3) {
  32814. this._effect.setVector3(name, this._vectors3[name]);
  32815. }
  32816. // Vector4
  32817. for (name in this._vectors4) {
  32818. this._effect.setVector4(name, this._vectors4[name]);
  32819. }
  32820. // Matrix
  32821. for (name in this._matrices) {
  32822. this._effect.setMatrix(name, this._matrices[name]);
  32823. }
  32824. // Matrix 3x3
  32825. for (name in this._matrices3x3) {
  32826. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  32827. }
  32828. // Matrix 2x2
  32829. for (name in this._matrices2x2) {
  32830. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  32831. }
  32832. }
  32833. _super.prototype.bind.call(this, world, mesh);
  32834. };
  32835. ShaderMaterial.prototype.clone = function (name) {
  32836. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  32837. return newShaderMaterial;
  32838. };
  32839. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  32840. for (var name in this._textures) {
  32841. this._textures[name].dispose();
  32842. }
  32843. this._textures = {};
  32844. _super.prototype.dispose.call(this, forceDisposeEffect);
  32845. };
  32846. ShaderMaterial.prototype.serialize = function () {
  32847. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32848. serializationObject.customType = "BABYLON.ShaderMaterial";
  32849. serializationObject.options = this._options;
  32850. serializationObject.shaderPath = this._shaderPath;
  32851. // Texture
  32852. serializationObject.textures = {};
  32853. for (var name in this._textures) {
  32854. serializationObject.textures[name] = this._textures[name].serialize();
  32855. }
  32856. // Float
  32857. serializationObject.floats = {};
  32858. for (name in this._floats) {
  32859. serializationObject.floats[name] = this._floats[name];
  32860. }
  32861. // Float s
  32862. serializationObject.floatArrays = {};
  32863. for (name in this._floatsArrays) {
  32864. serializationObject.floatArrays[name] = this._floatsArrays[name];
  32865. }
  32866. // Color3
  32867. serializationObject.colors3 = {};
  32868. for (name in this._colors3) {
  32869. serializationObject.colors3[name] = this._colors3[name].asArray();
  32870. }
  32871. // Color4
  32872. serializationObject.colors4 = {};
  32873. for (name in this._colors4) {
  32874. serializationObject.colors4[name] = this._colors4[name].asArray();
  32875. }
  32876. // Vector2
  32877. serializationObject.vectors2 = {};
  32878. for (name in this._vectors2) {
  32879. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  32880. }
  32881. // Vector3
  32882. serializationObject.vectors3 = {};
  32883. for (name in this._vectors3) {
  32884. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  32885. }
  32886. // Vector4
  32887. serializationObject.vectors4 = {};
  32888. for (name in this._vectors4) {
  32889. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  32890. }
  32891. // Matrix
  32892. serializationObject.matrices = {};
  32893. for (name in this._matrices) {
  32894. serializationObject.matrices[name] = this._matrices[name].asArray();
  32895. }
  32896. // Matrix 3x3
  32897. serializationObject.matrices3x3 = {};
  32898. for (name in this._matrices3x3) {
  32899. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  32900. }
  32901. // Matrix 2x2
  32902. serializationObject.matrices2x2 = {};
  32903. for (name in this._matrices2x2) {
  32904. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  32905. }
  32906. return serializationObject;
  32907. };
  32908. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  32909. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  32910. // Texture
  32911. for (var name in source.textures) {
  32912. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  32913. }
  32914. // Float
  32915. for (name in source.floats) {
  32916. material.setFloat(name, source.floats[name]);
  32917. }
  32918. // Float s
  32919. for (name in source.floatsArrays) {
  32920. material.setFloats(name, source.floatsArrays[name]);
  32921. }
  32922. // Color3
  32923. for (name in source.colors3) {
  32924. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  32925. }
  32926. // Color4
  32927. for (name in source.colors4) {
  32928. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  32929. }
  32930. // Vector2
  32931. for (name in source.vectors2) {
  32932. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  32933. }
  32934. // Vector3
  32935. for (name in source.vectors3) {
  32936. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  32937. }
  32938. // Vector4
  32939. for (name in source.vectors4) {
  32940. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  32941. }
  32942. // Matrix
  32943. for (name in source.matrices) {
  32944. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  32945. }
  32946. // Matrix 3x3
  32947. for (name in source.matrices3x3) {
  32948. material.setMatrix3x3(name, source.matrices3x3[name]);
  32949. }
  32950. // Matrix 2x2
  32951. for (name in source.matrices2x2) {
  32952. material.setMatrix2x2(name, source.matrices2x2[name]);
  32953. }
  32954. return material;
  32955. };
  32956. return ShaderMaterial;
  32957. })(BABYLON.Material);
  32958. BABYLON.ShaderMaterial = ShaderMaterial;
  32959. })(BABYLON || (BABYLON = {}));
  32960. var BABYLON;
  32961. (function (BABYLON) {
  32962. var Internals;
  32963. (function (Internals) {
  32964. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32965. // All values and structures referenced from:
  32966. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32967. var DDS_MAGIC = 0x20534444;
  32968. 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;
  32969. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32970. 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;
  32971. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32972. function FourCCToInt32(value) {
  32973. return value.charCodeAt(0) +
  32974. (value.charCodeAt(1) << 8) +
  32975. (value.charCodeAt(2) << 16) +
  32976. (value.charCodeAt(3) << 24);
  32977. }
  32978. function Int32ToFourCC(value) {
  32979. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32980. }
  32981. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32982. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32983. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32984. var headerLengthInt = 31; // The header length in 32 bit ints
  32985. // Offsets into the header array
  32986. var off_magic = 0;
  32987. var off_size = 1;
  32988. var off_flags = 2;
  32989. var off_height = 3;
  32990. var off_width = 4;
  32991. var off_mipmapCount = 7;
  32992. var off_pfFlags = 20;
  32993. var off_pfFourCC = 21;
  32994. var off_RGBbpp = 22;
  32995. var off_RMask = 23;
  32996. var off_GMask = 24;
  32997. var off_BMask = 25;
  32998. var off_AMask = 26;
  32999. var off_caps1 = 27;
  33000. var off_caps2 = 28;
  33001. ;
  33002. var DDSTools = (function () {
  33003. function DDSTools() {
  33004. }
  33005. DDSTools.GetDDSInfo = function (arrayBuffer) {
  33006. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  33007. var mipmapCount = 1;
  33008. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  33009. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33010. }
  33011. return {
  33012. width: header[off_width],
  33013. height: header[off_height],
  33014. mipmapCount: mipmapCount,
  33015. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  33016. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  33017. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  33018. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  33019. };
  33020. };
  33021. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33022. var byteArray = new Uint8Array(dataLength);
  33023. var srcData = new Uint8Array(arrayBuffer);
  33024. var index = 0;
  33025. for (var y = height - 1; y >= 0; y--) {
  33026. for (var x = 0; x < width; x++) {
  33027. var srcPos = dataOffset + (x + y * width) * 4;
  33028. byteArray[index + 2] = srcData[srcPos];
  33029. byteArray[index + 1] = srcData[srcPos + 1];
  33030. byteArray[index] = srcData[srcPos + 2];
  33031. byteArray[index + 3] = srcData[srcPos + 3];
  33032. index += 4;
  33033. }
  33034. }
  33035. return byteArray;
  33036. };
  33037. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33038. var byteArray = new Uint8Array(dataLength);
  33039. var srcData = new Uint8Array(arrayBuffer);
  33040. var index = 0;
  33041. for (var y = height - 1; y >= 0; y--) {
  33042. for (var x = 0; x < width; x++) {
  33043. var srcPos = dataOffset + (x + y * width) * 3;
  33044. byteArray[index + 2] = srcData[srcPos];
  33045. byteArray[index + 1] = srcData[srcPos + 1];
  33046. byteArray[index] = srcData[srcPos + 2];
  33047. index += 3;
  33048. }
  33049. }
  33050. return byteArray;
  33051. };
  33052. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33053. var byteArray = new Uint8Array(dataLength);
  33054. var srcData = new Uint8Array(arrayBuffer);
  33055. var index = 0;
  33056. for (var y = height - 1; y >= 0; y--) {
  33057. for (var x = 0; x < width; x++) {
  33058. var srcPos = dataOffset + (x + y * width);
  33059. byteArray[index] = srcData[srcPos];
  33060. index++;
  33061. }
  33062. }
  33063. return byteArray;
  33064. };
  33065. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  33066. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  33067. if (header[off_magic] != DDS_MAGIC) {
  33068. BABYLON.Tools.Error("Invalid magic number in DDS header");
  33069. return;
  33070. }
  33071. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  33072. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  33073. return;
  33074. }
  33075. if (info.isFourCC) {
  33076. fourCC = header[off_pfFourCC];
  33077. switch (fourCC) {
  33078. case FOURCC_DXT1:
  33079. blockBytes = 8;
  33080. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33081. break;
  33082. case FOURCC_DXT3:
  33083. blockBytes = 16;
  33084. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33085. break;
  33086. case FOURCC_DXT5:
  33087. blockBytes = 16;
  33088. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  33089. break;
  33090. default:
  33091. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  33092. return;
  33093. }
  33094. }
  33095. mipmapCount = 1;
  33096. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  33097. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33098. }
  33099. var bpp = header[off_RGBbpp];
  33100. for (var face = 0; face < faces; face++) {
  33101. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33102. width = header[off_width];
  33103. height = header[off_height];
  33104. dataOffset = header[off_size] + 4;
  33105. for (i = 0; i < mipmapCount; ++i) {
  33106. if (info.isRGB) {
  33107. if (bpp === 24) {
  33108. dataLength = width * height * 3;
  33109. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33110. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33111. }
  33112. else {
  33113. dataLength = width * height * 4;
  33114. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33115. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33116. }
  33117. }
  33118. else if (info.isLuminance) {
  33119. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33120. var unpaddedRowSize = width;
  33121. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33122. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33123. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33124. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33125. }
  33126. else {
  33127. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33128. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33129. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  33130. }
  33131. dataOffset += dataLength;
  33132. width *= 0.5;
  33133. height *= 0.5;
  33134. width = Math.max(1.0, width);
  33135. height = Math.max(1.0, height);
  33136. }
  33137. }
  33138. };
  33139. return DDSTools;
  33140. })();
  33141. Internals.DDSTools = DDSTools;
  33142. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33143. })(BABYLON || (BABYLON = {}));
  33144. var BABYLON;
  33145. (function (BABYLON) {
  33146. var CannonJSPlugin = (function () {
  33147. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  33148. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  33149. if (iterations === void 0) { iterations = 10; }
  33150. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  33151. this.name = "CannonJSPlugin";
  33152. this._physicsMaterials = [];
  33153. this._fixedTimeStep = 1 / 60;
  33154. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  33155. this._currentCollisionGroup = 2;
  33156. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  33157. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  33158. this._tmpPosition = BABYLON.Vector3.Zero();
  33159. this._tmpQuaternion = new BABYLON.Quaternion();
  33160. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  33161. this._tmpDeltaRotation = new BABYLON.Quaternion();
  33162. this._tmpUnityRotation = new BABYLON.Quaternion();
  33163. if (!this.isSupported()) {
  33164. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  33165. return;
  33166. }
  33167. this.world = new CANNON.World();
  33168. this.world.broadphase = new CANNON.NaiveBroadphase();
  33169. this.world.solver.iterations = iterations;
  33170. }
  33171. CannonJSPlugin.prototype.setGravity = function (gravity) {
  33172. this.world.gravity.copy(gravity);
  33173. };
  33174. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  33175. this._fixedTimeStep = timeStep;
  33176. };
  33177. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  33178. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  33179. };
  33180. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  33181. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  33182. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  33183. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  33184. };
  33185. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  33186. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  33187. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  33188. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  33189. };
  33190. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  33191. //parent-child relationship. Does this impostor has a parent impostor?
  33192. if (impostor.parent) {
  33193. if (impostor.physicsBody) {
  33194. this.removePhysicsBody(impostor);
  33195. //TODO is that needed?
  33196. impostor.forceUpdate();
  33197. }
  33198. return;
  33199. }
  33200. //should a new body be created for this impostor?
  33201. if (impostor.isBodyInitRequired()) {
  33202. if (!impostor.mesh.rotationQuaternion) {
  33203. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  33204. }
  33205. var shape = this._createShape(impostor);
  33206. //unregister events, if body is being changed
  33207. var oldBody = impostor.physicsBody;
  33208. if (oldBody) {
  33209. this.removePhysicsBody(impostor);
  33210. }
  33211. //create the body and material
  33212. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  33213. var bodyCreationObject = {
  33214. mass: impostor.getParam("mass"),
  33215. material: material
  33216. };
  33217. // A simple extend, in case native options were used.
  33218. var nativeOptions = impostor.getParam("nativeOptions");
  33219. for (var key in nativeOptions) {
  33220. if (nativeOptions.hasOwnProperty(key)) {
  33221. bodyCreationObject[key] = nativeOptions[key];
  33222. }
  33223. }
  33224. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  33225. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  33226. this.world.addEventListener("preStep", impostor.beforeStep);
  33227. this.world.addEventListener("postStep", impostor.afterStep);
  33228. impostor.physicsBody.addShape(shape);
  33229. this.world.add(impostor.physicsBody);
  33230. //try to keep the body moving in the right direction by taking old properties.
  33231. //Should be tested!
  33232. if (oldBody) {
  33233. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  33234. impostor.physicsBody[param].copy(oldBody[param]);
  33235. });
  33236. }
  33237. this._processChildMeshes(impostor);
  33238. }
  33239. //now update the body's transformation
  33240. this._updatePhysicsBodyTransformation(impostor);
  33241. };
  33242. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  33243. var _this = this;
  33244. var meshChildren = mainImpostor.mesh.getChildMeshes();
  33245. if (meshChildren.length) {
  33246. var processMesh = function (localPosition, mesh) {
  33247. var childImpostor = mesh.getPhysicsImpostor();
  33248. if (childImpostor) {
  33249. var parent = childImpostor.parent;
  33250. if (parent !== mainImpostor) {
  33251. var localPosition = mesh.position;
  33252. if (childImpostor.physicsBody) {
  33253. _this.removePhysicsBody(childImpostor);
  33254. childImpostor.physicsBody = null;
  33255. }
  33256. childImpostor.parent = mainImpostor;
  33257. childImpostor.resetUpdateFlags();
  33258. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  33259. //Add the mass of the children.
  33260. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  33261. }
  33262. }
  33263. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  33264. };
  33265. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  33266. }
  33267. };
  33268. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  33269. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  33270. this.world.removeEventListener("preStep", impostor.beforeStep);
  33271. this.world.removeEventListener("postStep", impostor.afterStep);
  33272. this.world.remove(impostor.physicsBody);
  33273. };
  33274. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  33275. var mainBody = impostorJoint.mainImpostor.physicsBody;
  33276. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  33277. if (!mainBody || !connectedBody) {
  33278. return;
  33279. }
  33280. var constraint;
  33281. var jointData = impostorJoint.joint.jointData;
  33282. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  33283. var constraintData = {
  33284. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  33285. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  33286. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  33287. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  33288. maxForce: jointData.nativeParams.maxForce,
  33289. collideConnected: !!jointData.collision
  33290. };
  33291. //Not needed, Cannon has a collideConnected flag
  33292. /*if (!jointData.collision) {
  33293. //add 1st body to a collision group of its own, if it is not in 1
  33294. if (mainBody.collisionFilterGroup === 1) {
  33295. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  33296. this._currentCollisionGroup <<= 1;
  33297. }
  33298. if (connectedBody.collisionFilterGroup === 1) {
  33299. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  33300. this._currentCollisionGroup <<= 1;
  33301. }
  33302. //add their mask to the collisionFilterMask of each other:
  33303. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  33304. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  33305. }*/
  33306. switch (impostorJoint.joint.type) {
  33307. case BABYLON.PhysicsJoint.HingeJoint:
  33308. case BABYLON.PhysicsJoint.Hinge2Joint:
  33309. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  33310. break;
  33311. case BABYLON.PhysicsJoint.DistanceJoint:
  33312. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  33313. break;
  33314. case BABYLON.PhysicsJoint.SpringJoint:
  33315. var springData = jointData;
  33316. constraint = new CANNON.Spring(mainBody, connectedBody, {
  33317. restLength: springData.length,
  33318. stiffness: springData.stiffness,
  33319. damping: springData.damping,
  33320. localAnchorA: constraintData.pivotA,
  33321. localAnchorB: constraintData.pivotB
  33322. });
  33323. break;
  33324. default:
  33325. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  33326. break;
  33327. }
  33328. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  33329. constraint.collideConnected = !!jointData.collision;
  33330. impostorJoint.joint.physicsJoint = constraint;
  33331. //don't add spring as constraint, as it is not one.
  33332. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  33333. this.world.addConstraint(constraint);
  33334. }
  33335. else {
  33336. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  33337. constraint.applyForce();
  33338. });
  33339. }
  33340. };
  33341. CannonJSPlugin.prototype.removeJoint = function (joint) {
  33342. //TODO
  33343. };
  33344. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  33345. var index;
  33346. var mat;
  33347. for (index = 0; index < this._physicsMaterials.length; index++) {
  33348. mat = this._physicsMaterials[index];
  33349. if (mat.friction === friction && mat.restitution === restitution) {
  33350. return mat;
  33351. }
  33352. }
  33353. var currentMat = new CANNON.Material("mat");
  33354. currentMat.friction = friction;
  33355. currentMat.restitution = restitution;
  33356. this._physicsMaterials.push(currentMat);
  33357. return currentMat;
  33358. };
  33359. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  33360. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  33361. };
  33362. CannonJSPlugin.prototype._createShape = function (impostor) {
  33363. var mesh = impostor.mesh;
  33364. //get the correct bounding box
  33365. var oldQuaternion = mesh.rotationQuaternion;
  33366. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  33367. mesh.computeWorldMatrix(true);
  33368. var returnValue;
  33369. switch (impostor.type) {
  33370. case BABYLON.PhysicsEngine.SphereImpostor:
  33371. var bbox = mesh.getBoundingInfo().boundingBox;
  33372. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  33373. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  33374. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  33375. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  33376. break;
  33377. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  33378. case BABYLON.PhysicsEngine.CylinderImpostor:
  33379. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  33380. case BABYLON.PhysicsEngine.BoxImpostor:
  33381. bbox = mesh.getBoundingInfo().boundingBox;
  33382. var min = bbox.minimumWorld;
  33383. var max = bbox.maximumWorld;
  33384. var box = max.subtract(min).scale(0.5);
  33385. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  33386. break;
  33387. case BABYLON.PhysicsEngine.PlaneImpostor:
  33388. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  33389. returnValue = new CANNON.Plane();
  33390. break;
  33391. case BABYLON.PhysicsEngine.MeshImpostor:
  33392. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33393. var rawFaces = mesh.getIndices();
  33394. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  33395. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  33396. break;
  33397. case BABYLON.PhysicsEngine.HeightmapImpostor:
  33398. returnValue = this._createHeightmap(mesh);
  33399. break;
  33400. }
  33401. mesh.rotationQuaternion = oldQuaternion;
  33402. return returnValue;
  33403. };
  33404. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  33405. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33406. var matrix = [];
  33407. //For now pointDepth will not be used and will be automatically calculated.
  33408. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  33409. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  33410. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  33411. var elementSize = dim * 2 / arraySize;
  33412. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  33413. for (var i = 0; i < pos.length; i = i + 3) {
  33414. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  33415. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  33416. var y = pos[i + 1] + minY;
  33417. if (!matrix[x]) {
  33418. matrix[x] = [];
  33419. }
  33420. if (!matrix[x][z]) {
  33421. matrix[x][z] = y;
  33422. }
  33423. matrix[x][z] = Math.max(y, matrix[x][z]);
  33424. }
  33425. for (var x = 0; x <= arraySize; ++x) {
  33426. if (!matrix[x]) {
  33427. var loc = 1;
  33428. while (!matrix[(x + loc) % arraySize]) {
  33429. loc++;
  33430. }
  33431. matrix[x] = matrix[(x + loc) % arraySize].slice();
  33432. }
  33433. for (var z = 0; z <= arraySize; ++z) {
  33434. if (!matrix[x][z]) {
  33435. var loc = 1;
  33436. var newValue;
  33437. while (newValue === undefined) {
  33438. newValue = matrix[x][(z + loc++) % arraySize];
  33439. }
  33440. matrix[x][z] = newValue;
  33441. }
  33442. }
  33443. }
  33444. var shape = new CANNON.Heightfield(matrix, {
  33445. elementSize: elementSize
  33446. });
  33447. //For future reference, needed for body transformation
  33448. shape.minY = minY;
  33449. return shape;
  33450. };
  33451. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  33452. var mesh = impostor.mesh;
  33453. //make sure it is updated...
  33454. impostor.mesh.computeWorldMatrix(true);
  33455. // The delta between the mesh position and the mesh bounding box center
  33456. var bbox = mesh.getBoundingInfo().boundingBox;
  33457. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  33458. var quaternion = mesh.rotationQuaternion;
  33459. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  33460. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  33461. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  33462. //-90 DEG in X, precalculated
  33463. quaternion = quaternion.multiply(this._minus90X);
  33464. //Invert! (Precalculated, 90 deg in X)
  33465. //No need to clone. this will never change.
  33466. impostor.setDeltaRotation(this._plus90X);
  33467. }
  33468. //If it is a heightfield, if should be centered.
  33469. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  33470. //calculate the correct body position:
  33471. var rotationQuaternion = mesh.rotationQuaternion;
  33472. mesh.rotationQuaternion = this._tmpUnityRotation;
  33473. mesh.computeWorldMatrix(true);
  33474. //get original center with no rotation
  33475. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  33476. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  33477. //rotation is back
  33478. mesh.rotationQuaternion = rotationQuaternion;
  33479. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  33480. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  33481. mesh.setPivotMatrix(p);
  33482. mesh.computeWorldMatrix(true);
  33483. //calculate the translation
  33484. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  33485. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  33486. //add it inverted to the delta
  33487. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  33488. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  33489. mesh.setPivotMatrix(oldPivot);
  33490. mesh.computeWorldMatrix(true);
  33491. }
  33492. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  33493. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  33494. this._tmpPosition.copyFrom(mesh.position);
  33495. }
  33496. impostor.setDeltaPosition(this._tmpDeltaPosition);
  33497. //Now update the impostor object
  33498. impostor.physicsBody.position.copy(this._tmpPosition);
  33499. impostor.physicsBody.quaternion.copy(quaternion);
  33500. };
  33501. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  33502. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  33503. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  33504. };
  33505. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  33506. impostor.physicsBody.position.copy(newPosition);
  33507. impostor.physicsBody.quaternion.copy(newRotation);
  33508. };
  33509. CannonJSPlugin.prototype.isSupported = function () {
  33510. return window.CANNON !== undefined;
  33511. };
  33512. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  33513. impostor.physicsBody.velocity.copy(velocity);
  33514. };
  33515. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  33516. impostor.physicsBody.angularVelocity.copy(velocity);
  33517. };
  33518. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  33519. var v = impostor.physicsBody.velocity;
  33520. if (!v)
  33521. return null;
  33522. return new BABYLON.Vector3(v.x, v.y, v.z);
  33523. };
  33524. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  33525. var v = impostor.physicsBody.angularVelocity;
  33526. if (!v)
  33527. return null;
  33528. return new BABYLON.Vector3(v.x, v.y, v.z);
  33529. };
  33530. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  33531. impostor.physicsBody.mass = mass;
  33532. impostor.physicsBody.updateMassProperties();
  33533. };
  33534. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  33535. impostor.physicsBody.sleep();
  33536. };
  33537. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  33538. impostor.physicsBody.wakeUp();
  33539. };
  33540. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  33541. joint.physicsJoint.distance = maxDistance;
  33542. };
  33543. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  33544. if (!motorIndex) {
  33545. joint.physicsJoint.enableMotor();
  33546. }
  33547. };
  33548. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  33549. if (!motorIndex) {
  33550. joint.physicsJoint.disableMotor();
  33551. }
  33552. };
  33553. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  33554. if (!motorIndex) {
  33555. joint.physicsJoint.enableMotor();
  33556. joint.physicsJoint.setMotorSpeed(speed);
  33557. if (maxForce) {
  33558. this.setLimit(joint, maxForce);
  33559. }
  33560. }
  33561. };
  33562. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  33563. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  33564. joint.physicsJoint.motorEquation.minForce = lowerLimit || -upperLimit;
  33565. };
  33566. CannonJSPlugin.prototype.dispose = function () {
  33567. //nothing to do, actually.
  33568. };
  33569. return CannonJSPlugin;
  33570. })();
  33571. BABYLON.CannonJSPlugin = CannonJSPlugin;
  33572. })(BABYLON || (BABYLON = {}));
  33573. var BABYLON;
  33574. (function (BABYLON) {
  33575. var OimoJSPlugin = (function () {
  33576. function OimoJSPlugin(iterations) {
  33577. this.name = "OimoJSPlugin";
  33578. this._tmpImpostorsArray = [];
  33579. this._tmpPositionVector = BABYLON.Vector3.Zero();
  33580. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  33581. this.world.clear();
  33582. //making sure no stats are calculated
  33583. this.world.isNoStat = true;
  33584. }
  33585. OimoJSPlugin.prototype.setGravity = function (gravity) {
  33586. this.world.gravity.copy(gravity);
  33587. };
  33588. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  33589. this.world.timeStep = timeStep;
  33590. };
  33591. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  33592. var _this = this;
  33593. impostors.forEach(function (impostor) {
  33594. impostor.beforeStep();
  33595. });
  33596. this.world.step();
  33597. impostors.forEach(function (impostor) {
  33598. impostor.afterStep();
  33599. //update the ordered impostors array
  33600. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  33601. });
  33602. //check for collisions
  33603. var contact = this.world.contacts;
  33604. while (contact !== null) {
  33605. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  33606. contact = contact.next;
  33607. continue;
  33608. }
  33609. //is this body colliding with any other? get the impostor
  33610. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  33611. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  33612. if (!mainImpostor || !collidingImpostor) {
  33613. contact = contact.next;
  33614. continue;
  33615. }
  33616. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  33617. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  33618. contact = contact.next;
  33619. }
  33620. };
  33621. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  33622. var mass = impostor.physicsBody.massInfo.mass;
  33623. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  33624. };
  33625. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  33626. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  33627. this.applyImpulse(impostor, force, contactPoint);
  33628. };
  33629. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  33630. var _this = this;
  33631. //parent-child relationship. Does this impostor has a parent impostor?
  33632. if (impostor.parent) {
  33633. if (impostor.physicsBody) {
  33634. this.removePhysicsBody(impostor);
  33635. //TODO is that needed?
  33636. impostor.forceUpdate();
  33637. }
  33638. return;
  33639. }
  33640. impostor.mesh.computeWorldMatrix(true);
  33641. if (impostor.isBodyInitRequired()) {
  33642. if (!impostor.mesh.rotationQuaternion) {
  33643. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  33644. }
  33645. var bodyConfig = {
  33646. name: impostor.mesh.uniqueId,
  33647. //Oimo must have mass, also for static objects.
  33648. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  33649. size: [],
  33650. type: [],
  33651. pos: [],
  33652. rot: [],
  33653. move: impostor.getParam("mass") !== 0,
  33654. //Supporting older versions of Oimo
  33655. world: this.world
  33656. };
  33657. var impostors = [impostor];
  33658. function addToArray(parent) {
  33659. parent.getChildMeshes().forEach(function (m) {
  33660. if (m.physicsImpostor) {
  33661. impostors.push(m.physicsImpostor);
  33662. m.physicsImpostor._init();
  33663. }
  33664. });
  33665. }
  33666. addToArray(impostor.mesh);
  33667. function checkWithEpsilon(value) {
  33668. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  33669. }
  33670. impostors.forEach(function (i) {
  33671. //get the correct bounding box
  33672. var oldQuaternion = i.mesh.rotationQuaternion;
  33673. 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 });
  33674. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  33675. i.mesh.computeWorldMatrix(true);
  33676. var bbox = i.mesh.getBoundingInfo().boundingBox;
  33677. if (i === impostor) {
  33678. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  33679. //Can also use Array.prototype.push.apply
  33680. bodyConfig.pos.push(bbox.center.x);
  33681. bodyConfig.pos.push(bbox.center.y);
  33682. bodyConfig.pos.push(bbox.center.z);
  33683. //tmp solution
  33684. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  33685. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  33686. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  33687. }
  33688. else {
  33689. bodyConfig.pos.push(i.mesh.position.x);
  33690. bodyConfig.pos.push(i.mesh.position.y);
  33691. bodyConfig.pos.push(i.mesh.position.z);
  33692. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  33693. bodyConfig.rot.push(0);
  33694. bodyConfig.rot.push(0);
  33695. bodyConfig.rot.push(0);
  33696. }
  33697. // register mesh
  33698. switch (i.type) {
  33699. case BABYLON.PhysicsEngine.SphereImpostor:
  33700. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  33701. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  33702. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  33703. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  33704. bodyConfig.type.push('sphere');
  33705. //due to the way oimo works with compounds, add 3 times
  33706. bodyConfig.size.push(size);
  33707. bodyConfig.size.push(size);
  33708. bodyConfig.size.push(size);
  33709. break;
  33710. case BABYLON.PhysicsEngine.PlaneImpostor:
  33711. //TODO Oimo now supports cylinder!
  33712. case BABYLON.PhysicsEngine.CylinderImpostor:
  33713. case BABYLON.PhysicsEngine.BoxImpostor:
  33714. default:
  33715. var min = bbox.minimumWorld;
  33716. var max = bbox.maximumWorld;
  33717. var box = max.subtract(min);
  33718. var sizeX = checkWithEpsilon(box.x);
  33719. var sizeY = checkWithEpsilon(box.y);
  33720. var sizeZ = checkWithEpsilon(box.z);
  33721. bodyConfig.type.push('box');
  33722. bodyConfig.size.push(sizeX);
  33723. bodyConfig.size.push(sizeY);
  33724. bodyConfig.size.push(sizeZ);
  33725. break;
  33726. }
  33727. //actually not needed, but hey...
  33728. i.mesh.rotationQuaternion = oldQuaternion;
  33729. });
  33730. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  33731. }
  33732. else {
  33733. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  33734. }
  33735. impostor.setDeltaPosition(this._tmpPositionVector);
  33736. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  33737. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  33738. };
  33739. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  33740. //impostor.physicsBody.dispose();
  33741. //Same as : (older oimo versions)
  33742. this.world.removeRigidBody(impostor.physicsBody);
  33743. };
  33744. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  33745. var mainBody = impostorJoint.mainImpostor.physicsBody;
  33746. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  33747. if (!mainBody || !connectedBody) {
  33748. return;
  33749. }
  33750. var jointData = impostorJoint.joint.jointData;
  33751. var options = jointData.nativeParams || {};
  33752. var type;
  33753. var nativeJointData = {
  33754. body1: mainBody,
  33755. body2: connectedBody,
  33756. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  33757. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  33758. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  33759. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  33760. min: options.min,
  33761. max: options.max,
  33762. collision: options.collision || jointData.collision,
  33763. spring: options.spring,
  33764. //supporting older version of Oimo
  33765. world: this.world
  33766. };
  33767. switch (impostorJoint.joint.type) {
  33768. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  33769. type = "jointBall";
  33770. break;
  33771. case BABYLON.PhysicsJoint.SpringJoint:
  33772. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  33773. var springData = jointData;
  33774. nativeJointData.min = springData.length || nativeJointData.min;
  33775. //Max should also be set, just make sure it is at least min
  33776. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  33777. case BABYLON.PhysicsJoint.DistanceJoint:
  33778. type = "jointDistance";
  33779. nativeJointData.max = jointData.maxDistance;
  33780. break;
  33781. case BABYLON.PhysicsJoint.PrismaticJoint:
  33782. type = "jointPrisme";
  33783. break;
  33784. case BABYLON.PhysicsJoint.SliderJoint:
  33785. type = "jointSlide";
  33786. break;
  33787. case BABYLON.PhysicsJoint.WheelJoint:
  33788. type = "jointWheel";
  33789. break;
  33790. case BABYLON.PhysicsJoint.HingeJoint:
  33791. default:
  33792. type = "jointHinge";
  33793. break;
  33794. }
  33795. nativeJointData.type = type;
  33796. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  33797. };
  33798. OimoJSPlugin.prototype.removeJoint = function (joint) {
  33799. joint.joint.physicsJoint.dispose();
  33800. };
  33801. OimoJSPlugin.prototype.isSupported = function () {
  33802. return OIMO !== undefined;
  33803. };
  33804. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  33805. if (!impostor.physicsBody.sleeping) {
  33806. //TODO check that
  33807. if (impostor.physicsBody.shapes.next) {
  33808. var parentShape = this._getLastShape(impostor.physicsBody);
  33809. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  33810. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  33811. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  33812. }
  33813. else {
  33814. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  33815. }
  33816. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  33817. }
  33818. };
  33819. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  33820. var body = impostor.physicsBody;
  33821. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  33822. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  33823. body.syncShapes();
  33824. body.awake();
  33825. };
  33826. OimoJSPlugin.prototype._getLastShape = function (body) {
  33827. var lastShape = body.shapes;
  33828. while (lastShape.next) {
  33829. lastShape = lastShape.next;
  33830. }
  33831. return lastShape;
  33832. };
  33833. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  33834. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  33835. };
  33836. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  33837. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  33838. };
  33839. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  33840. var v = impostor.physicsBody.linearVelocity;
  33841. if (!v)
  33842. return null;
  33843. return new BABYLON.Vector3(v.x, v.y, v.z);
  33844. };
  33845. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  33846. var v = impostor.physicsBody.angularVelocity;
  33847. if (!v)
  33848. return null;
  33849. return new BABYLON.Vector3(v.x, v.y, v.z);
  33850. };
  33851. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  33852. var staticBody = mass === 0;
  33853. //this will actually set the body's density and not its mass.
  33854. //But this is how oimo treats the mass variable.
  33855. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  33856. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  33857. };
  33858. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  33859. impostor.physicsBody.sleep();
  33860. };
  33861. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  33862. impostor.physicsBody.awake();
  33863. };
  33864. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  33865. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  33866. if (minDistance !== void 0) {
  33867. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  33868. }
  33869. };
  33870. OimoJSPlugin.prototype.setMotor = function (joint, force, maxForce, motorIndex) {
  33871. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  33872. if (motor) {
  33873. motor.setMotor(force, maxForce);
  33874. }
  33875. };
  33876. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  33877. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  33878. if (motor) {
  33879. motor.setLimit(upperLimit, lowerLimit || -upperLimit);
  33880. }
  33881. };
  33882. OimoJSPlugin.prototype.dispose = function () {
  33883. this.world.clear();
  33884. };
  33885. return OimoJSPlugin;
  33886. })();
  33887. BABYLON.OimoJSPlugin = OimoJSPlugin;
  33888. })(BABYLON || (BABYLON = {}));
  33889. var BABYLON;
  33890. (function (BABYLON) {
  33891. var DisplayPassPostProcess = (function (_super) {
  33892. __extends(DisplayPassPostProcess, _super);
  33893. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33894. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  33895. }
  33896. return DisplayPassPostProcess;
  33897. })(BABYLON.PostProcess);
  33898. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  33899. })(BABYLON || (BABYLON = {}));
  33900. var BABYLON;
  33901. (function (BABYLON) {
  33902. var SimplificationSettings = (function () {
  33903. function SimplificationSettings(quality, distance, optimizeMesh) {
  33904. this.quality = quality;
  33905. this.distance = distance;
  33906. this.optimizeMesh = optimizeMesh;
  33907. }
  33908. return SimplificationSettings;
  33909. })();
  33910. BABYLON.SimplificationSettings = SimplificationSettings;
  33911. var SimplificationQueue = (function () {
  33912. function SimplificationQueue() {
  33913. this.running = false;
  33914. this._simplificationArray = [];
  33915. }
  33916. SimplificationQueue.prototype.addTask = function (task) {
  33917. this._simplificationArray.push(task);
  33918. };
  33919. SimplificationQueue.prototype.executeNext = function () {
  33920. var task = this._simplificationArray.pop();
  33921. if (task) {
  33922. this.running = true;
  33923. this.runSimplification(task);
  33924. }
  33925. else {
  33926. this.running = false;
  33927. }
  33928. };
  33929. SimplificationQueue.prototype.runSimplification = function (task) {
  33930. var _this = this;
  33931. if (task.parallelProcessing) {
  33932. //parallel simplifier
  33933. task.settings.forEach(function (setting) {
  33934. var simplifier = _this.getSimplifier(task);
  33935. simplifier.simplify(setting, function (newMesh) {
  33936. task.mesh.addLODLevel(setting.distance, newMesh);
  33937. newMesh.isVisible = true;
  33938. //check if it is the last
  33939. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  33940. //all done, run the success callback.
  33941. task.successCallback();
  33942. }
  33943. _this.executeNext();
  33944. });
  33945. });
  33946. }
  33947. else {
  33948. //single simplifier.
  33949. var simplifier = this.getSimplifier(task);
  33950. var runDecimation = function (setting, callback) {
  33951. simplifier.simplify(setting, function (newMesh) {
  33952. task.mesh.addLODLevel(setting.distance, newMesh);
  33953. newMesh.isVisible = true;
  33954. //run the next quality level
  33955. callback();
  33956. });
  33957. };
  33958. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  33959. runDecimation(task.settings[loop.index], function () {
  33960. loop.executeNext();
  33961. });
  33962. }, function () {
  33963. //execution ended, run the success callback.
  33964. if (task.successCallback) {
  33965. task.successCallback();
  33966. }
  33967. _this.executeNext();
  33968. });
  33969. }
  33970. };
  33971. SimplificationQueue.prototype.getSimplifier = function (task) {
  33972. switch (task.simplificationType) {
  33973. case SimplificationType.QUADRATIC:
  33974. default:
  33975. return new QuadraticErrorSimplification(task.mesh);
  33976. }
  33977. };
  33978. return SimplificationQueue;
  33979. })();
  33980. BABYLON.SimplificationQueue = SimplificationQueue;
  33981. /**
  33982. * The implemented types of simplification.
  33983. * At the moment only Quadratic Error Decimation is implemented.
  33984. */
  33985. (function (SimplificationType) {
  33986. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  33987. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  33988. var SimplificationType = BABYLON.SimplificationType;
  33989. var DecimationTriangle = (function () {
  33990. function DecimationTriangle(vertices) {
  33991. this.vertices = vertices;
  33992. this.error = new Array(4);
  33993. this.deleted = false;
  33994. this.isDirty = false;
  33995. this.deletePending = false;
  33996. this.borderFactor = 0;
  33997. }
  33998. return DecimationTriangle;
  33999. })();
  34000. BABYLON.DecimationTriangle = DecimationTriangle;
  34001. var DecimationVertex = (function () {
  34002. function DecimationVertex(position, id) {
  34003. this.position = position;
  34004. this.id = id;
  34005. this.isBorder = true;
  34006. this.q = new QuadraticMatrix();
  34007. this.triangleCount = 0;
  34008. this.triangleStart = 0;
  34009. this.originalOffsets = [];
  34010. }
  34011. DecimationVertex.prototype.updatePosition = function (newPosition) {
  34012. this.position.copyFrom(newPosition);
  34013. };
  34014. return DecimationVertex;
  34015. })();
  34016. BABYLON.DecimationVertex = DecimationVertex;
  34017. var QuadraticMatrix = (function () {
  34018. function QuadraticMatrix(data) {
  34019. this.data = new Array(10);
  34020. for (var i = 0; i < 10; ++i) {
  34021. if (data && data[i]) {
  34022. this.data[i] = data[i];
  34023. }
  34024. else {
  34025. this.data[i] = 0;
  34026. }
  34027. }
  34028. }
  34029. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  34030. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  34031. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  34032. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  34033. return det;
  34034. };
  34035. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  34036. for (var i = 0; i < 10; ++i) {
  34037. this.data[i] += matrix.data[i];
  34038. }
  34039. };
  34040. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  34041. for (var i = 0; i < 10; ++i) {
  34042. this.data[i] += data[i];
  34043. }
  34044. };
  34045. QuadraticMatrix.prototype.add = function (matrix) {
  34046. var m = new QuadraticMatrix();
  34047. for (var i = 0; i < 10; ++i) {
  34048. m.data[i] = this.data[i] + matrix.data[i];
  34049. }
  34050. return m;
  34051. };
  34052. QuadraticMatrix.FromData = function (a, b, c, d) {
  34053. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  34054. };
  34055. //returning an array to avoid garbage collection
  34056. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  34057. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  34058. };
  34059. return QuadraticMatrix;
  34060. })();
  34061. BABYLON.QuadraticMatrix = QuadraticMatrix;
  34062. var Reference = (function () {
  34063. function Reference(vertexId, triangleId) {
  34064. this.vertexId = vertexId;
  34065. this.triangleId = triangleId;
  34066. }
  34067. return Reference;
  34068. })();
  34069. BABYLON.Reference = Reference;
  34070. /**
  34071. * An implementation of the Quadratic Error simplification algorithm.
  34072. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  34073. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  34074. * @author RaananW
  34075. */
  34076. var QuadraticErrorSimplification = (function () {
  34077. function QuadraticErrorSimplification(_mesh) {
  34078. this._mesh = _mesh;
  34079. this.initialized = false;
  34080. this.syncIterations = 5000;
  34081. this.aggressiveness = 7;
  34082. this.decimationIterations = 100;
  34083. this.boundingBoxEpsilon = BABYLON.Epsilon;
  34084. }
  34085. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  34086. var _this = this;
  34087. this.initDecimatedMesh();
  34088. //iterating through the submeshes array, one after the other.
  34089. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  34090. _this.initWithMesh(loop.index, function () {
  34091. _this.runDecimation(settings, loop.index, function () {
  34092. loop.executeNext();
  34093. });
  34094. }, settings.optimizeMesh);
  34095. }, function () {
  34096. setTimeout(function () {
  34097. successCallback(_this._reconstructedMesh);
  34098. }, 0);
  34099. });
  34100. };
  34101. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  34102. var _this = this;
  34103. var gCount = 0;
  34104. triangle.vertices.forEach(function (vertex) {
  34105. var count = 0;
  34106. var vPos = vertex.position;
  34107. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  34108. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  34109. ++count;
  34110. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  34111. ++count;
  34112. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  34113. ++count;
  34114. if (count > 1) {
  34115. ++gCount;
  34116. }
  34117. ;
  34118. });
  34119. if (gCount > 1) {
  34120. console.log(triangle, gCount);
  34121. }
  34122. return gCount > 1;
  34123. };
  34124. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  34125. var _this = this;
  34126. var targetCount = ~~(this.triangles.length * settings.quality);
  34127. var deletedTriangles = 0;
  34128. var triangleCount = this.triangles.length;
  34129. var iterationFunction = function (iteration, callback) {
  34130. setTimeout(function () {
  34131. if (iteration % 5 === 0) {
  34132. _this.updateMesh(iteration === 0);
  34133. }
  34134. for (var i = 0; i < _this.triangles.length; ++i) {
  34135. _this.triangles[i].isDirty = false;
  34136. }
  34137. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  34138. var trianglesIterator = function (i) {
  34139. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  34140. var t = _this.triangles[tIdx];
  34141. if (!t)
  34142. return;
  34143. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  34144. return;
  34145. }
  34146. for (var j = 0; j < 3; ++j) {
  34147. if (t.error[j] < threshold) {
  34148. var deleted0 = [];
  34149. var deleted1 = [];
  34150. var v0 = t.vertices[j];
  34151. var v1 = t.vertices[(j + 1) % 3];
  34152. if (v0.isBorder !== v1.isBorder)
  34153. continue;
  34154. var p = BABYLON.Vector3.Zero();
  34155. var n = BABYLON.Vector3.Zero();
  34156. var uv = BABYLON.Vector2.Zero();
  34157. var color = new BABYLON.Color4(0, 0, 0, 1);
  34158. _this.calculateError(v0, v1, p, n, uv, color);
  34159. var delTr = [];
  34160. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  34161. continue;
  34162. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  34163. continue;
  34164. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  34165. continue;
  34166. var uniqueArray = [];
  34167. delTr.forEach(function (deletedT) {
  34168. if (uniqueArray.indexOf(deletedT) === -1) {
  34169. deletedT.deletePending = true;
  34170. uniqueArray.push(deletedT);
  34171. }
  34172. });
  34173. if (uniqueArray.length % 2 !== 0) {
  34174. continue;
  34175. }
  34176. v0.q = v1.q.add(v0.q);
  34177. v0.updatePosition(p);
  34178. var tStart = _this.references.length;
  34179. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  34180. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  34181. var tCount = _this.references.length - tStart;
  34182. if (tCount <= v0.triangleCount) {
  34183. if (tCount) {
  34184. for (var c = 0; c < tCount; c++) {
  34185. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  34186. }
  34187. }
  34188. }
  34189. else {
  34190. v0.triangleStart = tStart;
  34191. }
  34192. v0.triangleCount = tCount;
  34193. break;
  34194. }
  34195. }
  34196. };
  34197. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  34198. }, 0);
  34199. };
  34200. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  34201. if (triangleCount - deletedTriangles <= targetCount)
  34202. loop.breakLoop();
  34203. else {
  34204. iterationFunction(loop.index, function () {
  34205. loop.executeNext();
  34206. });
  34207. }
  34208. }, function () {
  34209. setTimeout(function () {
  34210. //reconstruct this part of the mesh
  34211. _this.reconstructMesh(submeshIndex);
  34212. successCallback();
  34213. }, 0);
  34214. });
  34215. };
  34216. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  34217. var _this = this;
  34218. this.vertices = [];
  34219. this.triangles = [];
  34220. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34221. var indices = this._mesh.getIndices();
  34222. var submesh = this._mesh.subMeshes[submeshIndex];
  34223. var findInVertices = function (positionToSearch) {
  34224. if (optimizeMesh) {
  34225. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  34226. if (_this.vertices[ii].position.equals(positionToSearch)) {
  34227. return _this.vertices[ii];
  34228. }
  34229. }
  34230. }
  34231. return null;
  34232. };
  34233. var vertexReferences = [];
  34234. var vertexInit = function (i) {
  34235. var offset = i + submesh.verticesStart;
  34236. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  34237. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  34238. vertex.originalOffsets.push(offset);
  34239. if (vertex.id === _this.vertices.length) {
  34240. _this.vertices.push(vertex);
  34241. }
  34242. vertexReferences.push(vertex.id);
  34243. };
  34244. //var totalVertices = mesh.getTotalVertices();
  34245. var totalVertices = submesh.verticesCount;
  34246. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  34247. var indicesInit = function (i) {
  34248. var offset = (submesh.indexStart / 3) + i;
  34249. var pos = (offset * 3);
  34250. var i0 = indices[pos + 0];
  34251. var i1 = indices[pos + 1];
  34252. var i2 = indices[pos + 2];
  34253. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  34254. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  34255. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  34256. var triangle = new DecimationTriangle([v0, v1, v2]);
  34257. triangle.originalOffset = pos;
  34258. _this.triangles.push(triangle);
  34259. };
  34260. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  34261. _this.init(callback);
  34262. });
  34263. });
  34264. };
  34265. QuadraticErrorSimplification.prototype.init = function (callback) {
  34266. var _this = this;
  34267. var triangleInit1 = function (i) {
  34268. var t = _this.triangles[i];
  34269. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  34270. for (var j = 0; j < 3; j++) {
  34271. 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))));
  34272. }
  34273. };
  34274. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  34275. var triangleInit2 = function (i) {
  34276. var t = _this.triangles[i];
  34277. for (var j = 0; j < 3; ++j) {
  34278. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  34279. }
  34280. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  34281. };
  34282. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  34283. _this.initialized = true;
  34284. callback();
  34285. });
  34286. });
  34287. };
  34288. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  34289. var newTriangles = [];
  34290. var i;
  34291. for (i = 0; i < this.vertices.length; ++i) {
  34292. this.vertices[i].triangleCount = 0;
  34293. }
  34294. var t;
  34295. var j;
  34296. for (i = 0; i < this.triangles.length; ++i) {
  34297. if (!this.triangles[i].deleted) {
  34298. t = this.triangles[i];
  34299. for (j = 0; j < 3; ++j) {
  34300. t.vertices[j].triangleCount = 1;
  34301. }
  34302. newTriangles.push(t);
  34303. }
  34304. }
  34305. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  34306. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  34307. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  34308. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  34309. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34310. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34311. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34312. var vertexCount = 0;
  34313. for (i = 0; i < this.vertices.length; ++i) {
  34314. var vertex = this.vertices[i];
  34315. vertex.id = vertexCount;
  34316. if (vertex.triangleCount) {
  34317. vertex.originalOffsets.forEach(function (originalOffset) {
  34318. newPositionData.push(vertex.position.x);
  34319. newPositionData.push(vertex.position.y);
  34320. newPositionData.push(vertex.position.z);
  34321. newNormalData.push(normalData[originalOffset * 3]);
  34322. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  34323. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  34324. if (uvs && uvs.length) {
  34325. newUVsData.push(uvs[(originalOffset * 2)]);
  34326. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  34327. }
  34328. else if (colorsData && colorsData.length) {
  34329. newColorsData.push(colorsData[(originalOffset * 4)]);
  34330. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  34331. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  34332. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  34333. }
  34334. ++vertexCount;
  34335. });
  34336. }
  34337. }
  34338. var startingIndex = this._reconstructedMesh.getTotalIndices();
  34339. var startingVertex = this._reconstructedMesh.getTotalVertices();
  34340. var submeshesArray = this._reconstructedMesh.subMeshes;
  34341. this._reconstructedMesh.subMeshes = [];
  34342. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  34343. var originalIndices = this._mesh.getIndices();
  34344. for (i = 0; i < newTriangles.length; ++i) {
  34345. t = newTriangles[i]; //now get the new referencing point for each vertex
  34346. [0, 1, 2].forEach(function (idx) {
  34347. var id = originalIndices[t.originalOffset + idx];
  34348. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  34349. if (offset < 0)
  34350. offset = 0;
  34351. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  34352. });
  34353. }
  34354. //overwriting the old vertex buffers and indices.
  34355. this._reconstructedMesh.setIndices(newIndicesArray);
  34356. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  34357. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  34358. if (newUVsData.length > 0)
  34359. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  34360. if (newColorsData.length > 0)
  34361. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  34362. //create submesh
  34363. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  34364. if (submeshIndex > 0) {
  34365. this._reconstructedMesh.subMeshes = [];
  34366. submeshesArray.forEach(function (submesh) {
  34367. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  34368. });
  34369. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  34370. }
  34371. };
  34372. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  34373. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  34374. this._reconstructedMesh.material = this._mesh.material;
  34375. this._reconstructedMesh.parent = this._mesh.parent;
  34376. this._reconstructedMesh.isVisible = false;
  34377. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  34378. };
  34379. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  34380. for (var i = 0; i < vertex1.triangleCount; ++i) {
  34381. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  34382. if (t.deleted)
  34383. continue;
  34384. var s = this.references[vertex1.triangleStart + i].vertexId;
  34385. var v1 = t.vertices[(s + 1) % 3];
  34386. var v2 = t.vertices[(s + 2) % 3];
  34387. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  34388. deletedArray[i] = true;
  34389. delTr.push(t);
  34390. continue;
  34391. }
  34392. var d1 = v1.position.subtract(point);
  34393. d1 = d1.normalize();
  34394. var d2 = v2.position.subtract(point);
  34395. d2 = d2.normalize();
  34396. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  34397. return true;
  34398. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  34399. deletedArray[i] = false;
  34400. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  34401. return true;
  34402. }
  34403. return false;
  34404. };
  34405. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  34406. var newDeleted = deletedTriangles;
  34407. for (var i = 0; i < vertex.triangleCount; ++i) {
  34408. var ref = this.references[vertex.triangleStart + i];
  34409. var t = this.triangles[ref.triangleId];
  34410. if (t.deleted)
  34411. continue;
  34412. if (deletedArray[i] && t.deletePending) {
  34413. t.deleted = true;
  34414. newDeleted++;
  34415. continue;
  34416. }
  34417. t.vertices[ref.vertexId] = origVertex;
  34418. t.isDirty = true;
  34419. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  34420. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  34421. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  34422. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  34423. this.references.push(ref);
  34424. }
  34425. return newDeleted;
  34426. };
  34427. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  34428. for (var i = 0; i < this.vertices.length; ++i) {
  34429. var vCount = [];
  34430. var vId = [];
  34431. var v = this.vertices[i];
  34432. var j;
  34433. for (j = 0; j < v.triangleCount; ++j) {
  34434. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  34435. for (var ii = 0; ii < 3; ii++) {
  34436. var ofs = 0;
  34437. var vv = triangle.vertices[ii];
  34438. while (ofs < vCount.length) {
  34439. if (vId[ofs] === vv.id)
  34440. break;
  34441. ++ofs;
  34442. }
  34443. if (ofs === vCount.length) {
  34444. vCount.push(1);
  34445. vId.push(vv.id);
  34446. }
  34447. else {
  34448. vCount[ofs]++;
  34449. }
  34450. }
  34451. }
  34452. for (j = 0; j < vCount.length; ++j) {
  34453. if (vCount[j] === 1) {
  34454. this.vertices[vId[j]].isBorder = true;
  34455. }
  34456. else {
  34457. this.vertices[vId[j]].isBorder = false;
  34458. }
  34459. }
  34460. }
  34461. };
  34462. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  34463. if (identifyBorders === void 0) { identifyBorders = false; }
  34464. var i;
  34465. if (!identifyBorders) {
  34466. var newTrianglesVector = [];
  34467. for (i = 0; i < this.triangles.length; ++i) {
  34468. if (!this.triangles[i].deleted) {
  34469. newTrianglesVector.push(this.triangles[i]);
  34470. }
  34471. }
  34472. this.triangles = newTrianglesVector;
  34473. }
  34474. for (i = 0; i < this.vertices.length; ++i) {
  34475. this.vertices[i].triangleCount = 0;
  34476. this.vertices[i].triangleStart = 0;
  34477. }
  34478. var t;
  34479. var j;
  34480. var v;
  34481. for (i = 0; i < this.triangles.length; ++i) {
  34482. t = this.triangles[i];
  34483. for (j = 0; j < 3; ++j) {
  34484. v = t.vertices[j];
  34485. v.triangleCount++;
  34486. }
  34487. }
  34488. var tStart = 0;
  34489. for (i = 0; i < this.vertices.length; ++i) {
  34490. this.vertices[i].triangleStart = tStart;
  34491. tStart += this.vertices[i].triangleCount;
  34492. this.vertices[i].triangleCount = 0;
  34493. }
  34494. var newReferences = new Array(this.triangles.length * 3);
  34495. for (i = 0; i < this.triangles.length; ++i) {
  34496. t = this.triangles[i];
  34497. for (j = 0; j < 3; ++j) {
  34498. v = t.vertices[j];
  34499. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  34500. v.triangleCount++;
  34501. }
  34502. }
  34503. this.references = newReferences;
  34504. if (identifyBorders) {
  34505. this.identifyBorder();
  34506. }
  34507. };
  34508. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  34509. var x = point.x;
  34510. var y = point.y;
  34511. var z = point.z;
  34512. 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
  34513. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  34514. };
  34515. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  34516. var q = vertex1.q.add(vertex2.q);
  34517. var border = vertex1.isBorder && vertex2.isBorder;
  34518. var error = 0;
  34519. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  34520. if (qDet !== 0 && !border) {
  34521. if (!pointResult) {
  34522. pointResult = BABYLON.Vector3.Zero();
  34523. }
  34524. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  34525. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  34526. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  34527. error = this.vertexError(q, pointResult);
  34528. }
  34529. else {
  34530. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  34531. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  34532. var error1 = this.vertexError(q, vertex1.position);
  34533. var error2 = this.vertexError(q, vertex2.position);
  34534. var error3 = this.vertexError(q, p3);
  34535. error = Math.min(error1, error2, error3);
  34536. if (error === error1) {
  34537. if (pointResult) {
  34538. pointResult.copyFrom(vertex1.position);
  34539. }
  34540. }
  34541. else if (error === error2) {
  34542. if (pointResult) {
  34543. pointResult.copyFrom(vertex2.position);
  34544. }
  34545. }
  34546. else {
  34547. if (pointResult) {
  34548. pointResult.copyFrom(p3);
  34549. }
  34550. }
  34551. }
  34552. return error;
  34553. };
  34554. return QuadraticErrorSimplification;
  34555. })();
  34556. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  34557. })(BABYLON || (BABYLON = {}));
  34558. var BABYLON;
  34559. (function (BABYLON) {
  34560. var serializedGeometries = [];
  34561. var serializeGeometry = function (geometry, serializationGeometries) {
  34562. if (serializedGeometries[geometry.id]) {
  34563. return;
  34564. }
  34565. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  34566. serializationGeometries.boxes.push(geometry.serialize());
  34567. }
  34568. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  34569. serializationGeometries.spheres.push(geometry.serialize());
  34570. }
  34571. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  34572. serializationGeometries.cylinders.push(geometry.serialize());
  34573. }
  34574. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  34575. serializationGeometries.toruses.push(geometry.serialize());
  34576. }
  34577. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  34578. serializationGeometries.grounds.push(geometry.serialize());
  34579. }
  34580. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  34581. serializationGeometries.planes.push(geometry.serialize());
  34582. }
  34583. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  34584. serializationGeometries.torusKnots.push(geometry.serialize());
  34585. }
  34586. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  34587. throw new Error("Unknown primitive type");
  34588. }
  34589. else {
  34590. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  34591. }
  34592. serializedGeometries[geometry.id] = true;
  34593. };
  34594. var serializeMesh = function (mesh, serializationScene) {
  34595. var serializationObject = {};
  34596. serializationObject.name = mesh.name;
  34597. serializationObject.id = mesh.id;
  34598. if (BABYLON.Tags.HasTags(mesh)) {
  34599. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  34600. }
  34601. serializationObject.position = mesh.position.asArray();
  34602. if (mesh.rotationQuaternion) {
  34603. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  34604. }
  34605. else if (mesh.rotation) {
  34606. serializationObject.rotation = mesh.rotation.asArray();
  34607. }
  34608. serializationObject.scaling = mesh.scaling.asArray();
  34609. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  34610. serializationObject.isEnabled = mesh.isEnabled();
  34611. serializationObject.isVisible = mesh.isVisible;
  34612. serializationObject.infiniteDistance = mesh.infiniteDistance;
  34613. serializationObject.pickable = mesh.isPickable;
  34614. serializationObject.receiveShadows = mesh.receiveShadows;
  34615. serializationObject.billboardMode = mesh.billboardMode;
  34616. serializationObject.visibility = mesh.visibility;
  34617. serializationObject.checkCollisions = mesh.checkCollisions;
  34618. // Parent
  34619. if (mesh.parent) {
  34620. serializationObject.parentId = mesh.parent.id;
  34621. }
  34622. // Geometry
  34623. var geometry = mesh._geometry;
  34624. if (geometry) {
  34625. var geometryId = geometry.id;
  34626. serializationObject.geometryId = geometryId;
  34627. if (!mesh.getScene().getGeometryByID(geometryId)) {
  34628. // 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
  34629. serializeGeometry(geometry, serializationScene.geometries);
  34630. }
  34631. // SubMeshes
  34632. serializationObject.subMeshes = [];
  34633. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34634. var subMesh = mesh.subMeshes[subIndex];
  34635. serializationObject.subMeshes.push({
  34636. materialIndex: subMesh.materialIndex,
  34637. verticesStart: subMesh.verticesStart,
  34638. verticesCount: subMesh.verticesCount,
  34639. indexStart: subMesh.indexStart,
  34640. indexCount: subMesh.indexCount
  34641. });
  34642. }
  34643. }
  34644. // Material
  34645. if (mesh.material) {
  34646. serializationObject.materialId = mesh.material.id;
  34647. }
  34648. else {
  34649. mesh.material = null;
  34650. }
  34651. // Skeleton
  34652. if (mesh.skeleton) {
  34653. serializationObject.skeletonId = mesh.skeleton.id;
  34654. }
  34655. // Physics
  34656. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  34657. serializationObject.physicsMass = mesh.getPhysicsMass();
  34658. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  34659. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  34660. switch (mesh.getPhysicsImpostor().type) {
  34661. case BABYLON.PhysicsEngine.BoxImpostor:
  34662. serializationObject.physicsImpostor = 1;
  34663. break;
  34664. case BABYLON.PhysicsEngine.SphereImpostor:
  34665. serializationObject.physicsImpostor = 2;
  34666. break;
  34667. }
  34668. }
  34669. // Instances
  34670. serializationObject.instances = [];
  34671. for (var index = 0; index < mesh.instances.length; index++) {
  34672. var instance = mesh.instances[index];
  34673. var serializationInstance = {
  34674. name: instance.name,
  34675. position: instance.position.asArray(),
  34676. scaling: instance.scaling.asArray()
  34677. };
  34678. if (instance.rotationQuaternion) {
  34679. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34680. }
  34681. else if (instance.rotation) {
  34682. serializationInstance.rotation = instance.rotation.asArray();
  34683. }
  34684. serializationObject.instances.push(serializationInstance);
  34685. // Animations
  34686. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34687. serializationInstance.ranges = instance.serializeAnimationRanges();
  34688. }
  34689. // Animations
  34690. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  34691. serializationObject.ranges = mesh.serializeAnimationRanges();
  34692. // Layer mask
  34693. serializationObject.layerMask = mesh.layerMask;
  34694. return serializationObject;
  34695. };
  34696. var finalizeSingleMesh = function (mesh, serializationObject) {
  34697. //only works if the mesh is already loaded
  34698. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  34699. //serialize material
  34700. if (mesh.material) {
  34701. if (mesh.material instanceof BABYLON.StandardMaterial) {
  34702. serializationObject.materials = serializationObject.materials || [];
  34703. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  34704. serializationObject.materials.push(mesh.material.serialize());
  34705. }
  34706. }
  34707. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  34708. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  34709. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  34710. serializationObject.multiMaterials.push(mesh.material.serialize());
  34711. }
  34712. }
  34713. }
  34714. //serialize geometry
  34715. var geometry = mesh._geometry;
  34716. if (geometry) {
  34717. if (!serializationObject.geometries) {
  34718. serializationObject.geometries = {};
  34719. serializationObject.geometries.boxes = [];
  34720. serializationObject.geometries.spheres = [];
  34721. serializationObject.geometries.cylinders = [];
  34722. serializationObject.geometries.toruses = [];
  34723. serializationObject.geometries.grounds = [];
  34724. serializationObject.geometries.planes = [];
  34725. serializationObject.geometries.torusKnots = [];
  34726. serializationObject.geometries.vertexData = [];
  34727. }
  34728. serializeGeometry(geometry, serializationObject.geometries);
  34729. }
  34730. // Skeletons
  34731. if (mesh.skeleton) {
  34732. serializationObject.skeletons = serializationObject.skeletons || [];
  34733. serializationObject.skeletons.push(mesh.skeleton.serialize());
  34734. }
  34735. //serialize the actual mesh
  34736. serializationObject.meshes = serializationObject.meshes || [];
  34737. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  34738. }
  34739. };
  34740. var SceneSerializer = (function () {
  34741. function SceneSerializer() {
  34742. }
  34743. SceneSerializer.ClearCache = function () {
  34744. serializedGeometries = [];
  34745. };
  34746. SceneSerializer.Serialize = function (scene) {
  34747. var serializationObject = {};
  34748. // Scene
  34749. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  34750. serializationObject.autoClear = scene.autoClear;
  34751. serializationObject.clearColor = scene.clearColor.asArray();
  34752. serializationObject.ambientColor = scene.ambientColor.asArray();
  34753. serializationObject.gravity = scene.gravity.asArray();
  34754. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  34755. serializationObject.workerCollisions = scene.workerCollisions;
  34756. // Fog
  34757. if (scene.fogMode && scene.fogMode !== 0) {
  34758. serializationObject.fogMode = scene.fogMode;
  34759. serializationObject.fogColor = scene.fogColor.asArray();
  34760. serializationObject.fogStart = scene.fogStart;
  34761. serializationObject.fogEnd = scene.fogEnd;
  34762. serializationObject.fogDensity = scene.fogDensity;
  34763. }
  34764. //Physics
  34765. if (scene.isPhysicsEnabled()) {
  34766. serializationObject.physicsEnabled = true;
  34767. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  34768. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  34769. }
  34770. // Lights
  34771. serializationObject.lights = [];
  34772. var index;
  34773. var light;
  34774. for (index = 0; index < scene.lights.length; index++) {
  34775. light = scene.lights[index];
  34776. serializationObject.lights.push(light.serialize());
  34777. }
  34778. // Cameras
  34779. serializationObject.cameras = [];
  34780. for (index = 0; index < scene.cameras.length; index++) {
  34781. var camera = scene.cameras[index];
  34782. serializationObject.cameras.push(camera.serialize());
  34783. }
  34784. if (scene.activeCamera) {
  34785. serializationObject.activeCameraID = scene.activeCamera.id;
  34786. }
  34787. // Animations
  34788. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  34789. // Materials
  34790. serializationObject.materials = [];
  34791. serializationObject.multiMaterials = [];
  34792. var material;
  34793. for (index = 0; index < scene.materials.length; index++) {
  34794. material = scene.materials[index];
  34795. serializationObject.materials.push(material.serialize());
  34796. }
  34797. // MultiMaterials
  34798. serializationObject.multiMaterials = [];
  34799. for (index = 0; index < scene.multiMaterials.length; index++) {
  34800. var multiMaterial = scene.multiMaterials[index];
  34801. serializationObject.multiMaterials.push(multiMaterial.serialize());
  34802. }
  34803. // Skeletons
  34804. serializationObject.skeletons = [];
  34805. for (index = 0; index < scene.skeletons.length; index++) {
  34806. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  34807. }
  34808. // Geometries
  34809. serializationObject.geometries = {};
  34810. serializationObject.geometries.boxes = [];
  34811. serializationObject.geometries.spheres = [];
  34812. serializationObject.geometries.cylinders = [];
  34813. serializationObject.geometries.toruses = [];
  34814. serializationObject.geometries.grounds = [];
  34815. serializationObject.geometries.planes = [];
  34816. serializationObject.geometries.torusKnots = [];
  34817. serializationObject.geometries.vertexData = [];
  34818. serializedGeometries = [];
  34819. var geometries = scene.getGeometries();
  34820. for (index = 0; index < geometries.length; index++) {
  34821. var geometry = geometries[index];
  34822. if (geometry.isReady()) {
  34823. serializeGeometry(geometry, serializationObject.geometries);
  34824. }
  34825. }
  34826. // Meshes
  34827. serializationObject.meshes = [];
  34828. for (index = 0; index < scene.meshes.length; index++) {
  34829. var abstractMesh = scene.meshes[index];
  34830. if (abstractMesh instanceof BABYLON.Mesh) {
  34831. var mesh = abstractMesh;
  34832. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  34833. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  34834. }
  34835. }
  34836. }
  34837. // Particles Systems
  34838. serializationObject.particleSystems = [];
  34839. for (index = 0; index < scene.particleSystems.length; index++) {
  34840. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  34841. }
  34842. // Lens flares
  34843. serializationObject.lensFlareSystems = [];
  34844. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  34845. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  34846. }
  34847. // Shadows
  34848. serializationObject.shadowGenerators = [];
  34849. for (index = 0; index < scene.lights.length; index++) {
  34850. light = scene.lights[index];
  34851. if (light.getShadowGenerator()) {
  34852. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  34853. }
  34854. }
  34855. return serializationObject;
  34856. };
  34857. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  34858. if (withParents === void 0) { withParents = false; }
  34859. if (withChildren === void 0) { withChildren = false; }
  34860. var serializationObject = {};
  34861. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  34862. if (withParents || withChildren) {
  34863. //deliberate for loop! not for each, appended should be processed as well.
  34864. for (var i = 0; i < toSerialize.length; ++i) {
  34865. if (withChildren) {
  34866. toSerialize[i].getDescendants().forEach(function (node) {
  34867. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  34868. toSerialize.push(node);
  34869. }
  34870. });
  34871. }
  34872. //make sure the array doesn't contain the object already
  34873. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  34874. toSerialize.push(toSerialize[i].parent);
  34875. }
  34876. }
  34877. }
  34878. toSerialize.forEach(function (mesh) {
  34879. finalizeSingleMesh(mesh, serializationObject);
  34880. });
  34881. return serializationObject;
  34882. };
  34883. return SceneSerializer;
  34884. })();
  34885. BABYLON.SceneSerializer = SceneSerializer;
  34886. })(BABYLON || (BABYLON = {}));
  34887. var BABYLON;
  34888. (function (BABYLON) {
  34889. // Unique ID when we import meshes from Babylon to CSG
  34890. var currentCSGMeshId = 0;
  34891. // # class Vertex
  34892. // Represents a vertex of a polygon. Use your own vertex class instead of this
  34893. // one to provide additional features like texture coordinates and vertex
  34894. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  34895. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  34896. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  34897. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  34898. // is not used anywhere else.
  34899. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  34900. var Vertex = (function () {
  34901. function Vertex(pos, normal, uv) {
  34902. this.pos = pos;
  34903. this.normal = normal;
  34904. this.uv = uv;
  34905. }
  34906. Vertex.prototype.clone = function () {
  34907. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  34908. };
  34909. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  34910. // orientation of a polygon is flipped.
  34911. Vertex.prototype.flip = function () {
  34912. this.normal = this.normal.scale(-1);
  34913. };
  34914. // Create a new vertex between this vertex and `other` by linearly
  34915. // interpolating all properties using a parameter of `t`. Subclasses should
  34916. // override this to interpolate additional properties.
  34917. Vertex.prototype.interpolate = function (other, t) {
  34918. 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));
  34919. };
  34920. return Vertex;
  34921. })();
  34922. // # class Plane
  34923. // Represents a plane in 3D space.
  34924. var Plane = (function () {
  34925. function Plane(normal, w) {
  34926. this.normal = normal;
  34927. this.w = w;
  34928. }
  34929. Plane.FromPoints = function (a, b, c) {
  34930. var v0 = c.subtract(a);
  34931. var v1 = b.subtract(a);
  34932. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  34933. return null;
  34934. }
  34935. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  34936. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  34937. };
  34938. Plane.prototype.clone = function () {
  34939. return new Plane(this.normal.clone(), this.w);
  34940. };
  34941. Plane.prototype.flip = function () {
  34942. this.normal.scaleInPlace(-1);
  34943. this.w = -this.w;
  34944. };
  34945. // Split `polygon` by this plane if needed, then put the polygon or polygon
  34946. // fragments in the appropriate lists. Coplanar polygons go into either
  34947. // `coplanarFront` or `coplanarBack` depending on their orientation with
  34948. // respect to this plane. Polygons in front or in back of this plane go into
  34949. // either `front` or `back`.
  34950. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  34951. var COPLANAR = 0;
  34952. var FRONT = 1;
  34953. var BACK = 2;
  34954. var SPANNING = 3;
  34955. // Classify each point as well as the entire polygon into one of the above
  34956. // four classes.
  34957. var polygonType = 0;
  34958. var types = [];
  34959. var i;
  34960. var t;
  34961. for (i = 0; i < polygon.vertices.length; i++) {
  34962. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  34963. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  34964. polygonType |= type;
  34965. types.push(type);
  34966. }
  34967. // Put the polygon in the correct list, splitting it when necessary.
  34968. switch (polygonType) {
  34969. case COPLANAR:
  34970. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  34971. break;
  34972. case FRONT:
  34973. front.push(polygon);
  34974. break;
  34975. case BACK:
  34976. back.push(polygon);
  34977. break;
  34978. case SPANNING:
  34979. var f = [], b = [];
  34980. for (i = 0; i < polygon.vertices.length; i++) {
  34981. var j = (i + 1) % polygon.vertices.length;
  34982. var ti = types[i], tj = types[j];
  34983. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  34984. if (ti !== BACK)
  34985. f.push(vi);
  34986. if (ti !== FRONT)
  34987. b.push(ti !== BACK ? vi.clone() : vi);
  34988. if ((ti | tj) === SPANNING) {
  34989. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  34990. var v = vi.interpolate(vj, t);
  34991. f.push(v);
  34992. b.push(v.clone());
  34993. }
  34994. }
  34995. var poly;
  34996. if (f.length >= 3) {
  34997. poly = new Polygon(f, polygon.shared);
  34998. if (poly.plane)
  34999. front.push(poly);
  35000. }
  35001. if (b.length >= 3) {
  35002. poly = new Polygon(b, polygon.shared);
  35003. if (poly.plane)
  35004. back.push(poly);
  35005. }
  35006. break;
  35007. }
  35008. };
  35009. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  35010. // point is on the plane.
  35011. Plane.EPSILON = 1e-5;
  35012. return Plane;
  35013. })();
  35014. // # class Polygon
  35015. // Represents a convex polygon. The vertices used to initialize a polygon must
  35016. // be coplanar and form a convex loop.
  35017. //
  35018. // Each convex polygon has a `shared` property, which is shared between all
  35019. // polygons that are clones of each other or were split from the same polygon.
  35020. // This can be used to define per-polygon properties (such as surface color).
  35021. var Polygon = (function () {
  35022. function Polygon(vertices, shared) {
  35023. this.vertices = vertices;
  35024. this.shared = shared;
  35025. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  35026. }
  35027. Polygon.prototype.clone = function () {
  35028. var vertices = this.vertices.map(function (v) { return v.clone(); });
  35029. return new Polygon(vertices, this.shared);
  35030. };
  35031. Polygon.prototype.flip = function () {
  35032. this.vertices.reverse().map(function (v) { v.flip(); });
  35033. this.plane.flip();
  35034. };
  35035. return Polygon;
  35036. })();
  35037. // # class Node
  35038. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  35039. // by picking a polygon to split along. That polygon (and all other coplanar
  35040. // polygons) are added directly to that node and the other polygons are added to
  35041. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  35042. // no distinction between internal and leaf nodes.
  35043. var Node = (function () {
  35044. function Node(polygons) {
  35045. this.plane = null;
  35046. this.front = null;
  35047. this.back = null;
  35048. this.polygons = [];
  35049. if (polygons) {
  35050. this.build(polygons);
  35051. }
  35052. }
  35053. Node.prototype.clone = function () {
  35054. var node = new Node();
  35055. node.plane = this.plane && this.plane.clone();
  35056. node.front = this.front && this.front.clone();
  35057. node.back = this.back && this.back.clone();
  35058. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  35059. return node;
  35060. };
  35061. // Convert solid space to empty space and empty space to solid space.
  35062. Node.prototype.invert = function () {
  35063. for (var i = 0; i < this.polygons.length; i++) {
  35064. this.polygons[i].flip();
  35065. }
  35066. if (this.plane) {
  35067. this.plane.flip();
  35068. }
  35069. if (this.front) {
  35070. this.front.invert();
  35071. }
  35072. if (this.back) {
  35073. this.back.invert();
  35074. }
  35075. var temp = this.front;
  35076. this.front = this.back;
  35077. this.back = temp;
  35078. };
  35079. // Recursively remove all polygons in `polygons` that are inside this BSP
  35080. // tree.
  35081. Node.prototype.clipPolygons = function (polygons) {
  35082. if (!this.plane)
  35083. return polygons.slice();
  35084. var front = [], back = [];
  35085. for (var i = 0; i < polygons.length; i++) {
  35086. this.plane.splitPolygon(polygons[i], front, back, front, back);
  35087. }
  35088. if (this.front) {
  35089. front = this.front.clipPolygons(front);
  35090. }
  35091. if (this.back) {
  35092. back = this.back.clipPolygons(back);
  35093. }
  35094. else {
  35095. back = [];
  35096. }
  35097. return front.concat(back);
  35098. };
  35099. // Remove all polygons in this BSP tree that are inside the other BSP tree
  35100. // `bsp`.
  35101. Node.prototype.clipTo = function (bsp) {
  35102. this.polygons = bsp.clipPolygons(this.polygons);
  35103. if (this.front)
  35104. this.front.clipTo(bsp);
  35105. if (this.back)
  35106. this.back.clipTo(bsp);
  35107. };
  35108. // Return a list of all polygons in this BSP tree.
  35109. Node.prototype.allPolygons = function () {
  35110. var polygons = this.polygons.slice();
  35111. if (this.front)
  35112. polygons = polygons.concat(this.front.allPolygons());
  35113. if (this.back)
  35114. polygons = polygons.concat(this.back.allPolygons());
  35115. return polygons;
  35116. };
  35117. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  35118. // new polygons are filtered down to the bottom of the tree and become new
  35119. // nodes there. Each set of polygons is partitioned using the first polygon
  35120. // (no heuristic is used to pick a good split).
  35121. Node.prototype.build = function (polygons) {
  35122. if (!polygons.length)
  35123. return;
  35124. if (!this.plane)
  35125. this.plane = polygons[0].plane.clone();
  35126. var front = [], back = [];
  35127. for (var i = 0; i < polygons.length; i++) {
  35128. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  35129. }
  35130. if (front.length) {
  35131. if (!this.front)
  35132. this.front = new Node();
  35133. this.front.build(front);
  35134. }
  35135. if (back.length) {
  35136. if (!this.back)
  35137. this.back = new Node();
  35138. this.back.build(back);
  35139. }
  35140. };
  35141. return Node;
  35142. })();
  35143. var CSG = (function () {
  35144. function CSG() {
  35145. this.polygons = new Array();
  35146. }
  35147. // Convert BABYLON.Mesh to BABYLON.CSG
  35148. CSG.FromMesh = function (mesh) {
  35149. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  35150. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  35151. if (mesh instanceof BABYLON.Mesh) {
  35152. mesh.computeWorldMatrix(true);
  35153. matrix = mesh.getWorldMatrix();
  35154. meshPosition = mesh.position.clone();
  35155. meshRotation = mesh.rotation.clone();
  35156. if (mesh.rotationQuaternion) {
  35157. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  35158. }
  35159. meshScaling = mesh.scaling.clone();
  35160. }
  35161. else {
  35162. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  35163. }
  35164. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35165. var subMeshes = mesh.subMeshes;
  35166. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  35167. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  35168. vertices = [];
  35169. for (var j = 0; j < 3; j++) {
  35170. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  35171. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  35172. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  35173. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  35174. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  35175. vertex = new Vertex(position, normal, uv);
  35176. vertices.push(vertex);
  35177. }
  35178. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  35179. // To handle the case of degenerated triangle
  35180. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  35181. if (polygon.plane)
  35182. polygons.push(polygon);
  35183. }
  35184. }
  35185. var csg = CSG.FromPolygons(polygons);
  35186. csg.matrix = matrix;
  35187. csg.position = meshPosition;
  35188. csg.rotation = meshRotation;
  35189. csg.scaling = meshScaling;
  35190. csg.rotationQuaternion = meshRotationQuaternion;
  35191. currentCSGMeshId++;
  35192. return csg;
  35193. };
  35194. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  35195. CSG.FromPolygons = function (polygons) {
  35196. var csg = new CSG();
  35197. csg.polygons = polygons;
  35198. return csg;
  35199. };
  35200. CSG.prototype.clone = function () {
  35201. var csg = new CSG();
  35202. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  35203. csg.copyTransformAttributes(this);
  35204. return csg;
  35205. };
  35206. CSG.prototype.toPolygons = function () {
  35207. return this.polygons;
  35208. };
  35209. CSG.prototype.union = function (csg) {
  35210. var a = new Node(this.clone().polygons);
  35211. var b = new Node(csg.clone().polygons);
  35212. a.clipTo(b);
  35213. b.clipTo(a);
  35214. b.invert();
  35215. b.clipTo(a);
  35216. b.invert();
  35217. a.build(b.allPolygons());
  35218. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35219. };
  35220. CSG.prototype.unionInPlace = function (csg) {
  35221. var a = new Node(this.polygons);
  35222. var b = new Node(csg.polygons);
  35223. a.clipTo(b);
  35224. b.clipTo(a);
  35225. b.invert();
  35226. b.clipTo(a);
  35227. b.invert();
  35228. a.build(b.allPolygons());
  35229. this.polygons = a.allPolygons();
  35230. };
  35231. CSG.prototype.subtract = function (csg) {
  35232. var a = new Node(this.clone().polygons);
  35233. var b = new Node(csg.clone().polygons);
  35234. a.invert();
  35235. a.clipTo(b);
  35236. b.clipTo(a);
  35237. b.invert();
  35238. b.clipTo(a);
  35239. b.invert();
  35240. a.build(b.allPolygons());
  35241. a.invert();
  35242. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35243. };
  35244. CSG.prototype.subtractInPlace = function (csg) {
  35245. var a = new Node(this.polygons);
  35246. var b = new Node(csg.polygons);
  35247. a.invert();
  35248. a.clipTo(b);
  35249. b.clipTo(a);
  35250. b.invert();
  35251. b.clipTo(a);
  35252. b.invert();
  35253. a.build(b.allPolygons());
  35254. a.invert();
  35255. this.polygons = a.allPolygons();
  35256. };
  35257. CSG.prototype.intersect = function (csg) {
  35258. var a = new Node(this.clone().polygons);
  35259. var b = new Node(csg.clone().polygons);
  35260. a.invert();
  35261. b.clipTo(a);
  35262. b.invert();
  35263. a.clipTo(b);
  35264. b.clipTo(a);
  35265. a.build(b.allPolygons());
  35266. a.invert();
  35267. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35268. };
  35269. CSG.prototype.intersectInPlace = function (csg) {
  35270. var a = new Node(this.polygons);
  35271. var b = new Node(csg.polygons);
  35272. a.invert();
  35273. b.clipTo(a);
  35274. b.invert();
  35275. a.clipTo(b);
  35276. b.clipTo(a);
  35277. a.build(b.allPolygons());
  35278. a.invert();
  35279. this.polygons = a.allPolygons();
  35280. };
  35281. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  35282. // not modified.
  35283. CSG.prototype.inverse = function () {
  35284. var csg = this.clone();
  35285. csg.inverseInPlace();
  35286. return csg;
  35287. };
  35288. CSG.prototype.inverseInPlace = function () {
  35289. this.polygons.map(function (p) { p.flip(); });
  35290. };
  35291. // This is used to keep meshes transformations so they can be restored
  35292. // when we build back a Babylon Mesh
  35293. // NB : All CSG operations are performed in world coordinates
  35294. CSG.prototype.copyTransformAttributes = function (csg) {
  35295. this.matrix = csg.matrix;
  35296. this.position = csg.position;
  35297. this.rotation = csg.rotation;
  35298. this.scaling = csg.scaling;
  35299. this.rotationQuaternion = csg.rotationQuaternion;
  35300. return this;
  35301. };
  35302. // Build Raw mesh from CSG
  35303. // Coordinates here are in world space
  35304. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  35305. var matrix = this.matrix.clone();
  35306. matrix.invert();
  35307. 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;
  35308. if (keepSubMeshes) {
  35309. // Sort Polygons, since subMeshes are indices range
  35310. polygons.sort(function (a, b) {
  35311. if (a.shared.meshId === b.shared.meshId) {
  35312. return a.shared.subMeshId - b.shared.subMeshId;
  35313. }
  35314. else {
  35315. return a.shared.meshId - b.shared.meshId;
  35316. }
  35317. });
  35318. }
  35319. for (var i = 0, il = polygons.length; i < il; i++) {
  35320. polygon = polygons[i];
  35321. // Building SubMeshes
  35322. if (!subMesh_dict[polygon.shared.meshId]) {
  35323. subMesh_dict[polygon.shared.meshId] = {};
  35324. }
  35325. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  35326. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  35327. indexStart: +Infinity,
  35328. indexEnd: -Infinity,
  35329. materialIndex: polygon.shared.materialIndex
  35330. };
  35331. }
  35332. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  35333. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  35334. polygonIndices[0] = 0;
  35335. polygonIndices[1] = j - 1;
  35336. polygonIndices[2] = j;
  35337. for (var k = 0; k < 3; k++) {
  35338. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  35339. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  35340. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  35341. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  35342. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  35343. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  35344. // Check if 2 points can be merged
  35345. if (!(typeof vertex_idx !== 'undefined' &&
  35346. normals[vertex_idx * 3] === localNormal.x &&
  35347. normals[vertex_idx * 3 + 1] === localNormal.y &&
  35348. normals[vertex_idx * 3 + 2] === localNormal.z &&
  35349. uvs[vertex_idx * 2] === uv.x &&
  35350. uvs[vertex_idx * 2 + 1] === uv.y)) {
  35351. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  35352. uvs.push(uv.x, uv.y);
  35353. normals.push(normal.x, normal.y, normal.z);
  35354. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  35355. }
  35356. indices.push(vertex_idx);
  35357. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  35358. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  35359. currentIndex++;
  35360. }
  35361. }
  35362. }
  35363. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  35364. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  35365. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  35366. mesh.setIndices(indices);
  35367. if (keepSubMeshes) {
  35368. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  35369. var materialIndexOffset = 0, materialMaxIndex;
  35370. mesh.subMeshes = new Array();
  35371. for (var m in subMesh_dict) {
  35372. materialMaxIndex = -1;
  35373. for (var sm in subMesh_dict[m]) {
  35374. subMesh_obj = subMesh_dict[m][sm];
  35375. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  35376. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  35377. }
  35378. materialIndexOffset += ++materialMaxIndex;
  35379. }
  35380. }
  35381. return mesh;
  35382. };
  35383. // Build Mesh from CSG taking material and transforms into account
  35384. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  35385. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  35386. mesh.material = material;
  35387. mesh.position.copyFrom(this.position);
  35388. mesh.rotation.copyFrom(this.rotation);
  35389. if (this.rotationQuaternion) {
  35390. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  35391. }
  35392. mesh.scaling.copyFrom(this.scaling);
  35393. mesh.computeWorldMatrix(true);
  35394. return mesh;
  35395. };
  35396. return CSG;
  35397. })();
  35398. BABYLON.CSG = CSG;
  35399. })(BABYLON || (BABYLON = {}));
  35400. var BABYLON;
  35401. (function (BABYLON) {
  35402. var VRDistortionCorrectionPostProcess = (function (_super) {
  35403. __extends(VRDistortionCorrectionPostProcess, _super);
  35404. //ANY
  35405. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  35406. var _this = this;
  35407. _super.call(this, name, "vrDistortionCorrection", [
  35408. 'LensCenter',
  35409. 'Scale',
  35410. 'ScaleIn',
  35411. 'HmdWarpParam'
  35412. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  35413. this._isRightEye = isRightEye;
  35414. this._distortionFactors = vrMetrics.distortionK;
  35415. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  35416. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  35417. this.onSizeChanged = function () {
  35418. _this.aspectRatio = _this.width * .5 / _this.height;
  35419. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  35420. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  35421. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  35422. };
  35423. this.onApply = function (effect) {
  35424. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  35425. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  35426. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  35427. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  35428. };
  35429. }
  35430. return VRDistortionCorrectionPostProcess;
  35431. })(BABYLON.PostProcess);
  35432. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  35433. })(BABYLON || (BABYLON = {}));
  35434. // Mainly based on these 2 articles :
  35435. // 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
  35436. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  35437. var BABYLON;
  35438. (function (BABYLON) {
  35439. (function (JoystickAxis) {
  35440. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  35441. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  35442. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  35443. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  35444. var JoystickAxis = BABYLON.JoystickAxis;
  35445. var VirtualJoystick = (function () {
  35446. function VirtualJoystick(leftJoystick) {
  35447. var _this = this;
  35448. if (leftJoystick) {
  35449. this._leftJoystick = true;
  35450. }
  35451. else {
  35452. this._leftJoystick = false;
  35453. }
  35454. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  35455. VirtualJoystick._globalJoystickIndex++;
  35456. // By default left & right arrow keys are moving the X
  35457. // and up & down keys are moving the Y
  35458. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  35459. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  35460. this.reverseLeftRight = false;
  35461. this.reverseUpDown = false;
  35462. // collections of pointers
  35463. this._touches = new BABYLON.SmartCollection();
  35464. this.deltaPosition = BABYLON.Vector3.Zero();
  35465. this._joystickSensibility = 25;
  35466. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  35467. this._rotationSpeed = 25;
  35468. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  35469. this._rotateOnAxisRelativeToMesh = false;
  35470. this._onResize = function (evt) {
  35471. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  35472. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  35473. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  35474. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  35475. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  35476. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  35477. };
  35478. // injecting a canvas element on top of the canvas 3D game
  35479. if (!VirtualJoystick.vjCanvas) {
  35480. window.addEventListener("resize", this._onResize, false);
  35481. VirtualJoystick.vjCanvas = document.createElement("canvas");
  35482. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  35483. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  35484. VirtualJoystick.vjCanvas.width = window.innerWidth;
  35485. VirtualJoystick.vjCanvas.height = window.innerHeight;
  35486. VirtualJoystick.vjCanvas.style.width = "100%";
  35487. VirtualJoystick.vjCanvas.style.height = "100%";
  35488. VirtualJoystick.vjCanvas.style.position = "absolute";
  35489. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  35490. VirtualJoystick.vjCanvas.style.top = "0px";
  35491. VirtualJoystick.vjCanvas.style.left = "0px";
  35492. VirtualJoystick.vjCanvas.style.zIndex = "5";
  35493. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  35494. // Support for jQuery PEP polyfill
  35495. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  35496. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  35497. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  35498. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  35499. document.body.appendChild(VirtualJoystick.vjCanvas);
  35500. }
  35501. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  35502. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  35503. this.pressed = false;
  35504. // default joystick color
  35505. this._joystickColor = "cyan";
  35506. this._joystickPointerID = -1;
  35507. // current joystick position
  35508. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  35509. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  35510. // origin joystick position
  35511. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  35512. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  35513. this._onPointerDownHandlerRef = function (evt) {
  35514. _this._onPointerDown(evt);
  35515. };
  35516. this._onPointerMoveHandlerRef = function (evt) {
  35517. _this._onPointerMove(evt);
  35518. };
  35519. this._onPointerOutHandlerRef = function (evt) {
  35520. _this._onPointerUp(evt);
  35521. };
  35522. this._onPointerUpHandlerRef = function (evt) {
  35523. _this._onPointerUp(evt);
  35524. };
  35525. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  35526. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  35527. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  35528. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  35529. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  35530. evt.preventDefault(); // Disables system menu
  35531. }, false);
  35532. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  35533. }
  35534. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  35535. this._joystickSensibility = newJoystickSensibility;
  35536. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  35537. };
  35538. VirtualJoystick.prototype._onPointerDown = function (e) {
  35539. var positionOnScreenCondition;
  35540. e.preventDefault();
  35541. if (this._leftJoystick === true) {
  35542. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  35543. }
  35544. else {
  35545. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  35546. }
  35547. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  35548. // First contact will be dedicated to the virtual joystick
  35549. this._joystickPointerID = e.pointerId;
  35550. this._joystickPointerStartPos.x = e.clientX;
  35551. this._joystickPointerStartPos.y = e.clientY;
  35552. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  35553. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  35554. this._deltaJoystickVector.x = 0;
  35555. this._deltaJoystickVector.y = 0;
  35556. this.pressed = true;
  35557. this._touches.add(e.pointerId.toString(), e);
  35558. }
  35559. else {
  35560. // You can only trigger the action buttons with a joystick declared
  35561. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  35562. this._action();
  35563. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  35564. }
  35565. }
  35566. };
  35567. VirtualJoystick.prototype._onPointerMove = function (e) {
  35568. // If the current pointer is the one associated to the joystick (first touch contact)
  35569. if (this._joystickPointerID == e.pointerId) {
  35570. this._joystickPointerPos.x = e.clientX;
  35571. this._joystickPointerPos.y = e.clientY;
  35572. this._deltaJoystickVector = this._joystickPointerPos.clone();
  35573. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  35574. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  35575. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  35576. switch (this._axisTargetedByLeftAndRight) {
  35577. case JoystickAxis.X:
  35578. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  35579. break;
  35580. case JoystickAxis.Y:
  35581. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  35582. break;
  35583. case JoystickAxis.Z:
  35584. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  35585. break;
  35586. }
  35587. var directionUpDown = this.reverseUpDown ? 1 : -1;
  35588. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  35589. switch (this._axisTargetedByUpAndDown) {
  35590. case JoystickAxis.X:
  35591. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  35592. break;
  35593. case JoystickAxis.Y:
  35594. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  35595. break;
  35596. case JoystickAxis.Z:
  35597. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  35598. break;
  35599. }
  35600. }
  35601. else {
  35602. if (this._touches.item(e.pointerId.toString())) {
  35603. this._touches.item(e.pointerId.toString()).x = e.clientX;
  35604. this._touches.item(e.pointerId.toString()).y = e.clientY;
  35605. }
  35606. }
  35607. };
  35608. VirtualJoystick.prototype._onPointerUp = function (e) {
  35609. if (this._joystickPointerID == e.pointerId) {
  35610. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  35611. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  35612. this._joystickPointerID = -1;
  35613. this.pressed = false;
  35614. }
  35615. else {
  35616. var touch = this._touches.item(e.pointerId.toString());
  35617. if (touch) {
  35618. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  35619. }
  35620. }
  35621. this._deltaJoystickVector.x = 0;
  35622. this._deltaJoystickVector.y = 0;
  35623. this._touches.remove(e.pointerId.toString());
  35624. };
  35625. /**
  35626. * Change the color of the virtual joystick
  35627. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  35628. */
  35629. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  35630. this._joystickColor = newColor;
  35631. };
  35632. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  35633. this._action = action;
  35634. };
  35635. // Define which axis you'd like to control for left & right
  35636. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  35637. switch (axis) {
  35638. case JoystickAxis.X:
  35639. case JoystickAxis.Y:
  35640. case JoystickAxis.Z:
  35641. this._axisTargetedByLeftAndRight = axis;
  35642. break;
  35643. default:
  35644. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  35645. break;
  35646. }
  35647. };
  35648. // Define which axis you'd like to control for up & down
  35649. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  35650. switch (axis) {
  35651. case JoystickAxis.X:
  35652. case JoystickAxis.Y:
  35653. case JoystickAxis.Z:
  35654. this._axisTargetedByUpAndDown = axis;
  35655. break;
  35656. default:
  35657. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  35658. break;
  35659. }
  35660. };
  35661. VirtualJoystick.prototype._clearCanvas = function () {
  35662. if (this._leftJoystick) {
  35663. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  35664. }
  35665. else {
  35666. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  35667. }
  35668. };
  35669. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  35670. var _this = this;
  35671. if (this.pressed) {
  35672. this._touches.forEach(function (touch) {
  35673. if (touch.pointerId === _this._joystickPointerID) {
  35674. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  35675. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  35676. VirtualJoystick.vjCanvasContext.beginPath();
  35677. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  35678. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35679. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  35680. VirtualJoystick.vjCanvasContext.stroke();
  35681. VirtualJoystick.vjCanvasContext.closePath();
  35682. VirtualJoystick.vjCanvasContext.beginPath();
  35683. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35684. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  35685. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  35686. VirtualJoystick.vjCanvasContext.stroke();
  35687. VirtualJoystick.vjCanvasContext.closePath();
  35688. VirtualJoystick.vjCanvasContext.beginPath();
  35689. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35690. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  35691. VirtualJoystick.vjCanvasContext.stroke();
  35692. VirtualJoystick.vjCanvasContext.closePath();
  35693. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  35694. }
  35695. else {
  35696. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  35697. VirtualJoystick.vjCanvasContext.beginPath();
  35698. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  35699. VirtualJoystick.vjCanvasContext.beginPath();
  35700. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  35701. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  35702. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  35703. VirtualJoystick.vjCanvasContext.stroke();
  35704. VirtualJoystick.vjCanvasContext.closePath();
  35705. touch.prevX = touch.x;
  35706. touch.prevY = touch.y;
  35707. }
  35708. ;
  35709. });
  35710. }
  35711. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  35712. };
  35713. VirtualJoystick.prototype.releaseCanvas = function () {
  35714. if (VirtualJoystick.vjCanvas) {
  35715. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  35716. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  35717. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  35718. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  35719. window.removeEventListener("resize", this._onResize);
  35720. document.body.removeChild(VirtualJoystick.vjCanvas);
  35721. VirtualJoystick.vjCanvas = null;
  35722. }
  35723. };
  35724. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  35725. VirtualJoystick._globalJoystickIndex = 0;
  35726. return VirtualJoystick;
  35727. })();
  35728. BABYLON.VirtualJoystick = VirtualJoystick;
  35729. })(BABYLON || (BABYLON = {}));
  35730. var BABYLON;
  35731. (function (BABYLON) {
  35732. // We're mainly based on the logic defined into the FreeCamera code
  35733. var VirtualJoysticksCamera = (function (_super) {
  35734. __extends(VirtualJoysticksCamera, _super);
  35735. function VirtualJoysticksCamera(name, position, scene) {
  35736. _super.call(this, name, position, scene);
  35737. this.inputs.addVirtualJoystick();
  35738. }
  35739. return VirtualJoysticksCamera;
  35740. })(BABYLON.FreeCamera);
  35741. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  35742. })(BABYLON || (BABYLON = {}));
  35743. var BABYLON;
  35744. (function (BABYLON) {
  35745. var AnaglyphPostProcess = (function (_super) {
  35746. __extends(AnaglyphPostProcess, _super);
  35747. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35748. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  35749. }
  35750. return AnaglyphPostProcess;
  35751. })(BABYLON.PostProcess);
  35752. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  35753. })(BABYLON || (BABYLON = {}));
  35754. var BABYLON;
  35755. (function (BABYLON) {
  35756. var OutlineRenderer = (function () {
  35757. function OutlineRenderer(scene) {
  35758. this._scene = scene;
  35759. }
  35760. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  35761. var _this = this;
  35762. if (useOverlay === void 0) { useOverlay = false; }
  35763. var scene = this._scene;
  35764. var engine = this._scene.getEngine();
  35765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35766. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  35767. return;
  35768. }
  35769. var mesh = subMesh.getRenderingMesh();
  35770. var material = subMesh.getMaterial();
  35771. engine.enableEffect(this._effect);
  35772. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  35773. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  35774. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35775. // Bones
  35776. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35777. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35778. }
  35779. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35780. // Alpha test
  35781. if (material && material.needAlphaTesting()) {
  35782. var alphaTexture = material.getAlphaTestTexture();
  35783. this._effect.setTexture("diffuseSampler", alphaTexture);
  35784. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35785. }
  35786. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  35787. };
  35788. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  35789. var defines = [];
  35790. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  35791. var mesh = subMesh.getMesh();
  35792. var material = subMesh.getMaterial();
  35793. // Alpha test
  35794. if (material && material.needAlphaTesting()) {
  35795. defines.push("#define ALPHATEST");
  35796. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35797. attribs.push(BABYLON.VertexBuffer.UVKind);
  35798. defines.push("#define UV1");
  35799. }
  35800. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35801. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35802. defines.push("#define UV2");
  35803. }
  35804. }
  35805. // Bones
  35806. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35807. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35808. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35809. if (mesh.numBoneInfluencers > 4) {
  35810. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35811. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35812. }
  35813. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35814. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35815. }
  35816. else {
  35817. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35818. }
  35819. // Instances
  35820. if (useInstances) {
  35821. defines.push("#define INSTANCES");
  35822. attribs.push("world0");
  35823. attribs.push("world1");
  35824. attribs.push("world2");
  35825. attribs.push("world3");
  35826. }
  35827. // Get correct effect
  35828. var join = defines.join("\n");
  35829. if (this._cachedDefines !== join) {
  35830. this._cachedDefines = join;
  35831. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  35832. }
  35833. return this._effect.isReady();
  35834. };
  35835. return OutlineRenderer;
  35836. })();
  35837. BABYLON.OutlineRenderer = OutlineRenderer;
  35838. })(BABYLON || (BABYLON = {}));
  35839. var BABYLON;
  35840. (function (BABYLON) {
  35841. var MeshAssetTask = (function () {
  35842. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  35843. this.name = name;
  35844. this.meshesNames = meshesNames;
  35845. this.rootUrl = rootUrl;
  35846. this.sceneFilename = sceneFilename;
  35847. this.isCompleted = false;
  35848. }
  35849. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35850. var _this = this;
  35851. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  35852. _this.loadedMeshes = meshes;
  35853. _this.loadedParticleSystems = particleSystems;
  35854. _this.loadedSkeletons = skeletons;
  35855. _this.isCompleted = true;
  35856. if (_this.onSuccess) {
  35857. _this.onSuccess(_this);
  35858. }
  35859. onSuccess();
  35860. }, null, function () {
  35861. if (_this.onError) {
  35862. _this.onError(_this);
  35863. }
  35864. onError();
  35865. });
  35866. };
  35867. return MeshAssetTask;
  35868. })();
  35869. BABYLON.MeshAssetTask = MeshAssetTask;
  35870. var TextFileAssetTask = (function () {
  35871. function TextFileAssetTask(name, url) {
  35872. this.name = name;
  35873. this.url = url;
  35874. this.isCompleted = false;
  35875. }
  35876. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35877. var _this = this;
  35878. BABYLON.Tools.LoadFile(this.url, function (data) {
  35879. _this.text = data;
  35880. _this.isCompleted = true;
  35881. if (_this.onSuccess) {
  35882. _this.onSuccess(_this);
  35883. }
  35884. onSuccess();
  35885. }, null, scene.database, false, function () {
  35886. if (_this.onError) {
  35887. _this.onError(_this);
  35888. }
  35889. onError();
  35890. });
  35891. };
  35892. return TextFileAssetTask;
  35893. })();
  35894. BABYLON.TextFileAssetTask = TextFileAssetTask;
  35895. var BinaryFileAssetTask = (function () {
  35896. function BinaryFileAssetTask(name, url) {
  35897. this.name = name;
  35898. this.url = url;
  35899. this.isCompleted = false;
  35900. }
  35901. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35902. var _this = this;
  35903. BABYLON.Tools.LoadFile(this.url, function (data) {
  35904. _this.data = data;
  35905. _this.isCompleted = true;
  35906. if (_this.onSuccess) {
  35907. _this.onSuccess(_this);
  35908. }
  35909. onSuccess();
  35910. }, null, scene.database, true, function () {
  35911. if (_this.onError) {
  35912. _this.onError(_this);
  35913. }
  35914. onError();
  35915. });
  35916. };
  35917. return BinaryFileAssetTask;
  35918. })();
  35919. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  35920. var ImageAssetTask = (function () {
  35921. function ImageAssetTask(name, url) {
  35922. this.name = name;
  35923. this.url = url;
  35924. this.isCompleted = false;
  35925. }
  35926. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35927. var _this = this;
  35928. var img = new Image();
  35929. img.onload = function () {
  35930. _this.image = img;
  35931. _this.isCompleted = true;
  35932. if (_this.onSuccess) {
  35933. _this.onSuccess(_this);
  35934. }
  35935. onSuccess();
  35936. };
  35937. img.onerror = function () {
  35938. if (_this.onError) {
  35939. _this.onError(_this);
  35940. }
  35941. onError();
  35942. };
  35943. img.src = this.url;
  35944. };
  35945. return ImageAssetTask;
  35946. })();
  35947. BABYLON.ImageAssetTask = ImageAssetTask;
  35948. var TextureAssetTask = (function () {
  35949. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  35950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35951. this.name = name;
  35952. this.url = url;
  35953. this.noMipmap = noMipmap;
  35954. this.invertY = invertY;
  35955. this.samplingMode = samplingMode;
  35956. this.isCompleted = false;
  35957. }
  35958. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35959. var _this = this;
  35960. var onload = function () {
  35961. _this.isCompleted = true;
  35962. if (_this.onSuccess) {
  35963. _this.onSuccess(_this);
  35964. }
  35965. onSuccess();
  35966. };
  35967. var onerror = function () {
  35968. if (_this.onError) {
  35969. _this.onError(_this);
  35970. }
  35971. onError();
  35972. };
  35973. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  35974. };
  35975. return TextureAssetTask;
  35976. })();
  35977. BABYLON.TextureAssetTask = TextureAssetTask;
  35978. var AssetsManager = (function () {
  35979. function AssetsManager(scene) {
  35980. this._tasks = new Array();
  35981. this._waitingTasksCount = 0;
  35982. this.useDefaultLoadingScreen = true;
  35983. this._scene = scene;
  35984. }
  35985. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  35986. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  35987. this._tasks.push(task);
  35988. return task;
  35989. };
  35990. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  35991. var task = new TextFileAssetTask(taskName, url);
  35992. this._tasks.push(task);
  35993. return task;
  35994. };
  35995. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  35996. var task = new BinaryFileAssetTask(taskName, url);
  35997. this._tasks.push(task);
  35998. return task;
  35999. };
  36000. AssetsManager.prototype.addImageTask = function (taskName, url) {
  36001. var task = new ImageAssetTask(taskName, url);
  36002. this._tasks.push(task);
  36003. return task;
  36004. };
  36005. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  36006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36007. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  36008. this._tasks.push(task);
  36009. return task;
  36010. };
  36011. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  36012. this._waitingTasksCount--;
  36013. if (this._waitingTasksCount === 0) {
  36014. if (this.onFinish) {
  36015. this.onFinish(this._tasks);
  36016. }
  36017. this._scene.getEngine().hideLoadingUI();
  36018. }
  36019. };
  36020. AssetsManager.prototype._runTask = function (task) {
  36021. var _this = this;
  36022. task.run(this._scene, function () {
  36023. if (_this.onTaskSuccess) {
  36024. _this.onTaskSuccess(task);
  36025. }
  36026. _this._decreaseWaitingTasksCount();
  36027. }, function () {
  36028. if (_this.onTaskError) {
  36029. _this.onTaskError(task);
  36030. }
  36031. _this._decreaseWaitingTasksCount();
  36032. });
  36033. };
  36034. AssetsManager.prototype.reset = function () {
  36035. this._tasks = new Array();
  36036. return this;
  36037. };
  36038. AssetsManager.prototype.load = function () {
  36039. this._waitingTasksCount = this._tasks.length;
  36040. if (this._waitingTasksCount === 0) {
  36041. if (this.onFinish) {
  36042. this.onFinish(this._tasks);
  36043. }
  36044. return this;
  36045. }
  36046. if (this.useDefaultLoadingScreen) {
  36047. this._scene.getEngine().displayLoadingUI();
  36048. }
  36049. for (var index = 0; index < this._tasks.length; index++) {
  36050. var task = this._tasks[index];
  36051. this._runTask(task);
  36052. }
  36053. return this;
  36054. };
  36055. return AssetsManager;
  36056. })();
  36057. BABYLON.AssetsManager = AssetsManager;
  36058. })(BABYLON || (BABYLON = {}));
  36059. var BABYLON;
  36060. (function (BABYLON) {
  36061. var VRCameraMetrics = (function () {
  36062. function VRCameraMetrics() {
  36063. this.compensateDistortion = true;
  36064. }
  36065. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  36066. get: function () {
  36067. return this.hResolution / (2 * this.vResolution);
  36068. },
  36069. enumerable: true,
  36070. configurable: true
  36071. });
  36072. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  36073. get: function () {
  36074. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  36075. },
  36076. enumerable: true,
  36077. configurable: true
  36078. });
  36079. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  36080. get: function () {
  36081. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  36082. var h = (4 * meters) / this.hScreenSize;
  36083. return BABYLON.Matrix.Translation(h, 0, 0);
  36084. },
  36085. enumerable: true,
  36086. configurable: true
  36087. });
  36088. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  36089. get: function () {
  36090. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  36091. var h = (4 * meters) / this.hScreenSize;
  36092. return BABYLON.Matrix.Translation(-h, 0, 0);
  36093. },
  36094. enumerable: true,
  36095. configurable: true
  36096. });
  36097. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  36098. get: function () {
  36099. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  36100. },
  36101. enumerable: true,
  36102. configurable: true
  36103. });
  36104. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  36105. get: function () {
  36106. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  36107. },
  36108. enumerable: true,
  36109. configurable: true
  36110. });
  36111. VRCameraMetrics.GetDefault = function () {
  36112. var result = new VRCameraMetrics();
  36113. result.hResolution = 1280;
  36114. result.vResolution = 800;
  36115. result.hScreenSize = 0.149759993;
  36116. result.vScreenSize = 0.0935999975;
  36117. result.vScreenCenter = 0.0467999987,
  36118. result.eyeToScreenDistance = 0.0410000011;
  36119. result.lensSeparationDistance = 0.0635000020;
  36120. result.interpupillaryDistance = 0.0640000030;
  36121. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  36122. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  36123. result.postProcessScaleFactor = 1.714605507808412;
  36124. result.lensCenterOffset = 0.151976421;
  36125. return result;
  36126. };
  36127. return VRCameraMetrics;
  36128. })();
  36129. BABYLON.VRCameraMetrics = VRCameraMetrics;
  36130. })(BABYLON || (BABYLON = {}));
  36131. var BABYLON;
  36132. (function (BABYLON) {
  36133. var VRDeviceOrientationFreeCamera = (function (_super) {
  36134. __extends(VRDeviceOrientationFreeCamera, _super);
  36135. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  36136. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36137. _super.call(this, name, position, scene);
  36138. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  36139. metrics.compensateDistortion = compensateDistortion;
  36140. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  36141. this.inputs.addVRDeviceOrientation();
  36142. }
  36143. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  36144. return "VRDeviceOrientationFreeCamera";
  36145. };
  36146. return VRDeviceOrientationFreeCamera;
  36147. })(BABYLON.FreeCamera);
  36148. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  36149. })(BABYLON || (BABYLON = {}));
  36150. var BABYLON;
  36151. (function (BABYLON) {
  36152. var WebVRFreeCamera = (function (_super) {
  36153. __extends(WebVRFreeCamera, _super);
  36154. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  36155. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36156. _super.call(this, name, position, scene);
  36157. this._hmdDevice = null;
  36158. this._sensorDevice = null;
  36159. this._cacheState = null;
  36160. this._cacheQuaternion = new BABYLON.Quaternion();
  36161. this._cacheRotation = BABYLON.Vector3.Zero();
  36162. this._vrEnabled = false;
  36163. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  36164. metrics.compensateDistortion = compensateDistortion;
  36165. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  36166. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  36167. }
  36168. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  36169. var size = devices.length;
  36170. var i = 0;
  36171. // Reset devices.
  36172. this._sensorDevice = null;
  36173. this._hmdDevice = null;
  36174. // Search for a HmdDevice.
  36175. while (i < size && this._hmdDevice === null) {
  36176. if (devices[i] instanceof HMDVRDevice) {
  36177. this._hmdDevice = devices[i];
  36178. }
  36179. i++;
  36180. }
  36181. i = 0;
  36182. while (i < size && this._sensorDevice === null) {
  36183. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  36184. this._sensorDevice = devices[i];
  36185. }
  36186. i++;
  36187. }
  36188. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  36189. };
  36190. WebVRFreeCamera.prototype._checkInputs = function () {
  36191. if (this._vrEnabled) {
  36192. this._cacheState = this._sensorDevice.getState();
  36193. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  36194. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  36195. this.rotation.x = -this._cacheRotation.x;
  36196. this.rotation.y = -this._cacheRotation.y;
  36197. this.rotation.z = this._cacheRotation.z;
  36198. }
  36199. _super.prototype._checkInputs.call(this);
  36200. };
  36201. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  36202. _super.prototype.attachControl.call(this, element, noPreventDefault);
  36203. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36204. if (navigator.getVRDevices) {
  36205. navigator.getVRDevices().then(this._getWebVRDevices);
  36206. }
  36207. else if (navigator.mozGetVRDevices) {
  36208. navigator.mozGetVRDevices(this._getWebVRDevices);
  36209. }
  36210. };
  36211. WebVRFreeCamera.prototype.detachControl = function (element) {
  36212. _super.prototype.detachControl.call(this, element);
  36213. this._vrEnabled = false;
  36214. };
  36215. WebVRFreeCamera.prototype.getTypeName = function () {
  36216. return "WebVRFreeCamera";
  36217. };
  36218. return WebVRFreeCamera;
  36219. })(BABYLON.FreeCamera);
  36220. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  36221. })(BABYLON || (BABYLON = {}));
  36222. var BABYLON;
  36223. (function (BABYLON) {
  36224. // Standard optimizations
  36225. var SceneOptimization = (function () {
  36226. function SceneOptimization(priority) {
  36227. if (priority === void 0) { priority = 0; }
  36228. this.priority = priority;
  36229. this.apply = function (scene) {
  36230. return true; // Return true if everything that can be done was applied
  36231. };
  36232. }
  36233. return SceneOptimization;
  36234. })();
  36235. BABYLON.SceneOptimization = SceneOptimization;
  36236. var TextureOptimization = (function (_super) {
  36237. __extends(TextureOptimization, _super);
  36238. function TextureOptimization(priority, maximumSize) {
  36239. var _this = this;
  36240. if (priority === void 0) { priority = 0; }
  36241. if (maximumSize === void 0) { maximumSize = 1024; }
  36242. _super.call(this, priority);
  36243. this.priority = priority;
  36244. this.maximumSize = maximumSize;
  36245. this.apply = function (scene) {
  36246. var allDone = true;
  36247. for (var index = 0; index < scene.textures.length; index++) {
  36248. var texture = scene.textures[index];
  36249. if (!texture.canRescale) {
  36250. continue;
  36251. }
  36252. var currentSize = texture.getSize();
  36253. var maxDimension = Math.max(currentSize.width, currentSize.height);
  36254. if (maxDimension > _this.maximumSize) {
  36255. texture.scale(0.5);
  36256. allDone = false;
  36257. }
  36258. }
  36259. return allDone;
  36260. };
  36261. }
  36262. return TextureOptimization;
  36263. })(SceneOptimization);
  36264. BABYLON.TextureOptimization = TextureOptimization;
  36265. var HardwareScalingOptimization = (function (_super) {
  36266. __extends(HardwareScalingOptimization, _super);
  36267. function HardwareScalingOptimization(priority, maximumScale) {
  36268. var _this = this;
  36269. if (priority === void 0) { priority = 0; }
  36270. if (maximumScale === void 0) { maximumScale = 2; }
  36271. _super.call(this, priority);
  36272. this.priority = priority;
  36273. this.maximumScale = maximumScale;
  36274. this._currentScale = 1;
  36275. this.apply = function (scene) {
  36276. _this._currentScale++;
  36277. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  36278. return _this._currentScale >= _this.maximumScale;
  36279. };
  36280. }
  36281. return HardwareScalingOptimization;
  36282. })(SceneOptimization);
  36283. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  36284. var ShadowsOptimization = (function (_super) {
  36285. __extends(ShadowsOptimization, _super);
  36286. function ShadowsOptimization() {
  36287. _super.apply(this, arguments);
  36288. this.apply = function (scene) {
  36289. scene.shadowsEnabled = false;
  36290. return true;
  36291. };
  36292. }
  36293. return ShadowsOptimization;
  36294. })(SceneOptimization);
  36295. BABYLON.ShadowsOptimization = ShadowsOptimization;
  36296. var PostProcessesOptimization = (function (_super) {
  36297. __extends(PostProcessesOptimization, _super);
  36298. function PostProcessesOptimization() {
  36299. _super.apply(this, arguments);
  36300. this.apply = function (scene) {
  36301. scene.postProcessesEnabled = false;
  36302. return true;
  36303. };
  36304. }
  36305. return PostProcessesOptimization;
  36306. })(SceneOptimization);
  36307. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  36308. var LensFlaresOptimization = (function (_super) {
  36309. __extends(LensFlaresOptimization, _super);
  36310. function LensFlaresOptimization() {
  36311. _super.apply(this, arguments);
  36312. this.apply = function (scene) {
  36313. scene.lensFlaresEnabled = false;
  36314. return true;
  36315. };
  36316. }
  36317. return LensFlaresOptimization;
  36318. })(SceneOptimization);
  36319. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  36320. var ParticlesOptimization = (function (_super) {
  36321. __extends(ParticlesOptimization, _super);
  36322. function ParticlesOptimization() {
  36323. _super.apply(this, arguments);
  36324. this.apply = function (scene) {
  36325. scene.particlesEnabled = false;
  36326. return true;
  36327. };
  36328. }
  36329. return ParticlesOptimization;
  36330. })(SceneOptimization);
  36331. BABYLON.ParticlesOptimization = ParticlesOptimization;
  36332. var RenderTargetsOptimization = (function (_super) {
  36333. __extends(RenderTargetsOptimization, _super);
  36334. function RenderTargetsOptimization() {
  36335. _super.apply(this, arguments);
  36336. this.apply = function (scene) {
  36337. scene.renderTargetsEnabled = false;
  36338. return true;
  36339. };
  36340. }
  36341. return RenderTargetsOptimization;
  36342. })(SceneOptimization);
  36343. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  36344. var MergeMeshesOptimization = (function (_super) {
  36345. __extends(MergeMeshesOptimization, _super);
  36346. function MergeMeshesOptimization() {
  36347. var _this = this;
  36348. _super.apply(this, arguments);
  36349. this._canBeMerged = function (abstractMesh) {
  36350. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  36351. return false;
  36352. }
  36353. var mesh = abstractMesh;
  36354. if (!mesh.isVisible || !mesh.isEnabled()) {
  36355. return false;
  36356. }
  36357. if (mesh.instances.length > 0) {
  36358. return false;
  36359. }
  36360. if (mesh.skeleton || mesh.hasLODLevels) {
  36361. return false;
  36362. }
  36363. if (mesh.parent) {
  36364. return false;
  36365. }
  36366. return true;
  36367. };
  36368. this.apply = function (scene, updateSelectionTree) {
  36369. var globalPool = scene.meshes.slice(0);
  36370. var globalLength = globalPool.length;
  36371. for (var index = 0; index < globalLength; index++) {
  36372. var currentPool = new Array();
  36373. var current = globalPool[index];
  36374. // Checks
  36375. if (!_this._canBeMerged(current)) {
  36376. continue;
  36377. }
  36378. currentPool.push(current);
  36379. // Find compatible meshes
  36380. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  36381. var otherMesh = globalPool[subIndex];
  36382. if (!_this._canBeMerged(otherMesh)) {
  36383. continue;
  36384. }
  36385. if (otherMesh.material !== current.material) {
  36386. continue;
  36387. }
  36388. if (otherMesh.checkCollisions !== current.checkCollisions) {
  36389. continue;
  36390. }
  36391. currentPool.push(otherMesh);
  36392. globalLength--;
  36393. globalPool.splice(subIndex, 1);
  36394. subIndex--;
  36395. }
  36396. if (currentPool.length < 2) {
  36397. continue;
  36398. }
  36399. // Merge meshes
  36400. BABYLON.Mesh.MergeMeshes(currentPool);
  36401. }
  36402. if (updateSelectionTree != undefined) {
  36403. if (updateSelectionTree) {
  36404. scene.createOrUpdateSelectionOctree();
  36405. }
  36406. }
  36407. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  36408. scene.createOrUpdateSelectionOctree();
  36409. }
  36410. return true;
  36411. };
  36412. }
  36413. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  36414. get: function () {
  36415. return MergeMeshesOptimization._UpdateSelectionTree;
  36416. },
  36417. set: function (value) {
  36418. MergeMeshesOptimization._UpdateSelectionTree = value;
  36419. },
  36420. enumerable: true,
  36421. configurable: true
  36422. });
  36423. MergeMeshesOptimization._UpdateSelectionTree = false;
  36424. return MergeMeshesOptimization;
  36425. })(SceneOptimization);
  36426. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  36427. // Options
  36428. var SceneOptimizerOptions = (function () {
  36429. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  36430. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  36431. if (trackerDuration === void 0) { trackerDuration = 2000; }
  36432. this.targetFrameRate = targetFrameRate;
  36433. this.trackerDuration = trackerDuration;
  36434. this.optimizations = new Array();
  36435. }
  36436. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  36437. var result = new SceneOptimizerOptions(targetFrameRate);
  36438. var priority = 0;
  36439. result.optimizations.push(new MergeMeshesOptimization(priority));
  36440. result.optimizations.push(new ShadowsOptimization(priority));
  36441. result.optimizations.push(new LensFlaresOptimization(priority));
  36442. // Next priority
  36443. priority++;
  36444. result.optimizations.push(new PostProcessesOptimization(priority));
  36445. result.optimizations.push(new ParticlesOptimization(priority));
  36446. // Next priority
  36447. priority++;
  36448. result.optimizations.push(new TextureOptimization(priority, 1024));
  36449. return result;
  36450. };
  36451. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  36452. var result = new SceneOptimizerOptions(targetFrameRate);
  36453. var priority = 0;
  36454. result.optimizations.push(new MergeMeshesOptimization(priority));
  36455. result.optimizations.push(new ShadowsOptimization(priority));
  36456. result.optimizations.push(new LensFlaresOptimization(priority));
  36457. // Next priority
  36458. priority++;
  36459. result.optimizations.push(new PostProcessesOptimization(priority));
  36460. result.optimizations.push(new ParticlesOptimization(priority));
  36461. // Next priority
  36462. priority++;
  36463. result.optimizations.push(new TextureOptimization(priority, 512));
  36464. // Next priority
  36465. priority++;
  36466. result.optimizations.push(new RenderTargetsOptimization(priority));
  36467. // Next priority
  36468. priority++;
  36469. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  36470. return result;
  36471. };
  36472. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  36473. var result = new SceneOptimizerOptions(targetFrameRate);
  36474. var priority = 0;
  36475. result.optimizations.push(new MergeMeshesOptimization(priority));
  36476. result.optimizations.push(new ShadowsOptimization(priority));
  36477. result.optimizations.push(new LensFlaresOptimization(priority));
  36478. // Next priority
  36479. priority++;
  36480. result.optimizations.push(new PostProcessesOptimization(priority));
  36481. result.optimizations.push(new ParticlesOptimization(priority));
  36482. // Next priority
  36483. priority++;
  36484. result.optimizations.push(new TextureOptimization(priority, 256));
  36485. // Next priority
  36486. priority++;
  36487. result.optimizations.push(new RenderTargetsOptimization(priority));
  36488. // Next priority
  36489. priority++;
  36490. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  36491. return result;
  36492. };
  36493. return SceneOptimizerOptions;
  36494. })();
  36495. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  36496. // Scene optimizer tool
  36497. var SceneOptimizer = (function () {
  36498. function SceneOptimizer() {
  36499. }
  36500. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  36501. // TODO: add an epsilon
  36502. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  36503. if (onSuccess) {
  36504. onSuccess();
  36505. }
  36506. return;
  36507. }
  36508. // Apply current level of optimizations
  36509. var allDone = true;
  36510. var noOptimizationApplied = true;
  36511. for (var index = 0; index < options.optimizations.length; index++) {
  36512. var optimization = options.optimizations[index];
  36513. if (optimization.priority === currentPriorityLevel) {
  36514. noOptimizationApplied = false;
  36515. allDone = allDone && optimization.apply(scene);
  36516. }
  36517. }
  36518. // If no optimization was applied, this is a failure :(
  36519. if (noOptimizationApplied) {
  36520. if (onFailure) {
  36521. onFailure();
  36522. }
  36523. return;
  36524. }
  36525. // If all optimizations were done, move to next level
  36526. if (allDone) {
  36527. currentPriorityLevel++;
  36528. }
  36529. // Let's the system running for a specific amount of time before checking FPS
  36530. scene.executeWhenReady(function () {
  36531. setTimeout(function () {
  36532. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  36533. }, options.trackerDuration);
  36534. });
  36535. };
  36536. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  36537. if (!options) {
  36538. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  36539. }
  36540. // Let's the system running for a specific amount of time before checking FPS
  36541. scene.executeWhenReady(function () {
  36542. setTimeout(function () {
  36543. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  36544. }, options.trackerDuration);
  36545. });
  36546. };
  36547. return SceneOptimizer;
  36548. })();
  36549. BABYLON.SceneOptimizer = SceneOptimizer;
  36550. })(BABYLON || (BABYLON = {}));
  36551. var BABYLON;
  36552. (function (BABYLON) {
  36553. var Internals;
  36554. (function (Internals) {
  36555. var MeshLODLevel = (function () {
  36556. function MeshLODLevel(distance, mesh) {
  36557. this.distance = distance;
  36558. this.mesh = mesh;
  36559. }
  36560. return MeshLODLevel;
  36561. })();
  36562. Internals.MeshLODLevel = MeshLODLevel;
  36563. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36564. })(BABYLON || (BABYLON = {}));
  36565. var BABYLON;
  36566. (function (BABYLON) {
  36567. var RawTexture = (function (_super) {
  36568. __extends(RawTexture, _super);
  36569. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  36570. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36571. if (invertY === void 0) { invertY = false; }
  36572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36573. _super.call(this, null, scene, !generateMipMaps, invertY);
  36574. this.format = format;
  36575. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  36576. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36577. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36578. }
  36579. RawTexture.prototype.update = function (data) {
  36580. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  36581. };
  36582. // Statics
  36583. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36585. if (invertY === void 0) { invertY = false; }
  36586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36587. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  36588. };
  36589. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36591. if (invertY === void 0) { invertY = false; }
  36592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36593. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  36594. };
  36595. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36596. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36597. if (invertY === void 0) { invertY = false; }
  36598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36599. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  36600. };
  36601. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36602. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36603. if (invertY === void 0) { invertY = false; }
  36604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36605. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  36606. };
  36607. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36608. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36609. if (invertY === void 0) { invertY = false; }
  36610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36611. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  36612. };
  36613. return RawTexture;
  36614. })(BABYLON.Texture);
  36615. BABYLON.RawTexture = RawTexture;
  36616. })(BABYLON || (BABYLON = {}));
  36617. var BABYLON;
  36618. (function (BABYLON) {
  36619. var IndexedVector2 = (function (_super) {
  36620. __extends(IndexedVector2, _super);
  36621. function IndexedVector2(original, index) {
  36622. _super.call(this, original.x, original.y);
  36623. this.index = index;
  36624. }
  36625. return IndexedVector2;
  36626. })(BABYLON.Vector2);
  36627. var PolygonPoints = (function () {
  36628. function PolygonPoints() {
  36629. this.elements = new Array();
  36630. }
  36631. PolygonPoints.prototype.add = function (originalPoints) {
  36632. var _this = this;
  36633. var result = new Array();
  36634. originalPoints.forEach(function (point) {
  36635. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  36636. var newPoint = new IndexedVector2(point, _this.elements.length);
  36637. result.push(newPoint);
  36638. _this.elements.push(newPoint);
  36639. }
  36640. });
  36641. return result;
  36642. };
  36643. PolygonPoints.prototype.computeBounds = function () {
  36644. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  36645. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  36646. this.elements.forEach(function (point) {
  36647. // x
  36648. if (point.x < lmin.x) {
  36649. lmin.x = point.x;
  36650. }
  36651. else if (point.x > lmax.x) {
  36652. lmax.x = point.x;
  36653. }
  36654. // y
  36655. if (point.y < lmin.y) {
  36656. lmin.y = point.y;
  36657. }
  36658. else if (point.y > lmax.y) {
  36659. lmax.y = point.y;
  36660. }
  36661. });
  36662. return {
  36663. min: lmin,
  36664. max: lmax,
  36665. width: lmax.x - lmin.x,
  36666. height: lmax.y - lmin.y
  36667. };
  36668. };
  36669. return PolygonPoints;
  36670. })();
  36671. var Polygon = (function () {
  36672. function Polygon() {
  36673. }
  36674. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  36675. return [
  36676. new BABYLON.Vector2(xmin, ymin),
  36677. new BABYLON.Vector2(xmax, ymin),
  36678. new BABYLON.Vector2(xmax, ymax),
  36679. new BABYLON.Vector2(xmin, ymax)
  36680. ];
  36681. };
  36682. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  36683. if (cx === void 0) { cx = 0; }
  36684. if (cy === void 0) { cy = 0; }
  36685. if (numberOfSides === void 0) { numberOfSides = 32; }
  36686. var result = new Array();
  36687. var angle = 0;
  36688. var increment = (Math.PI * 2) / numberOfSides;
  36689. for (var i = 0; i < numberOfSides; i++) {
  36690. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  36691. angle -= increment;
  36692. }
  36693. return result;
  36694. };
  36695. Polygon.Parse = function (input) {
  36696. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  36697. var i, result = [];
  36698. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  36699. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  36700. }
  36701. return result;
  36702. };
  36703. Polygon.StartingAt = function (x, y) {
  36704. return BABYLON.Path2.StartingAt(x, y);
  36705. };
  36706. return Polygon;
  36707. })();
  36708. BABYLON.Polygon = Polygon;
  36709. var PolygonMeshBuilder = (function () {
  36710. function PolygonMeshBuilder(name, contours, scene) {
  36711. this._points = new PolygonPoints();
  36712. this._outlinepoints = new PolygonPoints();
  36713. this._holes = [];
  36714. if (!("poly2tri" in window)) {
  36715. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  36716. }
  36717. this._name = name;
  36718. this._scene = scene;
  36719. var points;
  36720. if (contours instanceof BABYLON.Path2) {
  36721. points = contours.getPoints();
  36722. }
  36723. else {
  36724. points = contours;
  36725. }
  36726. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  36727. this._outlinepoints.add(points);
  36728. }
  36729. PolygonMeshBuilder.prototype.addHole = function (hole) {
  36730. this._swctx.addHole(this._points.add(hole));
  36731. var holepoints = new PolygonPoints();
  36732. holepoints.add(hole);
  36733. this._holes.push(holepoints);
  36734. return this;
  36735. };
  36736. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  36737. var _this = this;
  36738. if (updatable === void 0) { updatable = false; }
  36739. var result = new BABYLON.Mesh(this._name, this._scene);
  36740. var normals = [];
  36741. var positions = [];
  36742. var uvs = [];
  36743. var bounds = this._points.computeBounds();
  36744. this._points.elements.forEach(function (p) {
  36745. normals.push(0, 1.0, 0);
  36746. positions.push(p.x, 0, p.y);
  36747. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  36748. });
  36749. var indices = [];
  36750. this._swctx.triangulate();
  36751. this._swctx.getTriangles().forEach(function (triangle) {
  36752. triangle.getPoints().forEach(function (point) {
  36753. indices.push(point.index);
  36754. });
  36755. });
  36756. if (depth > 0) {
  36757. var positionscount = (positions.length / 3); //get the current pointcount
  36758. this._points.elements.forEach(function (p) {
  36759. normals.push(0, -1.0, 0);
  36760. positions.push(p.x, -depth, p.y);
  36761. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  36762. });
  36763. var p1; //we need to change order of point so the triangles are made in the rigth way.
  36764. var p2;
  36765. var poscounter = 0;
  36766. this._swctx.getTriangles().forEach(function (triangle) {
  36767. triangle.getPoints().forEach(function (point) {
  36768. switch (poscounter) {
  36769. case 0:
  36770. p1 = point;
  36771. break;
  36772. case 1:
  36773. p2 = point;
  36774. break;
  36775. case 2:
  36776. indices.push(point.index + positionscount);
  36777. indices.push(p2.index + positionscount);
  36778. indices.push(p1.index + positionscount);
  36779. poscounter = -1;
  36780. break;
  36781. }
  36782. poscounter++;
  36783. //indices.push((<IndexedVector2>point).index + positionscount);
  36784. });
  36785. });
  36786. //Add the sides
  36787. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  36788. this._holes.forEach(function (hole) {
  36789. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  36790. });
  36791. }
  36792. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  36793. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  36794. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  36795. result.setIndices(indices);
  36796. return result;
  36797. };
  36798. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  36799. var StartIndex = positions.length / 3;
  36800. var ulength = 0;
  36801. for (var i = 0; i < points.elements.length; i++) {
  36802. var p = points.elements[i];
  36803. var p1;
  36804. if ((i + 1) > points.elements.length - 1) {
  36805. p1 = points.elements[0];
  36806. }
  36807. else {
  36808. p1 = points.elements[i + 1];
  36809. }
  36810. positions.push(p.x, 0, p.y);
  36811. positions.push(p.x, -depth, p.y);
  36812. positions.push(p1.x, 0, p1.y);
  36813. positions.push(p1.x, -depth, p1.y);
  36814. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  36815. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  36816. var v3 = v2.subtract(v1);
  36817. var v4 = new BABYLON.Vector3(0, 1, 0);
  36818. var vn = BABYLON.Vector3.Cross(v3, v4);
  36819. vn = vn.normalize();
  36820. uvs.push(ulength / bounds.width, 0);
  36821. uvs.push(ulength / bounds.width, 1);
  36822. ulength += v3.length();
  36823. uvs.push((ulength / bounds.width), 0);
  36824. uvs.push((ulength / bounds.width), 1);
  36825. if (!flip) {
  36826. normals.push(-vn.x, -vn.y, -vn.z);
  36827. normals.push(-vn.x, -vn.y, -vn.z);
  36828. normals.push(-vn.x, -vn.y, -vn.z);
  36829. normals.push(-vn.x, -vn.y, -vn.z);
  36830. indices.push(StartIndex);
  36831. indices.push(StartIndex + 1);
  36832. indices.push(StartIndex + 2);
  36833. indices.push(StartIndex + 1);
  36834. indices.push(StartIndex + 3);
  36835. indices.push(StartIndex + 2);
  36836. }
  36837. else {
  36838. normals.push(vn.x, vn.y, vn.z);
  36839. normals.push(vn.x, vn.y, vn.z);
  36840. normals.push(vn.x, vn.y, vn.z);
  36841. normals.push(vn.x, vn.y, vn.z);
  36842. indices.push(StartIndex);
  36843. indices.push(StartIndex + 2);
  36844. indices.push(StartIndex + 1);
  36845. indices.push(StartIndex + 1);
  36846. indices.push(StartIndex + 2);
  36847. indices.push(StartIndex + 3);
  36848. }
  36849. StartIndex += 4;
  36850. }
  36851. ;
  36852. };
  36853. return PolygonMeshBuilder;
  36854. })();
  36855. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  36856. })(BABYLON || (BABYLON = {}));
  36857. var BABYLON;
  36858. (function (BABYLON) {
  36859. var Octree = (function () {
  36860. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  36861. if (maxDepth === void 0) { maxDepth = 2; }
  36862. this.maxDepth = maxDepth;
  36863. this.dynamicContent = new Array();
  36864. this._maxBlockCapacity = maxBlockCapacity || 64;
  36865. this._selectionContent = new BABYLON.SmartArray(1024);
  36866. this._creationFunc = creationFunc;
  36867. }
  36868. // Methods
  36869. Octree.prototype.update = function (worldMin, worldMax, entries) {
  36870. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  36871. };
  36872. Octree.prototype.addMesh = function (entry) {
  36873. for (var index = 0; index < this.blocks.length; index++) {
  36874. var block = this.blocks[index];
  36875. block.addEntry(entry);
  36876. }
  36877. };
  36878. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  36879. this._selectionContent.reset();
  36880. for (var index = 0; index < this.blocks.length; index++) {
  36881. var block = this.blocks[index];
  36882. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  36883. }
  36884. if (allowDuplicate) {
  36885. this._selectionContent.concat(this.dynamicContent);
  36886. }
  36887. else {
  36888. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36889. }
  36890. return this._selectionContent;
  36891. };
  36892. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  36893. this._selectionContent.reset();
  36894. for (var index = 0; index < this.blocks.length; index++) {
  36895. var block = this.blocks[index];
  36896. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  36897. }
  36898. if (allowDuplicate) {
  36899. this._selectionContent.concat(this.dynamicContent);
  36900. }
  36901. else {
  36902. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36903. }
  36904. return this._selectionContent;
  36905. };
  36906. Octree.prototype.intersectsRay = function (ray) {
  36907. this._selectionContent.reset();
  36908. for (var index = 0; index < this.blocks.length; index++) {
  36909. var block = this.blocks[index];
  36910. block.intersectsRay(ray, this._selectionContent);
  36911. }
  36912. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36913. return this._selectionContent;
  36914. };
  36915. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  36916. target.blocks = new Array();
  36917. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  36918. // Segmenting space
  36919. for (var x = 0; x < 2; x++) {
  36920. for (var y = 0; y < 2; y++) {
  36921. for (var z = 0; z < 2; z++) {
  36922. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  36923. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  36924. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  36925. block.addEntries(entries);
  36926. target.blocks.push(block);
  36927. }
  36928. }
  36929. }
  36930. };
  36931. Octree.CreationFuncForMeshes = function (entry, block) {
  36932. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  36933. block.entries.push(entry);
  36934. }
  36935. };
  36936. Octree.CreationFuncForSubMeshes = function (entry, block) {
  36937. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  36938. block.entries.push(entry);
  36939. }
  36940. };
  36941. return Octree;
  36942. })();
  36943. BABYLON.Octree = Octree;
  36944. })(BABYLON || (BABYLON = {}));
  36945. var BABYLON;
  36946. (function (BABYLON) {
  36947. var OctreeBlock = (function () {
  36948. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  36949. this.entries = new Array();
  36950. this._boundingVectors = new Array();
  36951. this._capacity = capacity;
  36952. this._depth = depth;
  36953. this._maxDepth = maxDepth;
  36954. this._creationFunc = creationFunc;
  36955. this._minPoint = minPoint;
  36956. this._maxPoint = maxPoint;
  36957. this._boundingVectors.push(minPoint.clone());
  36958. this._boundingVectors.push(maxPoint.clone());
  36959. this._boundingVectors.push(minPoint.clone());
  36960. this._boundingVectors[2].x = maxPoint.x;
  36961. this._boundingVectors.push(minPoint.clone());
  36962. this._boundingVectors[3].y = maxPoint.y;
  36963. this._boundingVectors.push(minPoint.clone());
  36964. this._boundingVectors[4].z = maxPoint.z;
  36965. this._boundingVectors.push(maxPoint.clone());
  36966. this._boundingVectors[5].z = minPoint.z;
  36967. this._boundingVectors.push(maxPoint.clone());
  36968. this._boundingVectors[6].x = minPoint.x;
  36969. this._boundingVectors.push(maxPoint.clone());
  36970. this._boundingVectors[7].y = minPoint.y;
  36971. }
  36972. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  36973. // Property
  36974. get: function () {
  36975. return this._capacity;
  36976. },
  36977. enumerable: true,
  36978. configurable: true
  36979. });
  36980. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  36981. get: function () {
  36982. return this._minPoint;
  36983. },
  36984. enumerable: true,
  36985. configurable: true
  36986. });
  36987. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  36988. get: function () {
  36989. return this._maxPoint;
  36990. },
  36991. enumerable: true,
  36992. configurable: true
  36993. });
  36994. // Methods
  36995. OctreeBlock.prototype.addEntry = function (entry) {
  36996. if (this.blocks) {
  36997. for (var index = 0; index < this.blocks.length; index++) {
  36998. var block = this.blocks[index];
  36999. block.addEntry(entry);
  37000. }
  37001. return;
  37002. }
  37003. this._creationFunc(entry, this);
  37004. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  37005. this.createInnerBlocks();
  37006. }
  37007. };
  37008. OctreeBlock.prototype.addEntries = function (entries) {
  37009. for (var index = 0; index < entries.length; index++) {
  37010. var mesh = entries[index];
  37011. this.addEntry(mesh);
  37012. }
  37013. };
  37014. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  37015. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  37016. if (this.blocks) {
  37017. for (var index = 0; index < this.blocks.length; index++) {
  37018. var block = this.blocks[index];
  37019. block.select(frustumPlanes, selection, allowDuplicate);
  37020. }
  37021. return;
  37022. }
  37023. if (allowDuplicate) {
  37024. selection.concat(this.entries);
  37025. }
  37026. else {
  37027. selection.concatWithNoDuplicate(this.entries);
  37028. }
  37029. }
  37030. };
  37031. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  37032. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  37033. if (this.blocks) {
  37034. for (var index = 0; index < this.blocks.length; index++) {
  37035. var block = this.blocks[index];
  37036. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  37037. }
  37038. return;
  37039. }
  37040. if (allowDuplicate) {
  37041. selection.concat(this.entries);
  37042. }
  37043. else {
  37044. selection.concatWithNoDuplicate(this.entries);
  37045. }
  37046. }
  37047. };
  37048. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  37049. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  37050. if (this.blocks) {
  37051. for (var index = 0; index < this.blocks.length; index++) {
  37052. var block = this.blocks[index];
  37053. block.intersectsRay(ray, selection);
  37054. }
  37055. return;
  37056. }
  37057. selection.concatWithNoDuplicate(this.entries);
  37058. }
  37059. };
  37060. OctreeBlock.prototype.createInnerBlocks = function () {
  37061. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  37062. };
  37063. return OctreeBlock;
  37064. })();
  37065. BABYLON.OctreeBlock = OctreeBlock;
  37066. })(BABYLON || (BABYLON = {}));
  37067. var BABYLON;
  37068. (function (BABYLON) {
  37069. var BlurPostProcess = (function (_super) {
  37070. __extends(BlurPostProcess, _super);
  37071. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  37072. var _this = this;
  37073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37074. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  37075. this.direction = direction;
  37076. this.blurWidth = blurWidth;
  37077. this.onApply = function (effect) {
  37078. effect.setFloat2("screenSize", _this.width, _this.height);
  37079. effect.setVector2("direction", _this.direction);
  37080. effect.setFloat("blurWidth", _this.blurWidth);
  37081. };
  37082. }
  37083. return BlurPostProcess;
  37084. })(BABYLON.PostProcess);
  37085. BABYLON.BlurPostProcess = BlurPostProcess;
  37086. })(BABYLON || (BABYLON = {}));
  37087. var BABYLON;
  37088. (function (BABYLON) {
  37089. var RefractionPostProcess = (function (_super) {
  37090. __extends(RefractionPostProcess, _super);
  37091. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  37092. var _this = this;
  37093. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  37094. this.color = color;
  37095. this.depth = depth;
  37096. this.colorLevel = colorLevel;
  37097. this.onActivate = function (cam) {
  37098. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  37099. };
  37100. this.onApply = function (effect) {
  37101. effect.setColor3("baseColor", _this.color);
  37102. effect.setFloat("depth", _this.depth);
  37103. effect.setFloat("colorLevel", _this.colorLevel);
  37104. effect.setTexture("refractionSampler", _this._refRexture);
  37105. };
  37106. }
  37107. // Methods
  37108. RefractionPostProcess.prototype.dispose = function (camera) {
  37109. if (this._refRexture) {
  37110. this._refRexture.dispose();
  37111. }
  37112. _super.prototype.dispose.call(this, camera);
  37113. };
  37114. return RefractionPostProcess;
  37115. })(BABYLON.PostProcess);
  37116. BABYLON.RefractionPostProcess = RefractionPostProcess;
  37117. })(BABYLON || (BABYLON = {}));
  37118. var BABYLON;
  37119. (function (BABYLON) {
  37120. var BlackAndWhitePostProcess = (function (_super) {
  37121. __extends(BlackAndWhitePostProcess, _super);
  37122. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37123. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  37124. }
  37125. return BlackAndWhitePostProcess;
  37126. })(BABYLON.PostProcess);
  37127. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  37128. })(BABYLON || (BABYLON = {}));
  37129. var BABYLON;
  37130. (function (BABYLON) {
  37131. var ConvolutionPostProcess = (function (_super) {
  37132. __extends(ConvolutionPostProcess, _super);
  37133. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  37134. var _this = this;
  37135. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  37136. this.kernel = kernel;
  37137. this.onApply = function (effect) {
  37138. effect.setFloat2("screenSize", _this.width, _this.height);
  37139. effect.setArray("kernel", _this.kernel);
  37140. };
  37141. }
  37142. // Statics
  37143. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  37144. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  37145. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  37146. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  37147. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  37148. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  37149. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  37150. return ConvolutionPostProcess;
  37151. })(BABYLON.PostProcess);
  37152. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  37153. })(BABYLON || (BABYLON = {}));
  37154. var BABYLON;
  37155. (function (BABYLON) {
  37156. var FilterPostProcess = (function (_super) {
  37157. __extends(FilterPostProcess, _super);
  37158. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  37159. var _this = this;
  37160. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  37161. this.kernelMatrix = kernelMatrix;
  37162. this.onApply = function (effect) {
  37163. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  37164. };
  37165. }
  37166. return FilterPostProcess;
  37167. })(BABYLON.PostProcess);
  37168. BABYLON.FilterPostProcess = FilterPostProcess;
  37169. })(BABYLON || (BABYLON = {}));
  37170. var BABYLON;
  37171. (function (BABYLON) {
  37172. var FxaaPostProcess = (function (_super) {
  37173. __extends(FxaaPostProcess, _super);
  37174. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37175. var _this = this;
  37176. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  37177. this.onSizeChanged = function () {
  37178. _this.texelWidth = 1.0 / _this.width;
  37179. _this.texelHeight = 1.0 / _this.height;
  37180. };
  37181. this.onApply = function (effect) {
  37182. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  37183. };
  37184. }
  37185. return FxaaPostProcess;
  37186. })(BABYLON.PostProcess);
  37187. BABYLON.FxaaPostProcess = FxaaPostProcess;
  37188. })(BABYLON || (BABYLON = {}));
  37189. var BABYLON;
  37190. (function (BABYLON) {
  37191. var StereoscopicInterlacePostProcess = (function (_super) {
  37192. __extends(StereoscopicInterlacePostProcess, _super);
  37193. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  37194. var _this = this;
  37195. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  37196. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  37197. this.onSizeChanged = function () {
  37198. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  37199. };
  37200. this.onApply = function (effect) {
  37201. effect.setTextureFromPostProcess("camASampler", postProcessA);
  37202. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  37203. };
  37204. }
  37205. return StereoscopicInterlacePostProcess;
  37206. })(BABYLON.PostProcess);
  37207. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  37208. })(BABYLON || (BABYLON = {}));
  37209. var BABYLON;
  37210. (function (BABYLON) {
  37211. var LensFlare = (function () {
  37212. function LensFlare(size, position, color, imgUrl, system) {
  37213. this.size = size;
  37214. this.position = position;
  37215. this.dispose = function () {
  37216. if (this.texture) {
  37217. this.texture.dispose();
  37218. }
  37219. // Remove from scene
  37220. var index = this._system.lensFlares.indexOf(this);
  37221. this._system.lensFlares.splice(index, 1);
  37222. };
  37223. this.color = color || new BABYLON.Color3(1, 1, 1);
  37224. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  37225. this._system = system;
  37226. system.lensFlares.push(this);
  37227. }
  37228. return LensFlare;
  37229. })();
  37230. BABYLON.LensFlare = LensFlare;
  37231. })(BABYLON || (BABYLON = {}));
  37232. var BABYLON;
  37233. (function (BABYLON) {
  37234. var LensFlareSystem = (function () {
  37235. function LensFlareSystem(name, emitter, scene) {
  37236. this.name = name;
  37237. this.lensFlares = new Array();
  37238. this.borderLimit = 300;
  37239. this.layerMask = 0x0FFFFFFF;
  37240. this._vertexDeclaration = [2];
  37241. this._vertexStrideSize = 2 * 4;
  37242. this._isEnabled = true;
  37243. this._scene = scene;
  37244. this._emitter = emitter;
  37245. scene.lensFlareSystems.push(this);
  37246. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  37247. // VBO
  37248. var vertices = [];
  37249. vertices.push(1, 1);
  37250. vertices.push(-1, 1);
  37251. vertices.push(-1, -1);
  37252. vertices.push(1, -1);
  37253. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  37254. // Indices
  37255. var indices = [];
  37256. indices.push(0);
  37257. indices.push(1);
  37258. indices.push(2);
  37259. indices.push(0);
  37260. indices.push(2);
  37261. indices.push(3);
  37262. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  37263. // Effects
  37264. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  37265. }
  37266. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  37267. get: function () {
  37268. return this._isEnabled;
  37269. },
  37270. set: function (value) {
  37271. this._isEnabled = value;
  37272. },
  37273. enumerable: true,
  37274. configurable: true
  37275. });
  37276. LensFlareSystem.prototype.getScene = function () {
  37277. return this._scene;
  37278. };
  37279. LensFlareSystem.prototype.getEmitter = function () {
  37280. return this._emitter;
  37281. };
  37282. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  37283. this._emitter = newEmitter;
  37284. };
  37285. LensFlareSystem.prototype.getEmitterPosition = function () {
  37286. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  37287. };
  37288. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  37289. var position = this.getEmitterPosition();
  37290. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  37291. this._positionX = position.x;
  37292. this._positionY = position.y;
  37293. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  37294. if (position.z > 0) {
  37295. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  37296. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  37297. return true;
  37298. }
  37299. }
  37300. return false;
  37301. };
  37302. LensFlareSystem.prototype._isVisible = function () {
  37303. if (!this._isEnabled) {
  37304. return false;
  37305. }
  37306. var emitterPosition = this.getEmitterPosition();
  37307. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  37308. var distance = direction.length();
  37309. direction.normalize();
  37310. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  37311. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  37312. return !pickInfo.hit || pickInfo.distance > distance;
  37313. };
  37314. LensFlareSystem.prototype.render = function () {
  37315. if (!this._effect.isReady())
  37316. return false;
  37317. var engine = this._scene.getEngine();
  37318. var viewport = this._scene.activeCamera.viewport;
  37319. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  37320. // Position
  37321. if (!this.computeEffectivePosition(globalViewport)) {
  37322. return false;
  37323. }
  37324. // Visibility
  37325. if (!this._isVisible()) {
  37326. return false;
  37327. }
  37328. // Intensity
  37329. var awayX;
  37330. var awayY;
  37331. if (this._positionX < this.borderLimit + globalViewport.x) {
  37332. awayX = this.borderLimit + globalViewport.x - this._positionX;
  37333. }
  37334. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  37335. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  37336. }
  37337. else {
  37338. awayX = 0;
  37339. }
  37340. if (this._positionY < this.borderLimit + globalViewport.y) {
  37341. awayY = this.borderLimit + globalViewport.y - this._positionY;
  37342. }
  37343. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  37344. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  37345. }
  37346. else {
  37347. awayY = 0;
  37348. }
  37349. var away = (awayX > awayY) ? awayX : awayY;
  37350. if (away > this.borderLimit) {
  37351. away = this.borderLimit;
  37352. }
  37353. var intensity = 1.0 - (away / this.borderLimit);
  37354. if (intensity < 0) {
  37355. return false;
  37356. }
  37357. if (intensity > 1.0) {
  37358. intensity = 1.0;
  37359. }
  37360. // Position
  37361. var centerX = globalViewport.x + globalViewport.width / 2;
  37362. var centerY = globalViewport.y + globalViewport.height / 2;
  37363. var distX = centerX - this._positionX;
  37364. var distY = centerY - this._positionY;
  37365. // Effects
  37366. engine.enableEffect(this._effect);
  37367. engine.setState(false);
  37368. engine.setDepthBuffer(false);
  37369. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  37370. // VBOs
  37371. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  37372. // Flares
  37373. for (var index = 0; index < this.lensFlares.length; index++) {
  37374. var flare = this.lensFlares[index];
  37375. var x = centerX - (distX * flare.position);
  37376. var y = centerY - (distY * flare.position);
  37377. var cw = flare.size;
  37378. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  37379. var cx = 2 * (x / globalViewport.width) - 1.0;
  37380. var cy = 1.0 - 2 * (y / globalViewport.height);
  37381. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  37382. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  37383. // Texture
  37384. this._effect.setTexture("textureSampler", flare.texture);
  37385. // Color
  37386. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  37387. // Draw order
  37388. engine.draw(true, 0, 6);
  37389. }
  37390. engine.setDepthBuffer(true);
  37391. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37392. return true;
  37393. };
  37394. LensFlareSystem.prototype.dispose = function () {
  37395. if (this._vertexBuffer) {
  37396. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  37397. this._vertexBuffer = null;
  37398. }
  37399. if (this._indexBuffer) {
  37400. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37401. this._indexBuffer = null;
  37402. }
  37403. while (this.lensFlares.length) {
  37404. this.lensFlares[0].dispose();
  37405. }
  37406. // Remove from scene
  37407. var index = this._scene.lensFlareSystems.indexOf(this);
  37408. this._scene.lensFlareSystems.splice(index, 1);
  37409. };
  37410. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  37411. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  37412. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  37413. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  37414. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  37415. var parsedFlare = parsedLensFlareSystem.flares[index];
  37416. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  37417. }
  37418. return lensFlareSystem;
  37419. };
  37420. LensFlareSystem.prototype.serialize = function () {
  37421. var serializationObject = {};
  37422. serializationObject.emitterId = this.getEmitter().id;
  37423. serializationObject.borderLimit = this.borderLimit;
  37424. serializationObject.flares = [];
  37425. for (var index = 0; index < this.lensFlares.length; index++) {
  37426. var flare = this.lensFlares[index];
  37427. serializationObject.flares.push({
  37428. size: flare.size,
  37429. position: flare.position,
  37430. color: flare.color.asArray(),
  37431. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  37432. });
  37433. }
  37434. return serializationObject;
  37435. };
  37436. return LensFlareSystem;
  37437. })();
  37438. BABYLON.LensFlareSystem = LensFlareSystem;
  37439. })(BABYLON || (BABYLON = {}));
  37440. var BABYLON;
  37441. (function (BABYLON) {
  37442. // We're mainly based on the logic defined into the FreeCamera code
  37443. var DeviceOrientationCamera = (function (_super) {
  37444. __extends(DeviceOrientationCamera, _super);
  37445. //-- end properties for backward compatibility for inputs
  37446. function DeviceOrientationCamera(name, position, scene) {
  37447. _super.call(this, name, position, scene);
  37448. this.inputs.addDeviceOrientation();
  37449. }
  37450. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  37451. //-- Begin properties for backward compatibility for inputs
  37452. get: function () {
  37453. var gamepad = this.inputs.attached["deviceOrientation"];
  37454. if (gamepad)
  37455. return gamepad.angularSensibility;
  37456. },
  37457. set: function (value) {
  37458. var gamepad = this.inputs.attached["deviceOrientation"];
  37459. if (gamepad)
  37460. gamepad.angularSensibility = value;
  37461. },
  37462. enumerable: true,
  37463. configurable: true
  37464. });
  37465. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  37466. get: function () {
  37467. var gamepad = this.inputs.attached["deviceOrientation"];
  37468. if (gamepad)
  37469. return gamepad.moveSensibility;
  37470. },
  37471. set: function (value) {
  37472. var gamepad = this.inputs.attached["deviceOrientation"];
  37473. if (gamepad)
  37474. gamepad.moveSensibility = value;
  37475. },
  37476. enumerable: true,
  37477. configurable: true
  37478. });
  37479. DeviceOrientationCamera.prototype.getTypeName = function () {
  37480. return "DeviceOrientationCamera";
  37481. };
  37482. return DeviceOrientationCamera;
  37483. })(BABYLON.FreeCamera);
  37484. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  37485. })(BABYLON || (BABYLON = {}));
  37486. var BABYLON;
  37487. (function (BABYLON) {
  37488. // We're mainly based on the logic defined into the FreeCamera code
  37489. var UniversalCamera = (function (_super) {
  37490. __extends(UniversalCamera, _super);
  37491. //-- end properties for backward compatibility for inputs
  37492. function UniversalCamera(name, position, scene) {
  37493. _super.call(this, name, position, scene);
  37494. this.inputs.addGamepad();
  37495. }
  37496. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  37497. //-- Begin properties for backward compatibility for inputs
  37498. get: function () {
  37499. var gamepad = this.inputs.attached["gamepad"];
  37500. if (gamepad)
  37501. return gamepad.gamepadAngularSensibility;
  37502. },
  37503. set: function (value) {
  37504. var gamepad = this.inputs.attached["gamepad"];
  37505. if (gamepad)
  37506. gamepad.gamepadAngularSensibility = value;
  37507. },
  37508. enumerable: true,
  37509. configurable: true
  37510. });
  37511. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  37512. get: function () {
  37513. var gamepad = this.inputs.attached["gamepad"];
  37514. if (gamepad)
  37515. return gamepad.gamepadMoveSensibility;
  37516. },
  37517. set: function (value) {
  37518. var gamepad = this.inputs.attached["gamepad"];
  37519. if (gamepad)
  37520. gamepad.gamepadMoveSensibility = value;
  37521. },
  37522. enumerable: true,
  37523. configurable: true
  37524. });
  37525. UniversalCamera.prototype.getTypeName = function () {
  37526. return "UniversalCamera";
  37527. };
  37528. return UniversalCamera;
  37529. })(BABYLON.TouchCamera);
  37530. BABYLON.UniversalCamera = UniversalCamera;
  37531. })(BABYLON || (BABYLON = {}));
  37532. var BABYLON;
  37533. (function (BABYLON) {
  37534. var Gamepads = (function () {
  37535. function Gamepads(ongamedpadconnected) {
  37536. var _this = this;
  37537. this.babylonGamepads = [];
  37538. this.oneGamepadConnected = false;
  37539. this.isMonitoring = false;
  37540. this.gamepadEventSupported = 'GamepadEvent' in window;
  37541. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37542. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37543. this._callbackGamepadConnected = ongamedpadconnected;
  37544. if (this.gamepadSupportAvailable) {
  37545. // Checking if the gamepad connected event is supported (like in Firefox)
  37546. if (this.gamepadEventSupported) {
  37547. this._onGamepadConnectedEvent = function (evt) {
  37548. _this._onGamepadConnected(evt);
  37549. };
  37550. this._onGamepadDisonnectedEvent = function (evt) {
  37551. _this._onGamepadDisconnected(evt);
  37552. };
  37553. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  37554. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  37555. }
  37556. else {
  37557. this._startMonitoringGamepads();
  37558. }
  37559. }
  37560. }
  37561. Gamepads.prototype.dispose = function () {
  37562. if (Gamepads.gamepadDOMInfo) {
  37563. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37564. }
  37565. if (this._onGamepadConnectedEvent) {
  37566. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  37567. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  37568. this._onGamepadConnectedEvent = null;
  37569. this._onGamepadDisonnectedEvent = null;
  37570. }
  37571. };
  37572. Gamepads.prototype._onGamepadConnected = function (evt) {
  37573. var newGamepad = this._addNewGamepad(evt.gamepad);
  37574. if (this._callbackGamepadConnected)
  37575. this._callbackGamepadConnected(newGamepad);
  37576. this._startMonitoringGamepads();
  37577. };
  37578. Gamepads.prototype._addNewGamepad = function (gamepad) {
  37579. if (!this.oneGamepadConnected) {
  37580. this.oneGamepadConnected = true;
  37581. if (Gamepads.gamepadDOMInfo) {
  37582. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37583. Gamepads.gamepadDOMInfo = null;
  37584. }
  37585. }
  37586. var newGamepad;
  37587. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  37588. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  37589. }
  37590. else {
  37591. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  37592. }
  37593. this.babylonGamepads.push(newGamepad);
  37594. return newGamepad;
  37595. };
  37596. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  37597. // Remove the gamepad from the list of gamepads to monitor.
  37598. for (var i in this.babylonGamepads) {
  37599. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  37600. this.babylonGamepads.splice(+i, 1);
  37601. break;
  37602. }
  37603. }
  37604. // If no gamepads are left, stop the polling loop.
  37605. if (this.babylonGamepads.length == 0) {
  37606. this._stopMonitoringGamepads();
  37607. }
  37608. };
  37609. Gamepads.prototype._startMonitoringGamepads = function () {
  37610. if (!this.isMonitoring) {
  37611. this.isMonitoring = true;
  37612. this._checkGamepadsStatus();
  37613. }
  37614. };
  37615. Gamepads.prototype._stopMonitoringGamepads = function () {
  37616. this.isMonitoring = false;
  37617. };
  37618. Gamepads.prototype._checkGamepadsStatus = function () {
  37619. var _this = this;
  37620. // updating gamepad objects
  37621. this._updateGamepadObjects();
  37622. for (var i in this.babylonGamepads) {
  37623. this.babylonGamepads[i].update();
  37624. }
  37625. if (this.isMonitoring) {
  37626. if (window.requestAnimationFrame) {
  37627. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37628. }
  37629. else if (window.mozRequestAnimationFrame) {
  37630. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37631. }
  37632. else if (window.webkitRequestAnimationFrame) {
  37633. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37634. }
  37635. }
  37636. };
  37637. // This function is called only on Chrome, which does not yet support
  37638. // connection/disconnection events, but requires you to monitor
  37639. // an array for changes.
  37640. Gamepads.prototype._updateGamepadObjects = function () {
  37641. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  37642. for (var i = 0; i < gamepads.length; i++) {
  37643. if (gamepads[i]) {
  37644. if (!(gamepads[i].index in this.babylonGamepads)) {
  37645. var newGamepad = this._addNewGamepad(gamepads[i]);
  37646. if (this._callbackGamepadConnected) {
  37647. this._callbackGamepadConnected(newGamepad);
  37648. }
  37649. }
  37650. else {
  37651. this.babylonGamepads[i].browserGamepad = gamepads[i];
  37652. }
  37653. }
  37654. }
  37655. };
  37656. return Gamepads;
  37657. })();
  37658. BABYLON.Gamepads = Gamepads;
  37659. var StickValues = (function () {
  37660. function StickValues(x, y) {
  37661. this.x = x;
  37662. this.y = y;
  37663. }
  37664. return StickValues;
  37665. })();
  37666. BABYLON.StickValues = StickValues;
  37667. var Gamepad = (function () {
  37668. function Gamepad(id, index, browserGamepad) {
  37669. this.id = id;
  37670. this.index = index;
  37671. this.browserGamepad = browserGamepad;
  37672. if (this.browserGamepad.axes.length >= 2) {
  37673. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37674. }
  37675. if (this.browserGamepad.axes.length >= 4) {
  37676. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37677. }
  37678. }
  37679. Gamepad.prototype.onleftstickchanged = function (callback) {
  37680. this._onleftstickchanged = callback;
  37681. };
  37682. Gamepad.prototype.onrightstickchanged = function (callback) {
  37683. this._onrightstickchanged = callback;
  37684. };
  37685. Object.defineProperty(Gamepad.prototype, "leftStick", {
  37686. get: function () {
  37687. return this._leftStick;
  37688. },
  37689. set: function (newValues) {
  37690. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  37691. this._onleftstickchanged(newValues);
  37692. }
  37693. this._leftStick = newValues;
  37694. },
  37695. enumerable: true,
  37696. configurable: true
  37697. });
  37698. Object.defineProperty(Gamepad.prototype, "rightStick", {
  37699. get: function () {
  37700. return this._rightStick;
  37701. },
  37702. set: function (newValues) {
  37703. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  37704. this._onrightstickchanged(newValues);
  37705. }
  37706. this._rightStick = newValues;
  37707. },
  37708. enumerable: true,
  37709. configurable: true
  37710. });
  37711. Gamepad.prototype.update = function () {
  37712. if (this._leftStick) {
  37713. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37714. }
  37715. if (this._rightStick) {
  37716. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37717. }
  37718. };
  37719. return Gamepad;
  37720. })();
  37721. BABYLON.Gamepad = Gamepad;
  37722. var GenericPad = (function (_super) {
  37723. __extends(GenericPad, _super);
  37724. function GenericPad(id, index, gamepad) {
  37725. _super.call(this, id, index, gamepad);
  37726. this.id = id;
  37727. this.index = index;
  37728. this.gamepad = gamepad;
  37729. this._buttons = new Array(gamepad.buttons.length);
  37730. }
  37731. GenericPad.prototype.onbuttondown = function (callback) {
  37732. this._onbuttondown = callback;
  37733. };
  37734. GenericPad.prototype.onbuttonup = function (callback) {
  37735. this._onbuttonup = callback;
  37736. };
  37737. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  37738. if (newValue !== currentValue) {
  37739. if (this._onbuttondown && newValue === 1) {
  37740. this._onbuttondown(buttonIndex);
  37741. }
  37742. if (this._onbuttonup && newValue === 0) {
  37743. this._onbuttonup(buttonIndex);
  37744. }
  37745. }
  37746. return newValue;
  37747. };
  37748. GenericPad.prototype.update = function () {
  37749. _super.prototype.update.call(this);
  37750. for (var index = 0; index < this._buttons.length; index++) {
  37751. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  37752. }
  37753. };
  37754. return GenericPad;
  37755. })(Gamepad);
  37756. BABYLON.GenericPad = GenericPad;
  37757. (function (Xbox360Button) {
  37758. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  37759. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  37760. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  37761. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  37762. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  37763. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  37764. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  37765. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  37766. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  37767. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  37768. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  37769. var Xbox360Button = BABYLON.Xbox360Button;
  37770. (function (Xbox360Dpad) {
  37771. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  37772. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  37773. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  37774. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  37775. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  37776. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  37777. var Xbox360Pad = (function (_super) {
  37778. __extends(Xbox360Pad, _super);
  37779. function Xbox360Pad() {
  37780. _super.apply(this, arguments);
  37781. this._leftTrigger = 0;
  37782. this._rightTrigger = 0;
  37783. this._buttonA = 0;
  37784. this._buttonB = 0;
  37785. this._buttonX = 0;
  37786. this._buttonY = 0;
  37787. this._buttonBack = 0;
  37788. this._buttonStart = 0;
  37789. this._buttonLB = 0;
  37790. this._buttonRB = 0;
  37791. this._buttonLeftStick = 0;
  37792. this._buttonRightStick = 0;
  37793. this._dPadUp = 0;
  37794. this._dPadDown = 0;
  37795. this._dPadLeft = 0;
  37796. this._dPadRight = 0;
  37797. }
  37798. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  37799. this._onlefttriggerchanged = callback;
  37800. };
  37801. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  37802. this._onrighttriggerchanged = callback;
  37803. };
  37804. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  37805. get: function () {
  37806. return this._leftTrigger;
  37807. },
  37808. set: function (newValue) {
  37809. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  37810. this._onlefttriggerchanged(newValue);
  37811. }
  37812. this._leftTrigger = newValue;
  37813. },
  37814. enumerable: true,
  37815. configurable: true
  37816. });
  37817. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  37818. get: function () {
  37819. return this._rightTrigger;
  37820. },
  37821. set: function (newValue) {
  37822. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  37823. this._onrighttriggerchanged(newValue);
  37824. }
  37825. this._rightTrigger = newValue;
  37826. },
  37827. enumerable: true,
  37828. configurable: true
  37829. });
  37830. Xbox360Pad.prototype.onbuttondown = function (callback) {
  37831. this._onbuttondown = callback;
  37832. };
  37833. Xbox360Pad.prototype.onbuttonup = function (callback) {
  37834. this._onbuttonup = callback;
  37835. };
  37836. Xbox360Pad.prototype.ondpaddown = function (callback) {
  37837. this._ondpaddown = callback;
  37838. };
  37839. Xbox360Pad.prototype.ondpadup = function (callback) {
  37840. this._ondpadup = callback;
  37841. };
  37842. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  37843. if (newValue !== currentValue) {
  37844. if (this._onbuttondown && newValue === 1) {
  37845. this._onbuttondown(buttonType);
  37846. }
  37847. if (this._onbuttonup && newValue === 0) {
  37848. this._onbuttonup(buttonType);
  37849. }
  37850. }
  37851. return newValue;
  37852. };
  37853. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  37854. if (newValue !== currentValue) {
  37855. if (this._ondpaddown && newValue === 1) {
  37856. this._ondpaddown(buttonType);
  37857. }
  37858. if (this._ondpadup && newValue === 0) {
  37859. this._ondpadup(buttonType);
  37860. }
  37861. }
  37862. return newValue;
  37863. };
  37864. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  37865. get: function () {
  37866. return this._buttonA;
  37867. },
  37868. set: function (value) {
  37869. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  37870. },
  37871. enumerable: true,
  37872. configurable: true
  37873. });
  37874. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  37875. get: function () {
  37876. return this._buttonB;
  37877. },
  37878. set: function (value) {
  37879. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  37880. },
  37881. enumerable: true,
  37882. configurable: true
  37883. });
  37884. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  37885. get: function () {
  37886. return this._buttonX;
  37887. },
  37888. set: function (value) {
  37889. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  37890. },
  37891. enumerable: true,
  37892. configurable: true
  37893. });
  37894. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  37895. get: function () {
  37896. return this._buttonY;
  37897. },
  37898. set: function (value) {
  37899. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  37900. },
  37901. enumerable: true,
  37902. configurable: true
  37903. });
  37904. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  37905. get: function () {
  37906. return this._buttonStart;
  37907. },
  37908. set: function (value) {
  37909. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  37910. },
  37911. enumerable: true,
  37912. configurable: true
  37913. });
  37914. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  37915. get: function () {
  37916. return this._buttonBack;
  37917. },
  37918. set: function (value) {
  37919. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  37920. },
  37921. enumerable: true,
  37922. configurable: true
  37923. });
  37924. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  37925. get: function () {
  37926. return this._buttonLB;
  37927. },
  37928. set: function (value) {
  37929. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  37930. },
  37931. enumerable: true,
  37932. configurable: true
  37933. });
  37934. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  37935. get: function () {
  37936. return this._buttonRB;
  37937. },
  37938. set: function (value) {
  37939. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  37940. },
  37941. enumerable: true,
  37942. configurable: true
  37943. });
  37944. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  37945. get: function () {
  37946. return this._buttonLeftStick;
  37947. },
  37948. set: function (value) {
  37949. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  37950. },
  37951. enumerable: true,
  37952. configurable: true
  37953. });
  37954. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  37955. get: function () {
  37956. return this._buttonRightStick;
  37957. },
  37958. set: function (value) {
  37959. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  37960. },
  37961. enumerable: true,
  37962. configurable: true
  37963. });
  37964. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  37965. get: function () {
  37966. return this._dPadUp;
  37967. },
  37968. set: function (value) {
  37969. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  37970. },
  37971. enumerable: true,
  37972. configurable: true
  37973. });
  37974. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  37975. get: function () {
  37976. return this._dPadDown;
  37977. },
  37978. set: function (value) {
  37979. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  37980. },
  37981. enumerable: true,
  37982. configurable: true
  37983. });
  37984. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  37985. get: function () {
  37986. return this._dPadLeft;
  37987. },
  37988. set: function (value) {
  37989. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  37990. },
  37991. enumerable: true,
  37992. configurable: true
  37993. });
  37994. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  37995. get: function () {
  37996. return this._dPadRight;
  37997. },
  37998. set: function (value) {
  37999. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38000. },
  38001. enumerable: true,
  38002. configurable: true
  38003. });
  38004. Xbox360Pad.prototype.update = function () {
  38005. _super.prototype.update.call(this);
  38006. this.buttonA = this.browserGamepad.buttons[0].value;
  38007. this.buttonB = this.browserGamepad.buttons[1].value;
  38008. this.buttonX = this.browserGamepad.buttons[2].value;
  38009. this.buttonY = this.browserGamepad.buttons[3].value;
  38010. this.buttonLB = this.browserGamepad.buttons[4].value;
  38011. this.buttonRB = this.browserGamepad.buttons[5].value;
  38012. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38013. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38014. this.buttonBack = this.browserGamepad.buttons[8].value;
  38015. this.buttonStart = this.browserGamepad.buttons[9].value;
  38016. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38017. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38018. this.dPadUp = this.browserGamepad.buttons[12].value;
  38019. this.dPadDown = this.browserGamepad.buttons[13].value;
  38020. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38021. this.dPadRight = this.browserGamepad.buttons[15].value;
  38022. };
  38023. return Xbox360Pad;
  38024. })(Gamepad);
  38025. BABYLON.Xbox360Pad = Xbox360Pad;
  38026. })(BABYLON || (BABYLON = {}));
  38027. var BABYLON;
  38028. (function (BABYLON) {
  38029. // We're mainly based on the logic defined into the FreeCamera code
  38030. var GamepadCamera = (function (_super) {
  38031. __extends(GamepadCamera, _super);
  38032. //-- end properties for backward compatibility for inputs
  38033. function GamepadCamera(name, position, scene) {
  38034. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38035. _super.call(this, name, position, scene);
  38036. }
  38037. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  38038. //-- Begin properties for backward compatibility for inputs
  38039. get: function () {
  38040. var gamepad = this.inputs.attached["gamepad"];
  38041. if (gamepad)
  38042. return gamepad.gamepadAngularSensibility;
  38043. },
  38044. set: function (value) {
  38045. var gamepad = this.inputs.attached["gamepad"];
  38046. if (gamepad)
  38047. gamepad.gamepadAngularSensibility = value;
  38048. },
  38049. enumerable: true,
  38050. configurable: true
  38051. });
  38052. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  38053. get: function () {
  38054. var gamepad = this.inputs.attached["gamepad"];
  38055. if (gamepad)
  38056. return gamepad.gamepadMoveSensibility;
  38057. },
  38058. set: function (value) {
  38059. var gamepad = this.inputs.attached["gamepad"];
  38060. if (gamepad)
  38061. gamepad.gamepadMoveSensibility = value;
  38062. },
  38063. enumerable: true,
  38064. configurable: true
  38065. });
  38066. GamepadCamera.prototype.getTypeName = function () {
  38067. return "GamepadCamera";
  38068. };
  38069. return GamepadCamera;
  38070. })(BABYLON.UniversalCamera);
  38071. BABYLON.GamepadCamera = GamepadCamera;
  38072. })(BABYLON || (BABYLON = {}));
  38073. var BABYLON;
  38074. (function (BABYLON) {
  38075. var Analyser = (function () {
  38076. function Analyser(scene) {
  38077. this.SMOOTHING = 0.75;
  38078. this.FFT_SIZE = 512;
  38079. this.BARGRAPHAMPLITUDE = 256;
  38080. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  38081. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  38082. this._scene = scene;
  38083. this._audioEngine = BABYLON.Engine.audioEngine;
  38084. if (this._audioEngine.canUseWebAudio) {
  38085. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  38086. this._webAudioAnalyser.minDecibels = -140;
  38087. this._webAudioAnalyser.maxDecibels = 0;
  38088. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  38089. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  38090. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  38091. }
  38092. }
  38093. Analyser.prototype.getFrequencyBinCount = function () {
  38094. if (this._audioEngine.canUseWebAudio) {
  38095. return this._webAudioAnalyser.frequencyBinCount;
  38096. }
  38097. else {
  38098. return 0;
  38099. }
  38100. };
  38101. Analyser.prototype.getByteFrequencyData = function () {
  38102. if (this._audioEngine.canUseWebAudio) {
  38103. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38104. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38105. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  38106. }
  38107. return this._byteFreqs;
  38108. };
  38109. Analyser.prototype.getByteTimeDomainData = function () {
  38110. if (this._audioEngine.canUseWebAudio) {
  38111. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38112. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38113. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  38114. }
  38115. return this._byteTime;
  38116. };
  38117. Analyser.prototype.getFloatFrequencyData = function () {
  38118. if (this._audioEngine.canUseWebAudio) {
  38119. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38120. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38121. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  38122. }
  38123. return this._floatFreqs;
  38124. };
  38125. Analyser.prototype.drawDebugCanvas = function () {
  38126. var _this = this;
  38127. if (this._audioEngine.canUseWebAudio) {
  38128. if (!this._debugCanvas) {
  38129. this._debugCanvas = document.createElement("canvas");
  38130. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  38131. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  38132. this._debugCanvas.style.position = "absolute";
  38133. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  38134. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  38135. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  38136. document.body.appendChild(this._debugCanvas);
  38137. this._registerFunc = function () {
  38138. _this.drawDebugCanvas();
  38139. };
  38140. this._scene.registerBeforeRender(this._registerFunc);
  38141. }
  38142. if (this._registerFunc) {
  38143. var workingArray = this.getByteFrequencyData();
  38144. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  38145. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  38146. // Draw the frequency domain chart.
  38147. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  38148. var value = workingArray[i];
  38149. var percent = value / this.BARGRAPHAMPLITUDE;
  38150. var height = this.DEBUGCANVASSIZE.height * percent;
  38151. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  38152. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  38153. var hue = i / this.getFrequencyBinCount() * 360;
  38154. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  38155. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  38156. }
  38157. }
  38158. }
  38159. };
  38160. Analyser.prototype.stopDebugCanvas = function () {
  38161. if (this._debugCanvas) {
  38162. this._scene.unregisterBeforeRender(this._registerFunc);
  38163. this._registerFunc = null;
  38164. document.body.removeChild(this._debugCanvas);
  38165. this._debugCanvas = null;
  38166. this._debugCanvasContext = null;
  38167. }
  38168. };
  38169. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  38170. if (this._audioEngine.canUseWebAudio) {
  38171. inputAudioNode.connect(this._webAudioAnalyser);
  38172. this._webAudioAnalyser.connect(outputAudioNode);
  38173. }
  38174. };
  38175. Analyser.prototype.dispose = function () {
  38176. if (this._audioEngine.canUseWebAudio) {
  38177. this._webAudioAnalyser.disconnect();
  38178. }
  38179. };
  38180. return Analyser;
  38181. })();
  38182. BABYLON.Analyser = Analyser;
  38183. })(BABYLON || (BABYLON = {}));
  38184. var BABYLON;
  38185. (function (BABYLON) {
  38186. var DepthRenderer = (function () {
  38187. function DepthRenderer(scene, type) {
  38188. var _this = this;
  38189. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  38190. this._viewMatrix = BABYLON.Matrix.Zero();
  38191. this._projectionMatrix = BABYLON.Matrix.Zero();
  38192. this._transformMatrix = BABYLON.Matrix.Zero();
  38193. this._worldViewProjection = BABYLON.Matrix.Zero();
  38194. this._scene = scene;
  38195. var engine = scene.getEngine();
  38196. // Render target
  38197. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  38198. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38199. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38200. this._depthMap.refreshRate = 1;
  38201. this._depthMap.renderParticles = false;
  38202. this._depthMap.renderList = null;
  38203. // set default depth value to 1.0 (far away)
  38204. this._depthMap.onClear = function (engine) {
  38205. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  38206. };
  38207. // Custom render function
  38208. var renderSubMesh = function (subMesh) {
  38209. var mesh = subMesh.getRenderingMesh();
  38210. var scene = _this._scene;
  38211. var engine = scene.getEngine();
  38212. // Culling
  38213. engine.setState(subMesh.getMaterial().backFaceCulling);
  38214. // Managing instances
  38215. var batch = mesh._getInstancesRenderList(subMesh._id);
  38216. if (batch.mustReturn) {
  38217. return;
  38218. }
  38219. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  38220. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  38221. engine.enableEffect(_this._effect);
  38222. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  38223. var material = subMesh.getMaterial();
  38224. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  38225. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  38226. // Alpha test
  38227. if (material && material.needAlphaTesting()) {
  38228. var alphaTexture = material.getAlphaTestTexture();
  38229. _this._effect.setTexture("diffuseSampler", alphaTexture);
  38230. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38231. }
  38232. // Bones
  38233. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38234. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38235. }
  38236. // Draw
  38237. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  38238. }
  38239. };
  38240. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  38241. var index;
  38242. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38243. renderSubMesh(opaqueSubMeshes.data[index]);
  38244. }
  38245. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38246. renderSubMesh(alphaTestSubMeshes.data[index]);
  38247. }
  38248. };
  38249. }
  38250. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  38251. var defines = [];
  38252. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38253. var mesh = subMesh.getMesh();
  38254. var scene = mesh.getScene();
  38255. var material = subMesh.getMaterial();
  38256. // Alpha test
  38257. if (material && material.needAlphaTesting()) {
  38258. defines.push("#define ALPHATEST");
  38259. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38260. attribs.push(BABYLON.VertexBuffer.UVKind);
  38261. defines.push("#define UV1");
  38262. }
  38263. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38264. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38265. defines.push("#define UV2");
  38266. }
  38267. }
  38268. // Bones
  38269. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38270. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38271. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38272. if (mesh.numBoneInfluencers > 4) {
  38273. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38274. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38275. }
  38276. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38277. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38278. }
  38279. else {
  38280. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38281. }
  38282. // Instances
  38283. if (useInstances) {
  38284. defines.push("#define INSTANCES");
  38285. attribs.push("world0");
  38286. attribs.push("world1");
  38287. attribs.push("world2");
  38288. attribs.push("world3");
  38289. }
  38290. // Get correct effect
  38291. var join = defines.join("\n");
  38292. if (this._cachedDefines !== join) {
  38293. this._cachedDefines = join;
  38294. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  38295. }
  38296. return this._effect.isReady();
  38297. };
  38298. DepthRenderer.prototype.getDepthMap = function () {
  38299. return this._depthMap;
  38300. };
  38301. // Methods
  38302. DepthRenderer.prototype.dispose = function () {
  38303. this._depthMap.dispose();
  38304. };
  38305. return DepthRenderer;
  38306. })();
  38307. BABYLON.DepthRenderer = DepthRenderer;
  38308. })(BABYLON || (BABYLON = {}));
  38309. var BABYLON;
  38310. (function (BABYLON) {
  38311. var SSAORenderingPipeline = (function (_super) {
  38312. __extends(SSAORenderingPipeline, _super);
  38313. /**
  38314. * @constructor
  38315. * @param {string} name - The rendering pipeline name
  38316. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  38317. * @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 }
  38318. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  38319. */
  38320. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  38321. var _this = this;
  38322. _super.call(this, scene.getEngine(), name);
  38323. // Members
  38324. /**
  38325. * The PassPostProcess id in the pipeline that contains the original scene color
  38326. * @type {string}
  38327. */
  38328. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  38329. /**
  38330. * The SSAO PostProcess id in the pipeline
  38331. * @type {string}
  38332. */
  38333. this.SSAORenderEffect = "SSAORenderEffect";
  38334. /**
  38335. * The horizontal blur PostProcess id in the pipeline
  38336. * @type {string}
  38337. */
  38338. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  38339. /**
  38340. * The vertical blur PostProcess id in the pipeline
  38341. * @type {string}
  38342. */
  38343. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  38344. /**
  38345. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  38346. * @type {string}
  38347. */
  38348. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  38349. /**
  38350. * The output strength of the SSAO post-process. Default value is 1.0.
  38351. * @type {number}
  38352. */
  38353. this.totalStrength = 1.0;
  38354. /**
  38355. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  38356. * @type {number}
  38357. */
  38358. this.radius = 0.0001;
  38359. /**
  38360. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  38361. * Must not be equal to fallOff and superior to fallOff.
  38362. * Default value is 0.975
  38363. * @type {number}
  38364. */
  38365. this.area = 0.0075;
  38366. /**
  38367. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  38368. * Must not be equal to area and inferior to area.
  38369. * Default value is 0.0
  38370. * @type {number}
  38371. */
  38372. this.fallOff = 0.000001;
  38373. /**
  38374. * The base color of the SSAO post-process
  38375. * The final result is "base + ssao" between [0, 1]
  38376. * @type {number}
  38377. */
  38378. this.base = 0.5;
  38379. this._firstUpdate = true;
  38380. this._scene = scene;
  38381. // Set up assets
  38382. this._createRandomTexture();
  38383. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  38384. var ssaoRatio = ratio.ssaoRatio || ratio;
  38385. var combineRatio = ratio.combineRatio || ratio;
  38386. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38387. this._createSSAOPostProcess(ssaoRatio);
  38388. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38389. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38390. this._createSSAOCombinePostProcess(combineRatio);
  38391. // Set up pipeline
  38392. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  38393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  38394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  38395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  38396. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  38397. // Finish
  38398. scene.postProcessRenderPipelineManager.addPipeline(this);
  38399. if (cameras)
  38400. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38401. }
  38402. // Public Methods
  38403. /**
  38404. * Returns the horizontal blur PostProcess
  38405. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  38406. */
  38407. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  38408. return this._blurHPostProcess;
  38409. };
  38410. /**
  38411. * Returns the vertical blur PostProcess
  38412. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  38413. */
  38414. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  38415. return this._blurVPostProcess;
  38416. };
  38417. /**
  38418. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  38419. */
  38420. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  38421. if (disableDepthRender === void 0) { disableDepthRender = false; }
  38422. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38423. this._originalColorPostProcess = undefined;
  38424. this._ssaoPostProcess = undefined;
  38425. this._blurHPostProcess = undefined;
  38426. this._blurVPostProcess = undefined;
  38427. this._ssaoCombinePostProcess = undefined;
  38428. this._randomTexture.dispose();
  38429. if (disableDepthRender)
  38430. this._scene.disableDepthRenderer();
  38431. };
  38432. // Private Methods
  38433. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  38434. var _this = this;
  38435. var numSamples = 16;
  38436. var sampleSphere = [
  38437. 0.5381, 0.1856, -0.4319,
  38438. 0.1379, 0.2486, 0.4430,
  38439. 0.3371, 0.5679, -0.0057,
  38440. -0.6999, -0.0451, -0.0019,
  38441. 0.0689, -0.1598, -0.8547,
  38442. 0.0560, 0.0069, -0.1843,
  38443. -0.0146, 0.1402, 0.0762,
  38444. 0.0100, -0.1924, -0.0344,
  38445. -0.3577, -0.5301, -0.4358,
  38446. -0.3169, 0.1063, 0.0158,
  38447. 0.0103, -0.5869, 0.0046,
  38448. -0.0897, -0.4940, 0.3287,
  38449. 0.7119, -0.0154, -0.0918,
  38450. -0.0533, 0.0596, -0.5411,
  38451. 0.0352, -0.0631, 0.5460,
  38452. -0.4776, 0.2847, -0.0271
  38453. ];
  38454. var samplesFactor = 1.0 / numSamples;
  38455. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  38456. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  38457. "area", "fallOff", "base"
  38458. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  38459. this._ssaoPostProcess.onApply = function (effect) {
  38460. if (_this._firstUpdate) {
  38461. effect.setArray3("sampleSphere", sampleSphere);
  38462. effect.setFloat("samplesFactor", samplesFactor);
  38463. effect.setFloat("randTextureTiles", 4.0);
  38464. _this._firstUpdate = false;
  38465. }
  38466. effect.setFloat("totalStrength", _this.totalStrength);
  38467. effect.setFloat("radius", _this.radius);
  38468. effect.setFloat("area", _this.area);
  38469. effect.setFloat("fallOff", _this.fallOff);
  38470. effect.setFloat("base", _this.base);
  38471. effect.setTexture("textureSampler", _this._depthTexture);
  38472. effect.setTexture("randomSampler", _this._randomTexture);
  38473. };
  38474. };
  38475. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  38476. var _this = this;
  38477. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38478. this._ssaoCombinePostProcess.onApply = function (effect) {
  38479. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  38480. };
  38481. };
  38482. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  38483. var size = 512;
  38484. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38485. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  38486. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  38487. var context = this._randomTexture.getContext();
  38488. var rand = function (min, max) {
  38489. return Math.random() * (max - min) + min;
  38490. };
  38491. var randVector = BABYLON.Vector3.Zero();
  38492. for (var x = 0; x < size; x++) {
  38493. for (var y = 0; y < size; y++) {
  38494. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  38495. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  38496. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  38497. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  38498. context.fillRect(x, y, 1, 1);
  38499. }
  38500. }
  38501. this._randomTexture.update(false);
  38502. };
  38503. return SSAORenderingPipeline;
  38504. })(BABYLON.PostProcessRenderPipeline);
  38505. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  38506. })(BABYLON || (BABYLON = {}));
  38507. var BABYLON;
  38508. (function (BABYLON) {
  38509. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  38510. var VolumetricLightScatteringPostProcess = (function (_super) {
  38511. __extends(VolumetricLightScatteringPostProcess, _super);
  38512. /**
  38513. * @constructor
  38514. * @param {string} name - The post-process name
  38515. * @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)
  38516. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  38517. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  38518. * @param {number} samples - The post-process quality, default 100
  38519. * @param {number} samplingMode - The post-process filtering mode
  38520. * @param {BABYLON.Engine} engine - The babylon engine
  38521. * @param {boolean} reusable - If the post-process is reusable
  38522. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  38523. */
  38524. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  38525. var _this = this;
  38526. if (samples === void 0) { samples = 100; }
  38527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38528. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  38529. this._screenCoordinates = BABYLON.Vector2.Zero();
  38530. /**
  38531. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  38532. * @type {boolean}
  38533. */
  38534. this.useCustomMeshPosition = false;
  38535. /**
  38536. * If the post-process should inverse the light scattering direction
  38537. * @type {boolean}
  38538. */
  38539. this.invert = true;
  38540. /**
  38541. * Set to true to use the diffuseColor instead of the diffuseTexture
  38542. * @type {boolean}
  38543. */
  38544. this.useDiffuseColor = false;
  38545. /**
  38546. * Array containing the excluded meshes not rendered in the internal pass
  38547. */
  38548. this.excludedMeshes = new Array();
  38549. /**
  38550. * Controls the overall intensity of the post-process
  38551. * @type {number}
  38552. */
  38553. this.exposure = 0.3;
  38554. /**
  38555. * Dissipates each sample's contribution in range [0, 1]
  38556. * @type {number}
  38557. */
  38558. this.decay = 0.96815;
  38559. /**
  38560. * Controls the overall intensity of each sample
  38561. * @type {number}
  38562. */
  38563. this.weight = 0.58767;
  38564. /**
  38565. * Controls the density of each sample
  38566. * @type {number}
  38567. */
  38568. this.density = 0.926;
  38569. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  38570. var engine = scene.getEngine();
  38571. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  38572. // Configure mesh
  38573. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  38574. // Configure
  38575. this._createPass(scene, ratio.passRatio || ratio);
  38576. this.onActivate = function (camera) {
  38577. if (!_this.isSupported) {
  38578. _this.dispose(camera);
  38579. }
  38580. _this.onActivate = null;
  38581. };
  38582. this.onApply = function (effect) {
  38583. _this._updateMeshScreenCoordinates(scene);
  38584. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  38585. effect.setFloat("exposure", _this.exposure);
  38586. effect.setFloat("decay", _this.decay);
  38587. effect.setFloat("weight", _this.weight);
  38588. effect.setFloat("density", _this.density);
  38589. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  38590. };
  38591. }
  38592. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  38593. var mesh = subMesh.getMesh();
  38594. var defines = [];
  38595. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38596. var material = subMesh.getMaterial();
  38597. var needUV = false;
  38598. // Render this.mesh as default
  38599. if (mesh === this.mesh) {
  38600. if (this.useDiffuseColor) {
  38601. defines.push("#define DIFFUSE_COLOR_RENDER");
  38602. }
  38603. else if (material) {
  38604. if (material.diffuseTexture !== undefined) {
  38605. defines.push("#define BASIC_RENDER");
  38606. }
  38607. else {
  38608. defines.push("#define DIFFUSE_COLOR_RENDER");
  38609. }
  38610. }
  38611. defines.push("#define NEED_UV");
  38612. needUV = true;
  38613. }
  38614. // Alpha test
  38615. if (material) {
  38616. if (material.needAlphaTesting()) {
  38617. defines.push("#define ALPHATEST");
  38618. }
  38619. if (material.opacityTexture !== undefined) {
  38620. defines.push("#define OPACITY");
  38621. if (material.opacityTexture.getAlphaFromRGB) {
  38622. defines.push("#define OPACITYRGB");
  38623. }
  38624. if (!needUV) {
  38625. defines.push("#define NEED_UV");
  38626. }
  38627. }
  38628. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38629. attribs.push(BABYLON.VertexBuffer.UVKind);
  38630. defines.push("#define UV1");
  38631. }
  38632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38633. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38634. defines.push("#define UV2");
  38635. }
  38636. }
  38637. // Bones
  38638. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38639. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38640. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38641. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38642. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38643. }
  38644. else {
  38645. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38646. }
  38647. // Instances
  38648. if (useInstances) {
  38649. defines.push("#define INSTANCES");
  38650. attribs.push("world0");
  38651. attribs.push("world1");
  38652. attribs.push("world2");
  38653. attribs.push("world3");
  38654. }
  38655. // Get correct effect
  38656. var join = defines.join("\n");
  38657. if (this._cachedDefines !== join) {
  38658. this._cachedDefines = join;
  38659. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  38660. }
  38661. return this._volumetricLightScatteringPass.isReady();
  38662. };
  38663. /**
  38664. * Sets the new light position for light scattering effect
  38665. * @param {BABYLON.Vector3} The new custom light position
  38666. */
  38667. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  38668. this._customMeshPosition = position;
  38669. };
  38670. /**
  38671. * Returns the light position for light scattering effect
  38672. * @return {BABYLON.Vector3} The custom light position
  38673. */
  38674. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  38675. return this._customMeshPosition;
  38676. };
  38677. /**
  38678. * Disposes the internal assets and detaches the post-process from the camera
  38679. */
  38680. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  38681. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  38682. if (rttIndex !== -1) {
  38683. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  38684. }
  38685. this._volumetricLightScatteringRTT.dispose();
  38686. _super.prototype.dispose.call(this, camera);
  38687. };
  38688. /**
  38689. * Returns the render target texture used by the post-process
  38690. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  38691. */
  38692. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  38693. return this._volumetricLightScatteringRTT;
  38694. };
  38695. // Private methods
  38696. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  38697. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  38698. return true;
  38699. }
  38700. return false;
  38701. };
  38702. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  38703. var _this = this;
  38704. var engine = scene.getEngine();
  38705. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38706. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38707. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38708. this._volumetricLightScatteringRTT.renderList = null;
  38709. this._volumetricLightScatteringRTT.renderParticles = false;
  38710. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  38711. // Custom render function for submeshes
  38712. var renderSubMesh = function (subMesh) {
  38713. var mesh = subMesh.getRenderingMesh();
  38714. if (_this._meshExcluded(mesh)) {
  38715. return;
  38716. }
  38717. var scene = mesh.getScene();
  38718. var engine = scene.getEngine();
  38719. // Culling
  38720. engine.setState(subMesh.getMaterial().backFaceCulling);
  38721. // Managing instances
  38722. var batch = mesh._getInstancesRenderList(subMesh._id);
  38723. if (batch.mustReturn) {
  38724. return;
  38725. }
  38726. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  38727. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  38728. engine.enableEffect(_this._volumetricLightScatteringPass);
  38729. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  38730. var material = subMesh.getMaterial();
  38731. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  38732. // Alpha test
  38733. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  38734. var alphaTexture = material.getAlphaTestTexture();
  38735. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  38736. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  38737. }
  38738. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  38739. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  38740. if (alphaTexture) {
  38741. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38742. }
  38743. }
  38744. if (material.opacityTexture !== undefined) {
  38745. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  38746. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  38747. }
  38748. }
  38749. // Bones
  38750. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38751. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38752. }
  38753. // Draw
  38754. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  38755. }
  38756. };
  38757. // Render target texture callbacks
  38758. var savedSceneClearColor;
  38759. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  38760. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  38761. savedSceneClearColor = scene.clearColor;
  38762. scene.clearColor = sceneClearColor;
  38763. };
  38764. this._volumetricLightScatteringRTT.onAfterRender = function () {
  38765. scene.clearColor = savedSceneClearColor;
  38766. };
  38767. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38768. var engine = scene.getEngine();
  38769. var index;
  38770. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38771. renderSubMesh(opaqueSubMeshes.data[index]);
  38772. }
  38773. engine.setAlphaTesting(true);
  38774. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38775. renderSubMesh(alphaTestSubMeshes.data[index]);
  38776. }
  38777. engine.setAlphaTesting(false);
  38778. if (transparentSubMeshes.length) {
  38779. // Sort sub meshes
  38780. for (index = 0; index < transparentSubMeshes.length; index++) {
  38781. var submesh = transparentSubMeshes.data[index];
  38782. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  38783. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  38784. }
  38785. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  38786. sortedArray.sort(function (a, b) {
  38787. // Alpha index first
  38788. if (a._alphaIndex > b._alphaIndex) {
  38789. return 1;
  38790. }
  38791. if (a._alphaIndex < b._alphaIndex) {
  38792. return -1;
  38793. }
  38794. // Then distance to camera
  38795. if (a._distanceToCamera < b._distanceToCamera) {
  38796. return 1;
  38797. }
  38798. if (a._distanceToCamera > b._distanceToCamera) {
  38799. return -1;
  38800. }
  38801. return 0;
  38802. });
  38803. // Render sub meshes
  38804. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38805. for (index = 0; index < sortedArray.length; index++) {
  38806. renderSubMesh(sortedArray[index]);
  38807. }
  38808. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38809. }
  38810. };
  38811. };
  38812. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  38813. var transform = scene.getTransformMatrix();
  38814. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  38815. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  38816. this._screenCoordinates.x = pos.x / this._viewPort.width;
  38817. this._screenCoordinates.y = pos.y / this._viewPort.height;
  38818. if (this.invert)
  38819. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  38820. };
  38821. // Static methods
  38822. /**
  38823. * Creates a default mesh for the Volumeric Light Scattering post-process
  38824. * @param {string} The mesh name
  38825. * @param {BABYLON.Scene} The scene where to create the mesh
  38826. * @return {BABYLON.Mesh} the default mesh
  38827. */
  38828. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  38829. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  38830. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  38831. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  38832. return mesh;
  38833. };
  38834. return VolumetricLightScatteringPostProcess;
  38835. })(BABYLON.PostProcess);
  38836. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  38837. })(BABYLON || (BABYLON = {}));
  38838. // BABYLON.JS Chromatic Aberration GLSL Shader
  38839. // Author: Olivier Guyot
  38840. // Separates very slightly R, G and B colors on the edges of the screen
  38841. // Inspired by Francois Tarlier & Martins Upitis
  38842. var BABYLON;
  38843. (function (BABYLON) {
  38844. var LensRenderingPipeline = (function (_super) {
  38845. __extends(LensRenderingPipeline, _super);
  38846. /**
  38847. * @constructor
  38848. *
  38849. * Effect parameters are as follow:
  38850. * {
  38851. * chromatic_aberration: number; // from 0 to x (1 for realism)
  38852. * edge_blur: number; // from 0 to x (1 for realism)
  38853. * distortion: number; // from 0 to x (1 for realism)
  38854. * grain_amount: number; // from 0 to 1
  38855. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  38856. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  38857. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  38858. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  38859. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  38860. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  38861. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  38862. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  38863. * }
  38864. * Note: if an effect parameter is unset, effect is disabled
  38865. *
  38866. * @param {string} name - The rendering pipeline name
  38867. * @param {object} parameters - An object containing all parameters (see above)
  38868. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  38869. * @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)
  38870. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  38871. */
  38872. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  38873. var _this = this;
  38874. if (ratio === void 0) { ratio = 1.0; }
  38875. _super.call(this, scene.getEngine(), name);
  38876. // Lens effects can be of the following:
  38877. // - chromatic aberration (slight shift of RGB colors)
  38878. // - blur on the edge of the lens
  38879. // - lens distortion
  38880. // - depth-of-field blur & highlights enhancing
  38881. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  38882. // - grain effect (noise or custom texture)
  38883. // Two additional texture samplers are needed:
  38884. // - depth map (for depth-of-field)
  38885. // - grain texture
  38886. /**
  38887. * The chromatic aberration PostProcess id in the pipeline
  38888. * @type {string}
  38889. */
  38890. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  38891. /**
  38892. * The highlights enhancing PostProcess id in the pipeline
  38893. * @type {string}
  38894. */
  38895. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  38896. /**
  38897. * The depth-of-field PostProcess id in the pipeline
  38898. * @type {string}
  38899. */
  38900. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  38901. this._scene = scene;
  38902. // Fetch texture samplers
  38903. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  38904. if (parameters.grain_texture) {
  38905. this._grainTexture = parameters.grain_texture;
  38906. }
  38907. else {
  38908. this._createGrainTexture();
  38909. }
  38910. // save parameters
  38911. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  38912. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  38913. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  38914. this._distortion = parameters.distortion ? parameters.distortion : 0;
  38915. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  38916. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  38917. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  38918. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  38919. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  38920. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  38921. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  38922. // Create effects
  38923. this._createChromaticAberrationPostProcess(ratio);
  38924. this._createHighlightsPostProcess(ratio);
  38925. this._createDepthOfFieldPostProcess(ratio / 4);
  38926. // Set up pipeline
  38927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  38928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  38929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  38930. if (this._highlightsGain === -1) {
  38931. this._disableEffect(this.HighlightsEnhancingEffect, null);
  38932. }
  38933. // Finish
  38934. scene.postProcessRenderPipelineManager.addPipeline(this);
  38935. if (cameras) {
  38936. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38937. }
  38938. }
  38939. // public methods (self explanatory)
  38940. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  38941. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  38942. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  38943. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  38944. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  38945. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  38946. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  38947. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  38948. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  38949. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  38950. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  38951. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  38952. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  38953. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  38954. };
  38955. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  38956. this._highlightsPostProcess.updateEffect();
  38957. };
  38958. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  38959. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  38960. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  38961. this._highlightsGain = amount;
  38962. };
  38963. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  38964. if (this._highlightsGain === -1) {
  38965. this._highlightsGain = 1.0;
  38966. }
  38967. this._highlightsThreshold = amount;
  38968. };
  38969. LensRenderingPipeline.prototype.disableHighlights = function () {
  38970. this._highlightsGain = -1;
  38971. };
  38972. /**
  38973. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  38974. */
  38975. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  38976. if (disableDepthRender === void 0) { disableDepthRender = false; }
  38977. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38978. this._chromaticAberrationPostProcess = undefined;
  38979. this._highlightsPostProcess = undefined;
  38980. this._depthOfFieldPostProcess = undefined;
  38981. this._grainTexture.dispose();
  38982. if (disableDepthRender)
  38983. this._scene.disableDepthRenderer();
  38984. };
  38985. // colors shifting and distortion
  38986. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  38987. var _this = this;
  38988. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  38989. [], // samplers
  38990. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38991. this._chromaticAberrationPostProcess.onApply = function (effect) {
  38992. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  38993. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38994. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38995. };
  38996. };
  38997. // highlights enhancing
  38998. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  38999. var _this = this;
  39000. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  39001. [], // samplers
  39002. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  39003. this._highlightsPostProcess.onApply = function (effect) {
  39004. effect.setFloat('gain', _this._highlightsGain);
  39005. effect.setFloat('threshold', _this._highlightsThreshold);
  39006. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  39007. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  39008. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  39009. };
  39010. };
  39011. // colors shifting and distortion
  39012. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  39013. var _this = this;
  39014. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  39015. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  39016. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  39017. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39018. this._depthOfFieldPostProcess.onApply = function (effect) {
  39019. effect.setTexture("depthSampler", _this._depthTexture);
  39020. effect.setTexture("grainSampler", _this._grainTexture);
  39021. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  39022. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  39023. effect.setFloat('grain_amount', _this._grainAmount);
  39024. effect.setBool('blur_noise', _this._blurNoise);
  39025. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  39026. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  39027. effect.setFloat('distortion', _this._distortion);
  39028. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  39029. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  39030. effect.setFloat('aperture', _this._dofAperture);
  39031. effect.setFloat('darken', _this._dofDarken);
  39032. effect.setFloat('edge_blur', _this._edgeBlur);
  39033. effect.setBool('highlights', (_this._highlightsGain !== -1));
  39034. effect.setFloat('near', _this._scene.activeCamera.minZ);
  39035. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  39036. };
  39037. };
  39038. // creates a black and white random noise texture, 512x512
  39039. LensRenderingPipeline.prototype._createGrainTexture = function () {
  39040. var size = 512;
  39041. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39042. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39043. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39044. var context = this._grainTexture.getContext();
  39045. var rand = function (min, max) {
  39046. return Math.random() * (max - min) + min;
  39047. };
  39048. var value;
  39049. for (var x = 0; x < size; x++) {
  39050. for (var y = 0; y < size; y++) {
  39051. value = Math.floor(rand(0.42, 0.58) * 255);
  39052. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  39053. context.fillRect(x, y, 1, 1);
  39054. }
  39055. }
  39056. this._grainTexture.update(false);
  39057. };
  39058. return LensRenderingPipeline;
  39059. })(BABYLON.PostProcessRenderPipeline);
  39060. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  39061. })(BABYLON || (BABYLON = {}));
  39062. //
  39063. // This post-process allows the modification of rendered colors by using
  39064. // a 'look-up table' (LUT). This effect is also called Color Grading.
  39065. //
  39066. // The object needs to be provided an url to a texture containing the color
  39067. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  39068. // Use an image editing software to tweak the LUT to match your needs.
  39069. //
  39070. // For an example of a color LUT, see here:
  39071. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  39072. // For explanations on color grading, see here:
  39073. // http://udn.epicgames.com/Three/ColorGrading.html
  39074. //
  39075. var BABYLON;
  39076. (function (BABYLON) {
  39077. var ColorCorrectionPostProcess = (function (_super) {
  39078. __extends(ColorCorrectionPostProcess, _super);
  39079. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  39080. var _this = this;
  39081. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  39082. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  39083. this._colorTableTexture.anisotropicFilteringLevel = 1;
  39084. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39085. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39086. this.onApply = function (effect) {
  39087. effect.setTexture("colorTable", _this._colorTableTexture);
  39088. };
  39089. }
  39090. return ColorCorrectionPostProcess;
  39091. })(BABYLON.PostProcess);
  39092. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  39093. })(BABYLON || (BABYLON = {}));
  39094. var BABYLON;
  39095. (function (BABYLON) {
  39096. var AnaglyphFreeCamera = (function (_super) {
  39097. __extends(AnaglyphFreeCamera, _super);
  39098. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  39099. _super.call(this, name, position, scene);
  39100. this.interaxialDistance = interaxialDistance;
  39101. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39102. }
  39103. AnaglyphFreeCamera.prototype.getTypeName = function () {
  39104. return "AnaglyphFreeCamera";
  39105. };
  39106. return AnaglyphFreeCamera;
  39107. })(BABYLON.FreeCamera);
  39108. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  39109. var AnaglyphArcRotateCamera = (function (_super) {
  39110. __extends(AnaglyphArcRotateCamera, _super);
  39111. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  39112. _super.call(this, name, alpha, beta, radius, target, scene);
  39113. this.interaxialDistance = interaxialDistance;
  39114. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39115. }
  39116. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  39117. return "AnaglyphArcRotateCamera";
  39118. };
  39119. return AnaglyphArcRotateCamera;
  39120. })(BABYLON.ArcRotateCamera);
  39121. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  39122. var AnaglyphGamepadCamera = (function (_super) {
  39123. __extends(AnaglyphGamepadCamera, _super);
  39124. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  39125. _super.call(this, name, position, scene);
  39126. this.interaxialDistance = interaxialDistance;
  39127. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39128. }
  39129. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  39130. return "AnaglyphGamepadCamera";
  39131. };
  39132. return AnaglyphGamepadCamera;
  39133. })(BABYLON.GamepadCamera);
  39134. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  39135. var AnaglyphUniversalCamera = (function (_super) {
  39136. __extends(AnaglyphUniversalCamera, _super);
  39137. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  39138. _super.call(this, name, position, scene);
  39139. this.interaxialDistance = interaxialDistance;
  39140. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39141. }
  39142. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  39143. return "AnaglyphUniversalCamera";
  39144. };
  39145. return AnaglyphUniversalCamera;
  39146. })(BABYLON.UniversalCamera);
  39147. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  39148. var StereoscopicFreeCamera = (function (_super) {
  39149. __extends(StereoscopicFreeCamera, _super);
  39150. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39151. _super.call(this, name, position, scene);
  39152. this.interaxialDistance = interaxialDistance;
  39153. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39154. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39155. }
  39156. StereoscopicFreeCamera.prototype.getTypeName = function () {
  39157. return "StereoscopicFreeCamera";
  39158. };
  39159. return StereoscopicFreeCamera;
  39160. })(BABYLON.FreeCamera);
  39161. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  39162. var StereoscopicArcRotateCamera = (function (_super) {
  39163. __extends(StereoscopicArcRotateCamera, _super);
  39164. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  39165. _super.call(this, name, alpha, beta, radius, target, scene);
  39166. this.interaxialDistance = interaxialDistance;
  39167. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39168. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39169. }
  39170. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  39171. return "StereoscopicArcRotateCamera";
  39172. };
  39173. return StereoscopicArcRotateCamera;
  39174. })(BABYLON.ArcRotateCamera);
  39175. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  39176. var StereoscopicGamepadCamera = (function (_super) {
  39177. __extends(StereoscopicGamepadCamera, _super);
  39178. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39179. _super.call(this, name, position, scene);
  39180. this.interaxialDistance = interaxialDistance;
  39181. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39182. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39183. }
  39184. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  39185. return "StereoscopicGamepadCamera";
  39186. };
  39187. return StereoscopicGamepadCamera;
  39188. })(BABYLON.GamepadCamera);
  39189. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  39190. var StereoscopicUniversalCamera = (function (_super) {
  39191. __extends(StereoscopicUniversalCamera, _super);
  39192. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39193. _super.call(this, name, position, scene);
  39194. this.interaxialDistance = interaxialDistance;
  39195. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39196. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39197. }
  39198. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  39199. return "StereoscopicUniversalCamera";
  39200. };
  39201. return StereoscopicUniversalCamera;
  39202. })(BABYLON.UniversalCamera);
  39203. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  39204. })(BABYLON || (BABYLON = {}));
  39205. var BABYLON;
  39206. (function (BABYLON) {
  39207. var HDRRenderingPipeline = (function (_super) {
  39208. __extends(HDRRenderingPipeline, _super);
  39209. /**
  39210. * @constructor
  39211. * @param {string} name - The rendering pipeline name
  39212. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39213. * @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)
  39214. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  39215. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39216. */
  39217. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  39218. var _this = this;
  39219. if (originalPostProcess === void 0) { originalPostProcess = null; }
  39220. _super.call(this, scene.getEngine(), name);
  39221. /**
  39222. * Public members
  39223. */
  39224. // Gaussian Blur
  39225. /**
  39226. * Gaussian blur coefficient
  39227. * @type {number}
  39228. */
  39229. this.gaussCoeff = 0.3;
  39230. /**
  39231. * Gaussian blur mean
  39232. * @type {number}
  39233. */
  39234. this.gaussMean = 1.0;
  39235. /**
  39236. * Gaussian blur standard deviation
  39237. * @type {number}
  39238. */
  39239. this.gaussStandDev = 0.8;
  39240. /**
  39241. * Gaussian blur multiplier. Multiplies the blur effect
  39242. * @type {number}
  39243. */
  39244. this.gaussMultiplier = 4.0;
  39245. // HDR
  39246. /**
  39247. * Exposure, controls the overall intensity of the pipeline
  39248. * @type {number}
  39249. */
  39250. this.exposure = 1.0;
  39251. /**
  39252. * Minimum luminance that the post-process can output. Luminance is >= 0
  39253. * @type {number}
  39254. */
  39255. this.minimumLuminance = 1.0;
  39256. /**
  39257. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  39258. * @type {number}
  39259. */
  39260. this.maximumLuminance = 1e20;
  39261. /**
  39262. * Increase rate for luminance: eye adaptation speed to dark
  39263. * @type {number}
  39264. */
  39265. this.luminanceIncreaserate = 0.5;
  39266. /**
  39267. * Decrease rate for luminance: eye adaptation speed to bright
  39268. * @type {number}
  39269. */
  39270. this.luminanceDecreaseRate = 0.5;
  39271. // Bright pass
  39272. /**
  39273. * Minimum luminance needed to compute HDR
  39274. * @type {number}
  39275. */
  39276. this.brightThreshold = 0.8;
  39277. this._needUpdate = true;
  39278. this._scene = scene;
  39279. // Bright pass
  39280. this._createBrightPassPostProcess(scene, ratio);
  39281. // Down sample X4
  39282. this._createDownSampleX4PostProcess(scene, ratio);
  39283. // Create gaussian blur post-processes
  39284. this._createGaussianBlurPostProcess(scene, ratio);
  39285. // Texture adder
  39286. this._createTextureAdderPostProcess(scene, ratio);
  39287. // Luminance generator
  39288. this._createLuminanceGeneratorPostProcess(scene);
  39289. // HDR
  39290. this._createHDRPostProcess(scene, ratio);
  39291. // Pass postprocess
  39292. if (originalPostProcess === null) {
  39293. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39294. }
  39295. else {
  39296. this._originalPostProcess = originalPostProcess;
  39297. }
  39298. // Configure pipeline
  39299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  39300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  39301. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  39302. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  39303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  39304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  39305. var addDownSamplerPostProcess = function (id) {
  39306. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  39307. };
  39308. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  39309. addDownSamplerPostProcess(i);
  39310. }
  39311. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  39312. // Finish
  39313. scene.postProcessRenderPipelineManager.addPipeline(this);
  39314. if (cameras !== null) {
  39315. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39316. }
  39317. this.update();
  39318. }
  39319. /**
  39320. * Tells the pipeline to update its post-processes
  39321. */
  39322. HDRRenderingPipeline.prototype.update = function () {
  39323. this._needUpdate = true;
  39324. };
  39325. /**
  39326. * Returns the current calculated luminance
  39327. */
  39328. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  39329. return this._hdrCurrentLuminance;
  39330. };
  39331. /**
  39332. * Returns the currently drawn luminance
  39333. */
  39334. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  39335. return this._hdrOutputLuminance;
  39336. };
  39337. /**
  39338. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  39339. */
  39340. HDRRenderingPipeline.prototype.dispose = function () {
  39341. this._originalPostProcess = undefined;
  39342. this._brightPassPostProcess = undefined;
  39343. this._downSampleX4PostProcess = undefined;
  39344. this._guassianBlurHPostProcess = undefined;
  39345. this._guassianBlurVPostProcess = undefined;
  39346. this._textureAdderPostProcess = undefined;
  39347. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  39348. this._downSamplePostProcesses[i] = undefined;
  39349. }
  39350. this._hdrPostProcess = undefined;
  39351. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39352. };
  39353. /**
  39354. * Creates the HDR post-process and computes the luminance adaptation
  39355. */
  39356. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  39357. var _this = this;
  39358. var hdrLastLuminance = 0.0;
  39359. this._hdrOutputLuminance = -1.0;
  39360. this._hdrCurrentLuminance = 1.0;
  39361. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  39362. this._hdrPostProcess.onApply = function (effect) {
  39363. if (_this._hdrOutputLuminance < 0.0) {
  39364. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  39365. }
  39366. else {
  39367. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  39368. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  39369. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  39370. }
  39371. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  39372. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  39373. }
  39374. else {
  39375. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  39376. }
  39377. }
  39378. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  39379. hdrLastLuminance += scene.getEngine().getDeltaTime();
  39380. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  39381. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  39382. effect.setFloat("exposure", _this.exposure);
  39383. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  39384. _this._needUpdate = false;
  39385. };
  39386. };
  39387. /**
  39388. * Texture Adder post-process
  39389. */
  39390. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  39391. var _this = this;
  39392. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  39393. this._textureAdderPostProcess.onApply = function (effect) {
  39394. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  39395. };
  39396. };
  39397. /**
  39398. * Down sample X4 post-process
  39399. */
  39400. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  39401. var _this = this;
  39402. var downSampleX4Offsets = new Array(32);
  39403. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  39404. this._downSampleX4PostProcess.onApply = function (effect) {
  39405. if (_this._needUpdate) {
  39406. var id = 0;
  39407. for (var i = -2; i < 2; i++) {
  39408. for (var j = -2; j < 2; j++) {
  39409. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  39410. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  39411. id += 2;
  39412. }
  39413. }
  39414. }
  39415. effect.setArray2("dsOffsets", downSampleX4Offsets);
  39416. };
  39417. };
  39418. /**
  39419. * Bright pass post-process
  39420. */
  39421. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  39422. var _this = this;
  39423. var brightOffsets = new Array(8);
  39424. var brightPassCallback = function (effect) {
  39425. if (_this._needUpdate) {
  39426. var sU = (1.0 / _this._brightPassPostProcess.width);
  39427. var sV = (1.0 / _this._brightPassPostProcess.height);
  39428. brightOffsets[0] = -0.5 * sU;
  39429. brightOffsets[1] = 0.5 * sV;
  39430. brightOffsets[2] = 0.5 * sU;
  39431. brightOffsets[3] = 0.5 * sV;
  39432. brightOffsets[4] = -0.5 * sU;
  39433. brightOffsets[5] = -0.5 * sV;
  39434. brightOffsets[6] = 0.5 * sU;
  39435. brightOffsets[7] = -0.5 * sV;
  39436. }
  39437. effect.setArray2("dsOffsets", brightOffsets);
  39438. effect.setFloat("brightThreshold", _this.brightThreshold);
  39439. };
  39440. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  39441. this._brightPassPostProcess.onApply = brightPassCallback;
  39442. };
  39443. /**
  39444. * Luminance generator. Creates the luminance post-process and down sample post-processes
  39445. */
  39446. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  39447. var _this = this;
  39448. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  39449. var luminanceOffsets = new Array(8);
  39450. var downSampleOffsets = new Array(18);
  39451. var halfDestPixelSize;
  39452. this._downSamplePostProcesses = new Array(lumSteps);
  39453. // Utils for luminance
  39454. var luminanceUpdateSourceOffsets = function (width, height) {
  39455. var sU = (1.0 / width);
  39456. var sV = (1.0 / height);
  39457. luminanceOffsets[0] = -0.5 * sU;
  39458. luminanceOffsets[1] = 0.5 * sV;
  39459. luminanceOffsets[2] = 0.5 * sU;
  39460. luminanceOffsets[3] = 0.5 * sV;
  39461. luminanceOffsets[4] = -0.5 * sU;
  39462. luminanceOffsets[5] = -0.5 * sV;
  39463. luminanceOffsets[6] = 0.5 * sU;
  39464. luminanceOffsets[7] = -0.5 * sV;
  39465. };
  39466. var luminanceUpdateDestOffsets = function (width, height) {
  39467. var id = 0;
  39468. for (var x = -1; x < 2; x++) {
  39469. for (var y = -1; y < 2; y++) {
  39470. downSampleOffsets[id] = (x) / width;
  39471. downSampleOffsets[id + 1] = (y) / height;
  39472. id += 2;
  39473. }
  39474. }
  39475. };
  39476. // Luminance callback
  39477. var luminanceCallback = function (effect) {
  39478. if (_this._needUpdate) {
  39479. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  39480. }
  39481. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  39482. effect.setArray2("lumOffsets", luminanceOffsets);
  39483. };
  39484. // Down sample callbacks
  39485. var downSampleCallback = function (indice) {
  39486. var i = indice;
  39487. return function (effect) {
  39488. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  39489. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  39490. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  39491. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  39492. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  39493. effect.setArray2("dsOffsets", downSampleOffsets);
  39494. };
  39495. };
  39496. var downSampleAfterRenderCallback = function (effect) {
  39497. // Unpack result
  39498. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  39499. 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);
  39500. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  39501. };
  39502. // Create luminance post-process
  39503. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  39504. 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);
  39505. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  39506. // Create down sample post-processes
  39507. for (var i = lumSteps - 2; i >= 0; i--) {
  39508. var length = Math.pow(3, i);
  39509. ratio = { width: length, height: length };
  39510. var defines = "#define DOWN_SAMPLE\n";
  39511. if (i === 0) {
  39512. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  39513. }
  39514. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  39515. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  39516. if (i === 0) {
  39517. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  39518. }
  39519. }
  39520. };
  39521. /**
  39522. * Gaussian blur post-processes. Horizontal and Vertical
  39523. */
  39524. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  39525. var _this = this;
  39526. var blurOffsetsW = new Array(9);
  39527. var blurOffsetsH = new Array(9);
  39528. var blurWeights = new Array(9);
  39529. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  39530. // Utils for gaussian blur
  39531. var calculateBlurOffsets = function (height) {
  39532. var lastOutputDimensions = {
  39533. width: scene.getEngine().getRenderWidth(),
  39534. height: scene.getEngine().getRenderHeight()
  39535. };
  39536. for (var i = 0; i < 9; i++) {
  39537. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  39538. if (height) {
  39539. blurOffsetsH[i] = value;
  39540. }
  39541. else {
  39542. blurOffsetsW[i] = value;
  39543. }
  39544. }
  39545. };
  39546. var calculateWeights = function () {
  39547. var x = 0.0;
  39548. for (var i = 0; i < 9; i++) {
  39549. x = (i - 4.0) / 4.0;
  39550. 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));
  39551. }
  39552. };
  39553. // Callback
  39554. var gaussianBlurCallback = function (height) {
  39555. return function (effect) {
  39556. if (_this._needUpdate) {
  39557. calculateWeights();
  39558. calculateBlurOffsets(height);
  39559. }
  39560. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  39561. effect.setArray("blurWeights", blurWeights);
  39562. effect.setFloat("multiplier", _this.gaussMultiplier);
  39563. };
  39564. };
  39565. // Create horizontal gaussian blur post-processes
  39566. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  39567. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  39568. // Create vertical gaussian blur post-process
  39569. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  39570. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  39571. };
  39572. // Luminance generator
  39573. HDRRenderingPipeline.LUM_STEPS = 6;
  39574. return HDRRenderingPipeline;
  39575. })(BABYLON.PostProcessRenderPipeline);
  39576. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  39577. })(BABYLON || (BABYLON = {}));
  39578. var BABYLON;
  39579. (function (BABYLON) {
  39580. var FaceAdjacencies = (function () {
  39581. function FaceAdjacencies() {
  39582. this.edges = new Array();
  39583. this.edgesConnectedCount = 0;
  39584. }
  39585. return FaceAdjacencies;
  39586. })();
  39587. var EdgesRenderer = (function () {
  39588. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  39589. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  39590. if (epsilon === void 0) { epsilon = 0.95; }
  39591. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  39592. this.edgesWidthScalerForOrthographic = 1000.0;
  39593. this.edgesWidthScalerForPerspective = 50.0;
  39594. this._linesPositions = new Array();
  39595. this._linesNormals = new Array();
  39596. this._linesIndices = new Array();
  39597. this._buffers = new Array();
  39598. this._checkVerticesInsteadOfIndices = false;
  39599. this._source = source;
  39600. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  39601. this._epsilon = epsilon;
  39602. this._prepareRessources();
  39603. this._generateEdgesLines();
  39604. }
  39605. EdgesRenderer.prototype._prepareRessources = function () {
  39606. if (this._lineShader) {
  39607. return;
  39608. }
  39609. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  39610. attributes: ["position", "normal"],
  39611. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  39612. });
  39613. this._lineShader.disableDepthWrite = true;
  39614. this._lineShader.backFaceCulling = false;
  39615. };
  39616. EdgesRenderer.prototype.dispose = function () {
  39617. this._vb0.dispose();
  39618. this._vb1.dispose();
  39619. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  39620. this._lineShader.dispose();
  39621. };
  39622. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  39623. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  39624. return 0;
  39625. }
  39626. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  39627. return 1;
  39628. }
  39629. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  39630. return 2;
  39631. }
  39632. return -1;
  39633. };
  39634. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  39635. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  39636. return 0;
  39637. }
  39638. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  39639. return 1;
  39640. }
  39641. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  39642. return 2;
  39643. }
  39644. return -1;
  39645. };
  39646. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  39647. var needToCreateLine;
  39648. if (edge === undefined) {
  39649. needToCreateLine = true;
  39650. }
  39651. else {
  39652. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  39653. needToCreateLine = dotProduct < this._epsilon;
  39654. }
  39655. if (needToCreateLine) {
  39656. var offset = this._linesPositions.length / 3;
  39657. var normal = p0.subtract(p1);
  39658. normal.normalize();
  39659. // Positions
  39660. this._linesPositions.push(p0.x);
  39661. this._linesPositions.push(p0.y);
  39662. this._linesPositions.push(p0.z);
  39663. this._linesPositions.push(p0.x);
  39664. this._linesPositions.push(p0.y);
  39665. this._linesPositions.push(p0.z);
  39666. this._linesPositions.push(p1.x);
  39667. this._linesPositions.push(p1.y);
  39668. this._linesPositions.push(p1.z);
  39669. this._linesPositions.push(p1.x);
  39670. this._linesPositions.push(p1.y);
  39671. this._linesPositions.push(p1.z);
  39672. // Normals
  39673. this._linesNormals.push(p1.x);
  39674. this._linesNormals.push(p1.y);
  39675. this._linesNormals.push(p1.z);
  39676. this._linesNormals.push(-1);
  39677. this._linesNormals.push(p1.x);
  39678. this._linesNormals.push(p1.y);
  39679. this._linesNormals.push(p1.z);
  39680. this._linesNormals.push(1);
  39681. this._linesNormals.push(p0.x);
  39682. this._linesNormals.push(p0.y);
  39683. this._linesNormals.push(p0.z);
  39684. this._linesNormals.push(-1);
  39685. this._linesNormals.push(p0.x);
  39686. this._linesNormals.push(p0.y);
  39687. this._linesNormals.push(p0.z);
  39688. this._linesNormals.push(1);
  39689. // Indices
  39690. this._linesIndices.push(offset);
  39691. this._linesIndices.push(offset + 1);
  39692. this._linesIndices.push(offset + 2);
  39693. this._linesIndices.push(offset);
  39694. this._linesIndices.push(offset + 2);
  39695. this._linesIndices.push(offset + 3);
  39696. }
  39697. };
  39698. EdgesRenderer.prototype._generateEdgesLines = function () {
  39699. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39700. var indices = this._source.getIndices();
  39701. // First let's find adjacencies
  39702. var adjacencies = new Array();
  39703. var faceNormals = new Array();
  39704. var index;
  39705. var faceAdjacencies;
  39706. // Prepare faces
  39707. for (index = 0; index < indices.length; index += 3) {
  39708. faceAdjacencies = new FaceAdjacencies();
  39709. var p0Index = indices[index];
  39710. var p1Index = indices[index + 1];
  39711. var p2Index = indices[index + 2];
  39712. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  39713. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  39714. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  39715. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  39716. faceNormal.normalize();
  39717. faceNormals.push(faceNormal);
  39718. adjacencies.push(faceAdjacencies);
  39719. }
  39720. // Scan
  39721. for (index = 0; index < adjacencies.length; index++) {
  39722. faceAdjacencies = adjacencies[index];
  39723. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  39724. var otherFaceAdjacencies = adjacencies[otherIndex];
  39725. if (faceAdjacencies.edgesConnectedCount === 3) {
  39726. break;
  39727. }
  39728. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  39729. continue;
  39730. }
  39731. var otherP0 = indices[otherIndex * 3];
  39732. var otherP1 = indices[otherIndex * 3 + 1];
  39733. var otherP2 = indices[otherIndex * 3 + 2];
  39734. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  39735. var otherEdgeIndex;
  39736. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  39737. continue;
  39738. }
  39739. switch (edgeIndex) {
  39740. case 0:
  39741. if (this._checkVerticesInsteadOfIndices) {
  39742. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39743. }
  39744. else {
  39745. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  39746. }
  39747. break;
  39748. case 1:
  39749. if (this._checkVerticesInsteadOfIndices) {
  39750. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39751. }
  39752. else {
  39753. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  39754. }
  39755. break;
  39756. case 2:
  39757. if (this._checkVerticesInsteadOfIndices) {
  39758. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39759. }
  39760. else {
  39761. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  39762. }
  39763. break;
  39764. }
  39765. if (otherEdgeIndex === -1) {
  39766. continue;
  39767. }
  39768. faceAdjacencies.edges[edgeIndex] = otherIndex;
  39769. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  39770. faceAdjacencies.edgesConnectedCount++;
  39771. otherFaceAdjacencies.edgesConnectedCount++;
  39772. if (faceAdjacencies.edgesConnectedCount === 3) {
  39773. break;
  39774. }
  39775. }
  39776. }
  39777. }
  39778. // Create lines
  39779. for (index = 0; index < adjacencies.length; index++) {
  39780. // 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
  39781. var current = adjacencies[index];
  39782. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  39783. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  39784. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  39785. }
  39786. // Merge into a single mesh
  39787. var engine = this._source.getScene().getEngine();
  39788. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  39789. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  39790. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  39791. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  39792. this._ib = engine.createIndexBuffer(this._linesIndices);
  39793. this._indicesCount = this._linesIndices.length;
  39794. };
  39795. EdgesRenderer.prototype.render = function () {
  39796. if (!this._lineShader.isReady()) {
  39797. return;
  39798. }
  39799. var scene = this._source.getScene();
  39800. var engine = scene.getEngine();
  39801. this._lineShader._preBind();
  39802. // VBOs
  39803. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  39804. scene.resetCachedMaterial();
  39805. this._lineShader.setColor4("color", this._source.edgesColor);
  39806. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  39807. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  39808. }
  39809. else {
  39810. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  39811. }
  39812. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  39813. this._lineShader.bind(this._source.getWorldMatrix());
  39814. // Draw order
  39815. engine.draw(true, 0, this._indicesCount);
  39816. this._lineShader.unbind();
  39817. engine.setDepthWrite(true);
  39818. };
  39819. return EdgesRenderer;
  39820. })();
  39821. BABYLON.EdgesRenderer = EdgesRenderer;
  39822. })(BABYLON || (BABYLON = {}));
  39823. var BABYLON;
  39824. (function (BABYLON) {
  39825. (function (TonemappingOperator) {
  39826. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  39827. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  39828. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  39829. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  39830. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  39831. var TonemappingOperator = BABYLON.TonemappingOperator;
  39832. ;
  39833. var TonemapPostProcess = (function (_super) {
  39834. __extends(TonemapPostProcess, _super);
  39835. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  39836. var _this = this;
  39837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39838. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39839. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  39840. this._operator = _operator;
  39841. this.exposureAdjustment = exposureAdjustment;
  39842. var defines = "#define ";
  39843. if (this._operator === TonemappingOperator.Hable)
  39844. defines += "HABLE_TONEMAPPING";
  39845. else if (this._operator === TonemappingOperator.Reinhard)
  39846. defines += "REINHARD_TONEMAPPING";
  39847. else if (this._operator === TonemappingOperator.HejiDawson)
  39848. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  39849. else if (this._operator === TonemappingOperator.Photographic)
  39850. defines += "PHOTOGRAPHIC_TONEMAPPING";
  39851. //sadly a second call to create the effect.
  39852. this.updateEffect(defines);
  39853. this.onApply = function (effect) {
  39854. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  39855. };
  39856. }
  39857. return TonemapPostProcess;
  39858. })(BABYLON.PostProcess);
  39859. BABYLON.TonemapPostProcess = TonemapPostProcess;
  39860. })(BABYLON || (BABYLON = {}));
  39861. var BABYLON;
  39862. (function (BABYLON) {
  39863. var ReflectionProbe = (function () {
  39864. function ReflectionProbe(name, size, scene, generateMipMaps) {
  39865. var _this = this;
  39866. if (generateMipMaps === void 0) { generateMipMaps = true; }
  39867. this.name = name;
  39868. this._viewMatrix = BABYLON.Matrix.Identity();
  39869. this._target = BABYLON.Vector3.Zero();
  39870. this._add = BABYLON.Vector3.Zero();
  39871. this.position = BABYLON.Vector3.Zero();
  39872. this._scene = scene;
  39873. this._scene.reflectionProbes.push(this);
  39874. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  39875. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  39876. switch (faceIndex) {
  39877. case 0:
  39878. _this._add.copyFromFloats(1, 0, 0);
  39879. break;
  39880. case 1:
  39881. _this._add.copyFromFloats(-1, 0, 0);
  39882. break;
  39883. case 2:
  39884. _this._add.copyFromFloats(0, -1, 0);
  39885. break;
  39886. case 3:
  39887. _this._add.copyFromFloats(0, 1, 0);
  39888. break;
  39889. case 4:
  39890. _this._add.copyFromFloats(0, 0, 1);
  39891. break;
  39892. case 5:
  39893. _this._add.copyFromFloats(0, 0, -1);
  39894. break;
  39895. }
  39896. if (_this._attachedMesh) {
  39897. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  39898. }
  39899. _this.position.addToRef(_this._add, _this._target);
  39900. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  39901. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  39902. };
  39903. this._renderTargetTexture.onAfterUnbind = function () {
  39904. scene.updateTransformMatrix(true);
  39905. };
  39906. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  39907. }
  39908. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  39909. get: function () {
  39910. return this._renderTargetTexture.refreshRate;
  39911. },
  39912. set: function (value) {
  39913. this._renderTargetTexture.refreshRate = value;
  39914. },
  39915. enumerable: true,
  39916. configurable: true
  39917. });
  39918. ReflectionProbe.prototype.getScene = function () {
  39919. return this._scene;
  39920. };
  39921. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  39922. get: function () {
  39923. return this._renderTargetTexture;
  39924. },
  39925. enumerable: true,
  39926. configurable: true
  39927. });
  39928. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  39929. get: function () {
  39930. return this._renderTargetTexture.renderList;
  39931. },
  39932. enumerable: true,
  39933. configurable: true
  39934. });
  39935. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  39936. this._attachedMesh = mesh;
  39937. };
  39938. ReflectionProbe.prototype.dispose = function () {
  39939. var index = this._scene.reflectionProbes.indexOf(this);
  39940. if (index !== -1) {
  39941. // Remove from the scene if found
  39942. this._scene.reflectionProbes.splice(index, 1);
  39943. }
  39944. if (this._renderTargetTexture) {
  39945. this._renderTargetTexture.dispose();
  39946. this._renderTargetTexture = null;
  39947. }
  39948. };
  39949. return ReflectionProbe;
  39950. })();
  39951. BABYLON.ReflectionProbe = ReflectionProbe;
  39952. })(BABYLON || (BABYLON = {}));
  39953. var BABYLON;
  39954. (function (BABYLON) {
  39955. var SolidParticle = (function () {
  39956. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  39957. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  39958. this.position = BABYLON.Vector3.Zero(); // position
  39959. this.rotation = BABYLON.Vector3.Zero(); // rotation
  39960. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  39961. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  39962. this.velocity = BABYLON.Vector3.Zero(); // velocity
  39963. this.alive = true; // alive
  39964. this.idx = particleIndex;
  39965. this._pos = positionIndex;
  39966. this._model = model;
  39967. this.shapeId = shapeId;
  39968. this.idxInShape = idxInShape;
  39969. }
  39970. return SolidParticle;
  39971. })();
  39972. BABYLON.SolidParticle = SolidParticle;
  39973. var ModelShape = (function () {
  39974. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  39975. this.shapeID = id;
  39976. this._shape = shape;
  39977. this._shapeUV = shapeUV;
  39978. this._positionFunction = posFunction;
  39979. this._vertexFunction = vtxFunction;
  39980. }
  39981. return ModelShape;
  39982. })();
  39983. BABYLON.ModelShape = ModelShape;
  39984. })(BABYLON || (BABYLON = {}));
  39985. var BABYLON;
  39986. (function (BABYLON) {
  39987. /**
  39988. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  39989. */
  39990. var SolidParticleSystem = (function () {
  39991. /**
  39992. * Creates a SPS (Solid Particle System) object.
  39993. * @param name the SPS name, this will be the underlying mesh name
  39994. * @param scene the scene in which the SPS is added
  39995. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  39996. */
  39997. function SolidParticleSystem(name, scene, options) {
  39998. // public members
  39999. /**
  40000. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  40001. * Example : var p = SPS.particles[i];
  40002. */
  40003. this.particles = new Array();
  40004. /**
  40005. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  40006. */
  40007. this.nbParticles = 0;
  40008. /**
  40009. * If the particles must ever face the camera (default false). Useful for planar particles.
  40010. */
  40011. this.billboard = false;
  40012. /**
  40013. * This a counter ofr your own usage. It's not set by any SPS functions.
  40014. */
  40015. this.counter = 0;
  40016. /**
  40017. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  40018. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  40019. */
  40020. this.vars = {};
  40021. this._positions = new Array();
  40022. this._indices = new Array();
  40023. this._normals = new Array();
  40024. this._colors = new Array();
  40025. this._uvs = new Array();
  40026. this._index = 0; // indices index
  40027. this._updatable = true;
  40028. this._pickable = false;
  40029. this._isVisibilityBoxLocked = false;
  40030. this._alwaysVisible = false;
  40031. this._shapeCounter = 0;
  40032. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  40033. this._color = new BABYLON.Color4(0, 0, 0, 0);
  40034. this._computeParticleColor = true;
  40035. this._computeParticleTexture = true;
  40036. this._computeParticleRotation = true;
  40037. this._computeParticleVertex = false;
  40038. this._computeBoundingBox = false;
  40039. this._cam_axisZ = BABYLON.Vector3.Zero();
  40040. this._cam_axisY = BABYLON.Vector3.Zero();
  40041. this._cam_axisX = BABYLON.Vector3.Zero();
  40042. this._axisX = BABYLON.Axis.X;
  40043. this._axisY = BABYLON.Axis.Y;
  40044. this._axisZ = BABYLON.Axis.Z;
  40045. this._fakeCamPos = BABYLON.Vector3.Zero();
  40046. this._rotMatrix = new BABYLON.Matrix();
  40047. this._invertMatrix = new BABYLON.Matrix();
  40048. this._rotated = BABYLON.Vector3.Zero();
  40049. this._quaternion = new BABYLON.Quaternion();
  40050. this._vertex = BABYLON.Vector3.Zero();
  40051. this._normal = BABYLON.Vector3.Zero();
  40052. this._yaw = 0.0;
  40053. this._pitch = 0.0;
  40054. this._roll = 0.0;
  40055. this._halfroll = 0.0;
  40056. this._halfpitch = 0.0;
  40057. this._halfyaw = 0.0;
  40058. this._sinRoll = 0.0;
  40059. this._cosRoll = 0.0;
  40060. this._sinPitch = 0.0;
  40061. this._cosPitch = 0.0;
  40062. this._sinYaw = 0.0;
  40063. this._cosYaw = 0.0;
  40064. this._w = 0.0;
  40065. this._minimum = BABYLON.Tmp.Vector3[0];
  40066. this._maximum = BABYLON.Tmp.Vector3[1];
  40067. this.name = name;
  40068. this._scene = scene;
  40069. this._camera = scene.activeCamera;
  40070. this._pickable = options ? options.isPickable : false;
  40071. if (options && options.updatable) {
  40072. this._updatable = options.updatable;
  40073. }
  40074. else {
  40075. this._updatable = true;
  40076. }
  40077. if (this._pickable) {
  40078. this.pickedParticles = [];
  40079. }
  40080. }
  40081. /**
  40082. * Builds the SPS underlying mesh. Returns a standard Mesh.
  40083. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  40084. */
  40085. SolidParticleSystem.prototype.buildMesh = function () {
  40086. if (this.nbParticles === 0) {
  40087. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  40088. this.addShape(triangle, 1);
  40089. triangle.dispose();
  40090. }
  40091. this._positions32 = new Float32Array(this._positions);
  40092. this._uvs32 = new Float32Array(this._uvs);
  40093. this._colors32 = new Float32Array(this._colors);
  40094. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  40095. this._normals32 = new Float32Array(this._normals);
  40096. this._fixedNormal32 = new Float32Array(this._normals);
  40097. var vertexData = new BABYLON.VertexData();
  40098. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40099. vertexData.indices = this._indices;
  40100. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40101. if (this._uvs32) {
  40102. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  40103. ;
  40104. }
  40105. if (this._colors32) {
  40106. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  40107. }
  40108. var mesh = new BABYLON.Mesh(this.name, this._scene);
  40109. vertexData.applyToMesh(mesh, this._updatable);
  40110. this.mesh = mesh;
  40111. this.mesh.isPickable = this._pickable;
  40112. // free memory
  40113. this._positions = null;
  40114. this._normals = null;
  40115. this._uvs = null;
  40116. this._colors = null;
  40117. if (!this._updatable) {
  40118. this.particles.length = 0;
  40119. }
  40120. return mesh;
  40121. };
  40122. /**
  40123. * Digests the mesh and generates as many solid particles in the system as wanted.
  40124. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  40125. * Thus the particles generated from digest() have their property "positiion" yet set.
  40126. * @param mesh the mesh to be digested
  40127. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  40128. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  40129. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  40130. */
  40131. SolidParticleSystem.prototype.digest = function (mesh, options) {
  40132. var size = (options && options.facetNb) || 1;
  40133. var number = (options && options.number);
  40134. var delta = (options && options.delta) || 0;
  40135. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40136. var meshInd = mesh.getIndices();
  40137. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40138. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40139. var f = 0; // facet counter
  40140. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  40141. // compute size from number
  40142. if (number) {
  40143. number = (number > totalFacets) ? totalFacets : number;
  40144. size = Math.round(totalFacets / number);
  40145. delta = 0;
  40146. }
  40147. else {
  40148. size = (size > totalFacets) ? totalFacets : size;
  40149. }
  40150. var facetPos = []; // submesh positions
  40151. var facetInd = []; // submesh indices
  40152. var facetUV = []; // submesh UV
  40153. var facetCol = []; // submesh colors
  40154. var barycenter = BABYLON.Tmp.Vector3[0];
  40155. var rand;
  40156. var sizeO = size;
  40157. while (f < totalFacets) {
  40158. size = sizeO + Math.floor((1 + delta) * Math.random());
  40159. if (f > totalFacets - size) {
  40160. size = totalFacets - f;
  40161. }
  40162. // reset temp arrays
  40163. facetPos.length = 0;
  40164. facetInd.length = 0;
  40165. facetUV.length = 0;
  40166. facetCol.length = 0;
  40167. // iterate over "size" facets
  40168. var fi = 0;
  40169. for (var j = f * 3; j < (f + size) * 3; j++) {
  40170. facetInd.push(fi);
  40171. var i = meshInd[j];
  40172. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  40173. if (meshUV) {
  40174. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  40175. }
  40176. if (meshCol) {
  40177. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  40178. }
  40179. fi++;
  40180. }
  40181. // create a model shape for each single particle
  40182. var idx = this.nbParticles;
  40183. var shape = this._posToShape(facetPos);
  40184. var shapeUV = this._uvsToShapeUV(facetUV);
  40185. // compute the barycenter of the shape
  40186. var v;
  40187. for (v = 0; v < shape.length; v++) {
  40188. barycenter.addInPlace(shape[v]);
  40189. }
  40190. barycenter.scaleInPlace(1 / shape.length);
  40191. // shift the shape from its barycenter to the origin
  40192. for (v = 0; v < shape.length; v++) {
  40193. shape[v].subtractInPlace(barycenter);
  40194. }
  40195. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  40196. // add the particle in the SPS
  40197. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  40198. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  40199. // initialize the particle position
  40200. this.particles[this.nbParticles].position.addInPlace(barycenter);
  40201. this._index += shape.length;
  40202. idx++;
  40203. this.nbParticles++;
  40204. this._shapeCounter++;
  40205. f += size;
  40206. }
  40207. };
  40208. //reset copy
  40209. SolidParticleSystem.prototype._resetCopy = function () {
  40210. this._copy.position.x = 0;
  40211. this._copy.position.y = 0;
  40212. this._copy.position.z = 0;
  40213. this._copy.rotation.x = 0;
  40214. this._copy.rotation.y = 0;
  40215. this._copy.rotation.z = 0;
  40216. this._copy.quaternion = null;
  40217. this._copy.scale.x = 1;
  40218. this._copy.scale.y = 1;
  40219. this._copy.scale.z = 1;
  40220. this._copy.uvs.x = 0;
  40221. this._copy.uvs.y = 0;
  40222. this._copy.uvs.z = 1;
  40223. this._copy.uvs.w = 1;
  40224. this._copy.color = null;
  40225. };
  40226. // _meshBuilder : inserts the shape model in the global SPS mesh
  40227. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  40228. var i;
  40229. var u = 0;
  40230. var c = 0;
  40231. this._resetCopy();
  40232. if (options && options.positionFunction) {
  40233. options.positionFunction(this._copy, idx, idxInShape);
  40234. }
  40235. if (this._copy.quaternion) {
  40236. this._quaternion.x = this._copy.quaternion.x;
  40237. this._quaternion.y = this._copy.quaternion.y;
  40238. this._quaternion.z = this._copy.quaternion.z;
  40239. this._quaternion.w = this._copy.quaternion.w;
  40240. }
  40241. else {
  40242. this._yaw = this._copy.rotation.y;
  40243. this._pitch = this._copy.rotation.x;
  40244. this._roll = this._copy.rotation.z;
  40245. this._quaternionRotationYPR();
  40246. }
  40247. this._quaternionToRotationMatrix();
  40248. for (i = 0; i < shape.length; i++) {
  40249. this._vertex.x = shape[i].x;
  40250. this._vertex.y = shape[i].y;
  40251. this._vertex.z = shape[i].z;
  40252. if (options && options.vertexFunction) {
  40253. options.vertexFunction(this._copy, this._vertex, i);
  40254. }
  40255. this._vertex.x *= this._copy.scale.x;
  40256. this._vertex.y *= this._copy.scale.y;
  40257. this._vertex.z *= this._copy.scale.z;
  40258. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40259. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  40260. if (meshUV) {
  40261. 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);
  40262. u += 2;
  40263. }
  40264. if (this._copy.color) {
  40265. this._color = this._copy.color;
  40266. }
  40267. else if (meshCol && meshCol[c]) {
  40268. this._color.r = meshCol[c];
  40269. this._color.g = meshCol[c + 1];
  40270. this._color.b = meshCol[c + 2];
  40271. this._color.a = meshCol[c + 3];
  40272. }
  40273. else {
  40274. this._color.r = 1;
  40275. this._color.g = 1;
  40276. this._color.b = 1;
  40277. this._color.a = 1;
  40278. }
  40279. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  40280. c += 4;
  40281. }
  40282. for (i = 0; i < meshInd.length; i++) {
  40283. indices.push(p + meshInd[i]);
  40284. }
  40285. if (this._pickable) {
  40286. var nbfaces = meshInd.length / 3;
  40287. for (i = 0; i < nbfaces; i++) {
  40288. this.pickedParticles.push({ idx: idx, faceId: i });
  40289. }
  40290. }
  40291. };
  40292. // returns a shape array from positions array
  40293. SolidParticleSystem.prototype._posToShape = function (positions) {
  40294. var shape = [];
  40295. for (var i = 0; i < positions.length; i += 3) {
  40296. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  40297. }
  40298. return shape;
  40299. };
  40300. // returns a shapeUV array from a Vector4 uvs
  40301. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  40302. var shapeUV = [];
  40303. if (uvs) {
  40304. for (var i = 0; i < uvs.length; i++)
  40305. shapeUV.push(uvs[i]);
  40306. }
  40307. return shapeUV;
  40308. };
  40309. // adds a new particle object in the particles array
  40310. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  40311. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  40312. };
  40313. /**
  40314. * Adds some particles to the SPS from the model shape.
  40315. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  40316. * @param mesh any Mesh object that will be used as a model for the solid particles.
  40317. * @param nb the number of particles to be created from this model
  40318. * @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
  40319. */
  40320. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  40321. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40322. var meshInd = mesh.getIndices();
  40323. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40324. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40325. var shape = this._posToShape(meshPos);
  40326. var shapeUV = this._uvsToShapeUV(meshUV);
  40327. var posfunc = options ? options.positionFunction : null;
  40328. var vtxfunc = options ? options.vertexFunction : null;
  40329. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  40330. // particles
  40331. var idx = this.nbParticles;
  40332. for (var i = 0; i < nb; i++) {
  40333. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  40334. if (this._updatable) {
  40335. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  40336. }
  40337. this._index += shape.length;
  40338. idx++;
  40339. }
  40340. this.nbParticles += nb;
  40341. this._shapeCounter++;
  40342. return this._shapeCounter - 1;
  40343. };
  40344. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  40345. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  40346. this._resetCopy();
  40347. if (particle._model._positionFunction) {
  40348. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  40349. }
  40350. if (this._copy.quaternion) {
  40351. this._quaternion.x = this._copy.quaternion.x;
  40352. this._quaternion.y = this._copy.quaternion.y;
  40353. this._quaternion.z = this._copy.quaternion.z;
  40354. this._quaternion.w = this._copy.quaternion.w;
  40355. }
  40356. else {
  40357. this._yaw = this._copy.rotation.y;
  40358. this._pitch = this._copy.rotation.x;
  40359. this._roll = this._copy.rotation.z;
  40360. this._quaternionRotationYPR();
  40361. }
  40362. this._quaternionToRotationMatrix();
  40363. this._shape = particle._model._shape;
  40364. for (var pt = 0; pt < this._shape.length; pt++) {
  40365. this._vertex.x = this._shape[pt].x;
  40366. this._vertex.y = this._shape[pt].y;
  40367. this._vertex.z = this._shape[pt].z;
  40368. if (particle._model._vertexFunction) {
  40369. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  40370. }
  40371. this._vertex.x *= this._copy.scale.x;
  40372. this._vertex.y *= this._copy.scale.y;
  40373. this._vertex.z *= this._copy.scale.z;
  40374. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40375. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  40376. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  40377. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  40378. }
  40379. particle.position.x = 0;
  40380. particle.position.y = 0;
  40381. particle.position.z = 0;
  40382. particle.rotation.x = 0;
  40383. particle.rotation.y = 0;
  40384. particle.rotation.z = 0;
  40385. particle.quaternion = null;
  40386. particle.scale.x = 1;
  40387. particle.scale.y = 1;
  40388. particle.scale.z = 1;
  40389. };
  40390. /**
  40391. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  40392. */
  40393. SolidParticleSystem.prototype.rebuildMesh = function () {
  40394. for (var p = 0; p < this.particles.length; p++) {
  40395. this._rebuildParticle(this.particles[p]);
  40396. }
  40397. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40398. };
  40399. /**
  40400. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  40401. * This method calls updateParticle() for each particles of the SPS.
  40402. * For an animated SPS, it is usually called within the render loop.
  40403. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  40404. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  40405. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  40406. */
  40407. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  40408. if (start === void 0) { start = 0; }
  40409. if (end === void 0) { end = this.nbParticles - 1; }
  40410. if (update === void 0) { update = true; }
  40411. if (!this._updatable) {
  40412. return;
  40413. }
  40414. // custom beforeUpdate
  40415. this.beforeUpdateParticles(start, end, update);
  40416. this._cam_axisX.x = 1;
  40417. this._cam_axisX.y = 0;
  40418. this._cam_axisX.z = 0;
  40419. this._cam_axisY.x = 0;
  40420. this._cam_axisY.y = 1;
  40421. this._cam_axisY.z = 0;
  40422. this._cam_axisZ.x = 0;
  40423. this._cam_axisZ.y = 0;
  40424. this._cam_axisZ.z = 1;
  40425. // if the particles will always face the camera
  40426. if (this.billboard) {
  40427. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  40428. this._yaw = this.mesh.rotation.y;
  40429. this._pitch = this.mesh.rotation.x;
  40430. this._roll = this.mesh.rotation.z;
  40431. this._quaternionRotationYPR();
  40432. this._quaternionToRotationMatrix();
  40433. this._rotMatrix.invertToRef(this._invertMatrix);
  40434. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  40435. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  40436. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  40437. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  40438. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  40439. this._cam_axisY.normalize();
  40440. this._cam_axisX.normalize();
  40441. this._cam_axisZ.normalize();
  40442. }
  40443. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  40444. var idx = 0;
  40445. var index = 0;
  40446. var colidx = 0;
  40447. var colorIndex = 0;
  40448. var uvidx = 0;
  40449. var uvIndex = 0;
  40450. if (this._computeBoundingBox) {
  40451. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  40452. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  40453. }
  40454. // particle loop
  40455. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  40456. for (var p = start; p <= end; p++) {
  40457. this._particle = this.particles[p];
  40458. this._shape = this._particle._model._shape;
  40459. this._shapeUV = this._particle._model._shapeUV;
  40460. // call to custom user function to update the particle properties
  40461. this.updateParticle(this._particle);
  40462. // particle rotation matrix
  40463. if (this.billboard) {
  40464. this._particle.rotation.x = 0.0;
  40465. this._particle.rotation.y = 0.0;
  40466. }
  40467. if (this._computeParticleRotation) {
  40468. if (this._particle.quaternion) {
  40469. this._quaternion.x = this._particle.quaternion.x;
  40470. this._quaternion.y = this._particle.quaternion.y;
  40471. this._quaternion.z = this._particle.quaternion.z;
  40472. this._quaternion.w = this._particle.quaternion.w;
  40473. }
  40474. else {
  40475. this._yaw = this._particle.rotation.y;
  40476. this._pitch = this._particle.rotation.x;
  40477. this._roll = this._particle.rotation.z;
  40478. this._quaternionRotationYPR();
  40479. }
  40480. this._quaternionToRotationMatrix();
  40481. }
  40482. for (var pt = 0; pt < this._shape.length; pt++) {
  40483. idx = index + pt * 3;
  40484. colidx = colorIndex + pt * 4;
  40485. uvidx = uvIndex + pt * 2;
  40486. this._vertex.x = this._shape[pt].x;
  40487. this._vertex.y = this._shape[pt].y;
  40488. this._vertex.z = this._shape[pt].z;
  40489. if (this._computeParticleVertex) {
  40490. this.updateParticleVertex(this._particle, this._vertex, pt);
  40491. }
  40492. // positions
  40493. this._vertex.x *= this._particle.scale.x;
  40494. this._vertex.y *= this._particle.scale.y;
  40495. this._vertex.z *= this._particle.scale.z;
  40496. 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];
  40497. 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;
  40498. 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;
  40499. 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;
  40500. 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;
  40501. 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;
  40502. 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;
  40503. if (this._computeBoundingBox) {
  40504. if (this._positions32[idx] < this._minimum.x) {
  40505. this._minimum.x = this._positions32[idx];
  40506. }
  40507. if (this._positions32[idx] > this._maximum.x) {
  40508. this._maximum.x = this._positions32[idx];
  40509. }
  40510. if (this._positions32[idx + 1] < this._minimum.y) {
  40511. this._minimum.y = this._positions32[idx + 1];
  40512. }
  40513. if (this._positions32[idx + 1] > this._maximum.y) {
  40514. this._maximum.y = this._positions32[idx + 1];
  40515. }
  40516. if (this._positions32[idx + 2] < this._minimum.z) {
  40517. this._minimum.z = this._positions32[idx + 2];
  40518. }
  40519. if (this._positions32[idx + 2] > this._maximum.z) {
  40520. this._maximum.z = this._positions32[idx + 2];
  40521. }
  40522. }
  40523. // normals : if the particles can't be morphed then just rotate the normals
  40524. if (!this._computeParticleVertex && !this.billboard) {
  40525. this._normal.x = this._fixedNormal32[idx];
  40526. this._normal.y = this._fixedNormal32[idx + 1];
  40527. this._normal.z = this._fixedNormal32[idx + 2];
  40528. 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];
  40529. 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;
  40530. 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;
  40531. 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;
  40532. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  40533. 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;
  40534. 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;
  40535. }
  40536. if (this._computeParticleColor) {
  40537. this._colors32[colidx] = this._particle.color.r;
  40538. this._colors32[colidx + 1] = this._particle.color.g;
  40539. this._colors32[colidx + 2] = this._particle.color.b;
  40540. this._colors32[colidx + 3] = this._particle.color.a;
  40541. }
  40542. if (this._computeParticleTexture) {
  40543. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40544. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40545. }
  40546. }
  40547. index = idx + 3;
  40548. colorIndex = colidx + 4;
  40549. uvIndex = uvidx + 2;
  40550. }
  40551. if (update) {
  40552. if (this._computeParticleColor) {
  40553. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  40554. }
  40555. if (this._computeParticleTexture) {
  40556. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  40557. }
  40558. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40559. if (!this.mesh.areNormalsFrozen) {
  40560. if (this._computeParticleVertex || this.billboard) {
  40561. // recompute the normals only if the particles can be morphed, update then the normal reference array
  40562. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  40563. for (var i = 0; i < this._normals32.length; i++) {
  40564. this._fixedNormal32[i] = this._normals32[i];
  40565. }
  40566. }
  40567. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  40568. }
  40569. }
  40570. if (this._computeBoundingBox) {
  40571. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  40572. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  40573. }
  40574. this.afterUpdateParticles(start, end, update);
  40575. };
  40576. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  40577. this._halfroll = this._roll * 0.5;
  40578. this._halfpitch = this._pitch * 0.5;
  40579. this._halfyaw = this._yaw * 0.5;
  40580. this._sinRoll = Math.sin(this._halfroll);
  40581. this._cosRoll = Math.cos(this._halfroll);
  40582. this._sinPitch = Math.sin(this._halfpitch);
  40583. this._cosPitch = Math.cos(this._halfpitch);
  40584. this._sinYaw = Math.sin(this._halfyaw);
  40585. this._cosYaw = Math.cos(this._halfyaw);
  40586. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  40587. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  40588. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  40589. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  40590. };
  40591. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  40592. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  40593. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  40594. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  40595. this._rotMatrix.m[3] = 0;
  40596. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  40597. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  40598. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  40599. this._rotMatrix.m[7] = 0;
  40600. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  40601. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  40602. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  40603. this._rotMatrix.m[11] = 0;
  40604. this._rotMatrix.m[12] = 0;
  40605. this._rotMatrix.m[13] = 0;
  40606. this._rotMatrix.m[14] = 0;
  40607. this._rotMatrix.m[15] = 1.0;
  40608. };
  40609. /**
  40610. * Disposes the SPS
  40611. */
  40612. SolidParticleSystem.prototype.dispose = function () {
  40613. this.mesh.dispose();
  40614. this.vars = null;
  40615. // drop references to internal big arrays for the GC
  40616. this._positions = null;
  40617. this._indices = null;
  40618. this._normals = null;
  40619. this._uvs = null;
  40620. this._colors = null;
  40621. this._positions32 = null;
  40622. this._normals32 = null;
  40623. this._fixedNormal32 = null;
  40624. this._uvs32 = null;
  40625. this._colors32 = null;
  40626. this.pickedParticles = null;
  40627. };
  40628. /**
  40629. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  40630. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40631. */
  40632. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  40633. if (!this._isVisibilityBoxLocked) {
  40634. this.mesh.refreshBoundingInfo();
  40635. }
  40636. };
  40637. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  40638. * @param size the size (float) of the visibility box
  40639. * note : this doesn't lock the SPS mesh bounding box.
  40640. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40641. */
  40642. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  40643. var vis = size / 2;
  40644. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  40645. };
  40646. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  40647. // getter and setter
  40648. /**
  40649. * True if the SPS is set as always visible
  40650. */
  40651. get: function () {
  40652. return this._alwaysVisible;
  40653. },
  40654. /**
  40655. * Sets the SPS as always visible or not
  40656. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40657. */
  40658. set: function (val) {
  40659. this._alwaysVisible = val;
  40660. this.mesh.alwaysSelectAsActiveMesh = val;
  40661. },
  40662. enumerable: true,
  40663. configurable: true
  40664. });
  40665. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  40666. /**
  40667. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  40668. */
  40669. get: function () {
  40670. return this._isVisibilityBoxLocked;
  40671. },
  40672. /**
  40673. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  40674. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40675. */
  40676. set: function (val) {
  40677. this._isVisibilityBoxLocked = val;
  40678. this.mesh.getBoundingInfo().isLocked = val;
  40679. },
  40680. enumerable: true,
  40681. configurable: true
  40682. });
  40683. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  40684. // getters
  40685. get: function () {
  40686. return this._computeParticleRotation;
  40687. },
  40688. // Optimizer setters
  40689. /**
  40690. * Tells to setParticles() to compute the particle rotations or not.
  40691. * Default value : true. The SPS is faster when it's set to false.
  40692. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  40693. */
  40694. set: function (val) {
  40695. this._computeParticleRotation = val;
  40696. },
  40697. enumerable: true,
  40698. configurable: true
  40699. });
  40700. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  40701. get: function () {
  40702. return this._computeParticleColor;
  40703. },
  40704. /**
  40705. * Tells to setParticles() to compute the particle colors or not.
  40706. * Default value : true. The SPS is faster when it's set to false.
  40707. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  40708. */
  40709. set: function (val) {
  40710. this._computeParticleColor = val;
  40711. },
  40712. enumerable: true,
  40713. configurable: true
  40714. });
  40715. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  40716. get: function () {
  40717. return this._computeParticleTexture;
  40718. },
  40719. /**
  40720. * Tells to setParticles() to compute the particle textures or not.
  40721. * Default value : true. The SPS is faster when it's set to false.
  40722. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  40723. */
  40724. set: function (val) {
  40725. this._computeParticleTexture = val;
  40726. },
  40727. enumerable: true,
  40728. configurable: true
  40729. });
  40730. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  40731. get: function () {
  40732. return this._computeParticleVertex;
  40733. },
  40734. /**
  40735. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  40736. * Default value : false. The SPS is faster when it's set to false.
  40737. * Note : the particle custom vertex positions aren't stored values.
  40738. */
  40739. set: function (val) {
  40740. this._computeParticleVertex = val;
  40741. },
  40742. enumerable: true,
  40743. configurable: true
  40744. });
  40745. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  40746. get: function () {
  40747. return this._computeBoundingBox;
  40748. },
  40749. /**
  40750. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  40751. */
  40752. set: function (val) {
  40753. this._computeBoundingBox = val;
  40754. },
  40755. enumerable: true,
  40756. configurable: true
  40757. });
  40758. // =======================================================================
  40759. // Particle behavior logic
  40760. // these following methods may be overwritten by the user to fit his needs
  40761. /**
  40762. * This function does nothing. It may be overwritten to set all the particles first values.
  40763. * The SPS doesn't call this function, you may have to call it by your own.
  40764. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40765. */
  40766. SolidParticleSystem.prototype.initParticles = function () {
  40767. };
  40768. /**
  40769. * This function does nothing. It may be overwritten to recycle a particle.
  40770. * The SPS doesn't call this function, you may have to call it by your own.
  40771. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40772. */
  40773. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  40774. return particle;
  40775. };
  40776. /**
  40777. * Updates a particle : this function should be overwritten by the user.
  40778. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  40779. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40780. * ex : just set a particle position or velocity and recycle conditions
  40781. */
  40782. SolidParticleSystem.prototype.updateParticle = function (particle) {
  40783. return particle;
  40784. };
  40785. /**
  40786. * Updates a vertex of a particle : it can be overwritten by the user.
  40787. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  40788. * @param particle the current particle
  40789. * @param vertex the current index of the current particle
  40790. * @param pt the index of the current vertex in the particle shape
  40791. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  40792. * ex : just set a vertex particle position
  40793. */
  40794. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  40795. return vertex;
  40796. };
  40797. /**
  40798. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  40799. * This does nothing and may be overwritten by the user.
  40800. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40801. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40802. * @param update the boolean update value actually passed to setParticles()
  40803. */
  40804. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  40805. };
  40806. /**
  40807. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  40808. * This will be passed three parameters.
  40809. * This does nothing and may be overwritten by the user.
  40810. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40811. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40812. * @param update the boolean update value actually passed to setParticles()
  40813. */
  40814. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  40815. };
  40816. return SolidParticleSystem;
  40817. })();
  40818. BABYLON.SolidParticleSystem = SolidParticleSystem;
  40819. })(BABYLON || (BABYLON = {}));
  40820. var BABYLON;
  40821. (function (BABYLON) {
  40822. var Internals;
  40823. (function (Internals) {
  40824. var FileFaceOrientation = (function () {
  40825. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40826. this.name = name;
  40827. this.worldAxisForNormal = worldAxisForNormal;
  40828. this.worldAxisForFileX = worldAxisForFileX;
  40829. this.worldAxisForFileY = worldAxisForFileY;
  40830. }
  40831. return FileFaceOrientation;
  40832. })();
  40833. ;
  40834. /**
  40835. * Helper class dealing with the extraction of spherical polynomial dataArray
  40836. * from a cube map.
  40837. */
  40838. var CubeMapToSphericalPolynomialTools = (function () {
  40839. function CubeMapToSphericalPolynomialTools() {
  40840. }
  40841. /**
  40842. * Converts a cubemap to the according Spherical Polynomial data.
  40843. * This extracts the first 3 orders only as they are the only one used in the lighting.
  40844. *
  40845. * @param cubeInfo The Cube map to extract the information from.
  40846. * @return The Spherical Polynomial data.
  40847. */
  40848. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40849. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40850. var totalSolidAngle = 0.0;
  40851. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40852. var du = 2.0 / cubeInfo.size;
  40853. var dv = du;
  40854. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40855. var minUV = du * 0.5 - 1.0;
  40856. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40857. var fileFace = this.FileFaces[faceIndex];
  40858. var dataArray = cubeInfo[fileFace.name];
  40859. var v = minUV;
  40860. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40861. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40862. // Because SP is still linear, so summation is fine in that basis.
  40863. for (var y = 0; y < cubeInfo.size; y++) {
  40864. var u = minUV;
  40865. for (var x = 0; x < cubeInfo.size; x++) {
  40866. // World direction (not normalised)
  40867. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40868. worldDirection.normalize();
  40869. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40870. if (1) {
  40871. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40872. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40873. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40874. var color = new BABYLON.Color3(r, g, b);
  40875. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40876. }
  40877. else {
  40878. if (faceIndex == 0) {
  40879. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40880. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40881. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40882. }
  40883. else if (faceIndex == 1) {
  40884. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40885. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40886. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40887. }
  40888. else if (faceIndex == 2) {
  40889. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40890. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40891. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40892. }
  40893. else if (faceIndex == 3) {
  40894. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40895. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40896. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40897. }
  40898. else if (faceIndex == 4) {
  40899. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40900. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40901. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40902. }
  40903. else if (faceIndex == 5) {
  40904. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40905. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40906. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40907. }
  40908. 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]);
  40909. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40910. }
  40911. totalSolidAngle += deltaSolidAngle;
  40912. u += du;
  40913. }
  40914. v += dv;
  40915. }
  40916. }
  40917. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40918. var correction = correctSolidAngle / totalSolidAngle;
  40919. sphericalHarmonics.scale(correction);
  40920. // Additionally scale by pi -- audit needed
  40921. sphericalHarmonics.scale(1.0 / Math.PI);
  40922. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40923. };
  40924. CubeMapToSphericalPolynomialTools.FileFaces = [
  40925. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40926. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40927. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40928. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40929. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40930. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40931. ];
  40932. return CubeMapToSphericalPolynomialTools;
  40933. })();
  40934. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40935. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40936. })(BABYLON || (BABYLON = {}));
  40937. var BABYLON;
  40938. (function (BABYLON) {
  40939. var Internals;
  40940. (function (Internals) {
  40941. /**
  40942. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  40943. */
  40944. var PanoramaToCubeMapTools = (function () {
  40945. function PanoramaToCubeMapTools() {
  40946. }
  40947. /**
  40948. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  40949. *
  40950. * @param float32Array The source data.
  40951. * @param inputWidth The width of the input panorama.
  40952. * @param inputhHeight The height of the input panorama.
  40953. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  40954. * @return The cubemap data
  40955. */
  40956. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40957. if (!float32Array) {
  40958. throw "ConvertPanoramaToCubemap: input cannot be null";
  40959. }
  40960. if (float32Array.length != inputWidth * inputHeight * 3) {
  40961. throw "ConvertPanoramaToCubemap: input size is wrong";
  40962. }
  40963. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40964. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40965. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40966. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40967. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40968. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40969. return {
  40970. front: textureFront,
  40971. back: textureBack,
  40972. left: textureLeft,
  40973. right: textureRight,
  40974. up: textureUp,
  40975. down: textureDown,
  40976. size: size
  40977. };
  40978. };
  40979. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40980. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40981. var textureArray = new Float32Array(buffer);
  40982. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40983. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40984. var dy = 1 / texSize;
  40985. var fy = 0;
  40986. for (var y = 0; y < texSize; y++) {
  40987. var xv1 = faceData[0];
  40988. var xv2 = faceData[2];
  40989. for (var x = 0; x < texSize; x++) {
  40990. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40991. v.normalize();
  40992. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40993. // 3 channels per pixels
  40994. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40995. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40996. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40997. xv1 = xv1.add(rotDX1);
  40998. xv2 = xv2.add(rotDX2);
  40999. }
  41000. fy += dy;
  41001. }
  41002. return textureArray;
  41003. };
  41004. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  41005. var theta = Math.atan2(vDir.z, vDir.x);
  41006. var phi = Math.acos(vDir.y);
  41007. while (theta < -Math.PI)
  41008. theta += 2 * Math.PI;
  41009. while (theta > Math.PI)
  41010. theta -= 2 * Math.PI;
  41011. var dx = theta / Math.PI;
  41012. var dy = phi / Math.PI;
  41013. // recenter.
  41014. dx = dx * 0.5 + 0.5;
  41015. var px = Math.round(dx * inputWidth);
  41016. if (px < 0)
  41017. px = 0;
  41018. else if (px >= inputWidth)
  41019. px = inputWidth - 1;
  41020. var py = Math.round(dy * inputHeight);
  41021. if (py < 0)
  41022. py = 0;
  41023. else if (py >= inputHeight)
  41024. py = inputHeight - 1;
  41025. var inputY = (inputHeight - py - 1);
  41026. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  41027. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  41028. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  41029. return {
  41030. r: r,
  41031. g: g,
  41032. b: b
  41033. };
  41034. };
  41035. PanoramaToCubeMapTools.FACE_FRONT = [
  41036. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  41037. new BABYLON.Vector3(1.0, -1.0, -1.0),
  41038. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  41039. new BABYLON.Vector3(1.0, 1.0, -1.0)
  41040. ];
  41041. PanoramaToCubeMapTools.FACE_BACK = [
  41042. new BABYLON.Vector3(1.0, -1.0, 1.0),
  41043. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  41044. new BABYLON.Vector3(1.0, 1.0, 1.0),
  41045. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  41046. ];
  41047. PanoramaToCubeMapTools.FACE_RIGHT = [
  41048. new BABYLON.Vector3(1.0, -1.0, -1.0),
  41049. new BABYLON.Vector3(1.0, -1.0, 1.0),
  41050. new BABYLON.Vector3(1.0, 1.0, -1.0),
  41051. new BABYLON.Vector3(1.0, 1.0, 1.0)
  41052. ];
  41053. PanoramaToCubeMapTools.FACE_LEFT = [
  41054. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  41055. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  41056. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  41057. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  41058. ];
  41059. PanoramaToCubeMapTools.FACE_DOWN = [
  41060. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  41061. new BABYLON.Vector3(1.0, 1.0, -1.0),
  41062. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  41063. new BABYLON.Vector3(1.0, 1.0, 1.0)
  41064. ];
  41065. PanoramaToCubeMapTools.FACE_UP = [
  41066. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  41067. new BABYLON.Vector3(1.0, -1.0, 1.0),
  41068. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  41069. new BABYLON.Vector3(1.0, -1.0, -1.0)
  41070. ];
  41071. return PanoramaToCubeMapTools;
  41072. })();
  41073. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  41074. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41075. })(BABYLON || (BABYLON = {}));
  41076. var BABYLON;
  41077. (function (BABYLON) {
  41078. var Internals;
  41079. (function (Internals) {
  41080. ;
  41081. /**
  41082. * This groups tools to convert HDR texture to native colors array.
  41083. */
  41084. var HDRTools = (function () {
  41085. function HDRTools() {
  41086. }
  41087. HDRTools.Ldexp = function (mantissa, exponent) {
  41088. if (exponent > 1023) {
  41089. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  41090. }
  41091. if (exponent < -1074) {
  41092. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  41093. }
  41094. return mantissa * Math.pow(2, exponent);
  41095. };
  41096. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  41097. if (exponent > 0) {
  41098. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  41099. float32array[index + 0] = red * exponent;
  41100. float32array[index + 1] = green * exponent;
  41101. float32array[index + 2] = blue * exponent;
  41102. }
  41103. else {
  41104. float32array[index + 0] = 0;
  41105. float32array[index + 1] = 0;
  41106. float32array[index + 2] = 0;
  41107. }
  41108. };
  41109. HDRTools.readStringLine = function (uint8array, startIndex) {
  41110. var line = "";
  41111. var character = "";
  41112. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  41113. character = String.fromCharCode(uint8array[i]);
  41114. if (character == "\n") {
  41115. break;
  41116. }
  41117. line += character;
  41118. }
  41119. return line;
  41120. };
  41121. /**
  41122. * Reads header information from an RGBE texture stored in a native array.
  41123. * More information on this format are available here:
  41124. * https://en.wikipedia.org/wiki/RGBE_image_format
  41125. *
  41126. * @param uint8array The binary file stored in native array.
  41127. * @return The header information.
  41128. */
  41129. HDRTools.RGBE_ReadHeader = function (uint8array) {
  41130. var height = 0;
  41131. var width = 0;
  41132. var line = this.readStringLine(uint8array, 0);
  41133. if (line[0] != '#' || line[1] != '?') {
  41134. throw "Bad HDR Format.";
  41135. }
  41136. var endOfHeader = false;
  41137. var findFormat = false;
  41138. var lineIndex = 0;
  41139. do {
  41140. lineIndex += (line.length + 1);
  41141. line = this.readStringLine(uint8array, lineIndex);
  41142. if (line == "FORMAT=32-bit_rle_rgbe") {
  41143. findFormat = true;
  41144. }
  41145. else if (line.length == 0) {
  41146. endOfHeader = true;
  41147. }
  41148. } while (!endOfHeader);
  41149. if (!findFormat) {
  41150. throw "HDR Bad header format, unsupported FORMAT";
  41151. }
  41152. lineIndex += (line.length + 1);
  41153. line = this.readStringLine(uint8array, lineIndex);
  41154. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  41155. var match = sizeRegexp.exec(line);
  41156. // TODO. Support +Y and -X if needed.
  41157. if (match.length < 3) {
  41158. throw "HDR Bad header format, no size";
  41159. }
  41160. width = parseInt(match[2]);
  41161. height = parseInt(match[1]);
  41162. if (width < 8 || width > 0x7fff) {
  41163. throw "HDR Bad header format, unsupported size";
  41164. }
  41165. lineIndex += (line.length + 1);
  41166. return {
  41167. height: height,
  41168. width: width,
  41169. dataPosition: lineIndex
  41170. };
  41171. };
  41172. /**
  41173. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  41174. * This RGBE texture needs to store the information as a panorama.
  41175. *
  41176. * More information on this format are available here:
  41177. * https://en.wikipedia.org/wiki/RGBE_image_format
  41178. *
  41179. * @param buffer The binary file stored in an array buffer.
  41180. * @param size The expected size of the extracted cubemap.
  41181. * @return The Cube Map information.
  41182. */
  41183. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  41184. var uint8array = new Uint8Array(buffer);
  41185. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  41186. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  41187. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  41188. return cubeMapData;
  41189. };
  41190. /**
  41191. * Returns the pixels data extracted from an RGBE texture.
  41192. * This pixels will be stored left to right up to down in the R G B order in one array.
  41193. *
  41194. * More information on this format are available here:
  41195. * https://en.wikipedia.org/wiki/RGBE_image_format
  41196. *
  41197. * @param uint8array The binary file stored in an array buffer.
  41198. * @param hdrInfo The header information of the file.
  41199. * @return The pixels data in RGB right to left up to down order.
  41200. */
  41201. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  41202. // Keep for multi format supports.
  41203. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  41204. };
  41205. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  41206. var num_scanlines = hdrInfo.height;
  41207. var scanline_width = hdrInfo.width;
  41208. var a, b, c, d, count;
  41209. var dataIndex = hdrInfo.dataPosition;
  41210. var index = 0, endIndex = 0, i = 0;
  41211. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  41212. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  41213. // 3 channels of 4 bytes per pixel in float.
  41214. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  41215. var resultArray = new Float32Array(resultBuffer);
  41216. // read in each successive scanline
  41217. while (num_scanlines > 0) {
  41218. a = uint8array[dataIndex++];
  41219. b = uint8array[dataIndex++];
  41220. c = uint8array[dataIndex++];
  41221. d = uint8array[dataIndex++];
  41222. if (a != 2 || b != 2 || (c & 0x80)) {
  41223. // this file is not run length encoded
  41224. throw "HDR Bad header format, not RLE";
  41225. }
  41226. if (((c << 8) | d) != scanline_width) {
  41227. throw "HDR Bad header format, wrong scan line width";
  41228. }
  41229. index = 0;
  41230. // read each of the four channels for the scanline into the buffer
  41231. for (i = 0; i < 4; i++) {
  41232. endIndex = (i + 1) * scanline_width;
  41233. while (index < endIndex) {
  41234. a = uint8array[dataIndex++];
  41235. b = uint8array[dataIndex++];
  41236. if (a > 128) {
  41237. // a run of the same value
  41238. count = a - 128;
  41239. if ((count == 0) || (count > endIndex - index)) {
  41240. throw "HDR Bad Format, bad scanline data (run)";
  41241. }
  41242. while (count-- > 0) {
  41243. scanLineArray[index++] = b;
  41244. }
  41245. }
  41246. else {
  41247. // a non-run
  41248. count = a;
  41249. if ((count == 0) || (count > endIndex - index)) {
  41250. throw "HDR Bad Format, bad scanline data (non-run)";
  41251. }
  41252. scanLineArray[index++] = b;
  41253. if (--count > 0) {
  41254. for (var j = 0; j < count; j++) {
  41255. scanLineArray[index++] = uint8array[dataIndex++];
  41256. }
  41257. }
  41258. }
  41259. }
  41260. }
  41261. // now convert data from buffer into floats
  41262. for (i = 0; i < scanline_width; i++) {
  41263. a = scanLineArray[i];
  41264. b = scanLineArray[i + scanline_width];
  41265. c = scanLineArray[i + 2 * scanline_width];
  41266. d = scanLineArray[i + 3 * scanline_width];
  41267. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  41268. }
  41269. num_scanlines--;
  41270. }
  41271. return resultArray;
  41272. };
  41273. return HDRTools;
  41274. })();
  41275. Internals.HDRTools = HDRTools;
  41276. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41277. })(BABYLON || (BABYLON = {}));
  41278. //_______________________________________________________________
  41279. // Extracted from CubeMapGen:
  41280. // https://code.google.com/archive/p/cubemapgen/
  41281. //
  41282. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  41283. //_______________________________________________________________
  41284. var BABYLON;
  41285. (function (BABYLON) {
  41286. var Internals;
  41287. (function (Internals) {
  41288. /**
  41289. * The bounding box information used during the conversion process.
  41290. */
  41291. var CMGBoundinBox = (function () {
  41292. function CMGBoundinBox() {
  41293. this.min = new BABYLON.Vector3(0, 0, 0);
  41294. this.max = new BABYLON.Vector3(0, 0, 0);
  41295. this.clear();
  41296. }
  41297. CMGBoundinBox.prototype.clear = function () {
  41298. this.min.x = CMGBoundinBox.MAX;
  41299. this.min.y = CMGBoundinBox.MAX;
  41300. this.min.z = CMGBoundinBox.MAX;
  41301. this.max.x = CMGBoundinBox.MIN;
  41302. this.max.y = CMGBoundinBox.MIN;
  41303. this.max.z = CMGBoundinBox.MIN;
  41304. };
  41305. CMGBoundinBox.prototype.augment = function (x, y, z) {
  41306. this.min.x = Math.min(this.min.x, x);
  41307. this.min.y = Math.min(this.min.y, y);
  41308. this.min.z = Math.min(this.min.z, z);
  41309. this.max.x = Math.max(this.max.x, x);
  41310. this.max.y = Math.max(this.max.y, y);
  41311. this.max.z = Math.max(this.max.z, z);
  41312. };
  41313. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  41314. this.min.x = Math.max(this.min.x, x);
  41315. this.min.y = Math.max(this.min.y, y);
  41316. this.min.z = Math.max(this.min.z, z);
  41317. };
  41318. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  41319. this.max.x = Math.min(this.max.x, x);
  41320. this.max.y = Math.min(this.max.y, y);
  41321. this.max.z = Math.min(this.max.z, z);
  41322. };
  41323. CMGBoundinBox.prototype.empty = function () {
  41324. if ((this.min.x > this.max.y) ||
  41325. (this.min.y > this.max.y) ||
  41326. (this.min.z > this.max.y)) {
  41327. return true;
  41328. }
  41329. else {
  41330. return false;
  41331. }
  41332. };
  41333. CMGBoundinBox.MAX = Number.MAX_VALUE;
  41334. CMGBoundinBox.MIN = Number.MIN_VALUE;
  41335. return CMGBoundinBox;
  41336. })();
  41337. /**
  41338. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  41339. * required by the glossinees of a material.
  41340. *
  41341. * This only supports the cosine drop power as well as Warp fixup generation method.
  41342. *
  41343. * This is using the process from CubeMapGen described here:
  41344. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  41345. */
  41346. var PMREMGenerator = (function () {
  41347. /**
  41348. * Constructor of the generator.
  41349. *
  41350. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  41351. * @param inputSize The size of the cubemap faces
  41352. * @param outputSize The size of the output cubemap faces
  41353. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  41354. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  41355. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  41356. * @param specularPower The max specular level of the desired cubemap
  41357. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  41358. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  41359. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  41360. */
  41361. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  41362. this.input = input;
  41363. this.inputSize = inputSize;
  41364. this.outputSize = outputSize;
  41365. this.maxNumMipLevels = maxNumMipLevels;
  41366. this.numChannels = numChannels;
  41367. this.isFloat = isFloat;
  41368. this.specularPower = specularPower;
  41369. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  41370. this.excludeBase = excludeBase;
  41371. this.fixup = fixup;
  41372. this._outputSurface = [];
  41373. this._numMipLevels = 0;
  41374. }
  41375. /**
  41376. * Launches the filter process and return the result.
  41377. *
  41378. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  41379. */
  41380. PMREMGenerator.prototype.filterCubeMap = function () {
  41381. // Init cubemap processor
  41382. this.init();
  41383. // Filters the cubemap
  41384. this.filterCubeMapMipChain();
  41385. // Returns the filtered mips.
  41386. return this._outputSurface;
  41387. };
  41388. PMREMGenerator.prototype.init = function () {
  41389. var i;
  41390. var j;
  41391. var mipLevelSize;
  41392. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  41393. if (this.maxNumMipLevels == 0) {
  41394. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  41395. }
  41396. //first miplevel size
  41397. mipLevelSize = this.outputSize;
  41398. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  41399. for (j = 0; j < this.maxNumMipLevels; j++) {
  41400. this._outputSurface.length++;
  41401. this._outputSurface[j] = [];
  41402. //Iterate over faces for output images
  41403. for (i = 0; i < 6; i++) {
  41404. this._outputSurface[j].length++;
  41405. // Initializes a new array for the output.
  41406. if (this.isFloat) {
  41407. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  41408. }
  41409. else {
  41410. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  41411. }
  41412. }
  41413. //next mip level is half size
  41414. mipLevelSize >>= 1;
  41415. this._numMipLevels++;
  41416. //terminate if mip chain becomes too small
  41417. if (mipLevelSize == 0) {
  41418. this.maxNumMipLevels = j;
  41419. return;
  41420. }
  41421. }
  41422. };
  41423. //--------------------------------------------------------------------------------------
  41424. //Cube map filtering and mip chain generation.
  41425. // the cube map filtereing is specified using a number of parameters:
  41426. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  41427. // indicates the region of the hemisphere to filter over for each tap.
  41428. //
  41429. // Note that the top mip level is also a filtered version of the original input images
  41430. // as well in order to create mip chains for diffuse environment illumination.
  41431. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  41432. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  41433. //
  41434. // Then the mip angle used to genreate the next level of the mip chain from the first level
  41435. // is a_InitialMipAngle
  41436. //
  41437. // The angle for the subsequent levels of the mip chain are specified by their parents
  41438. // filtering angle and a per-level scale and bias
  41439. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  41440. //
  41441. //--------------------------------------------------------------------------------------
  41442. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  41443. // First, take count of the lighting model to modify SpecularPower
  41444. // 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;
  41445. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  41446. //Cone angle start (for generating subsequent mip levels)
  41447. var currentSpecularPower = this.specularPower;
  41448. //Build filter lookup tables based on the source miplevel size
  41449. this.precomputeFilterLookupTables(this.inputSize);
  41450. // Note that we need to filter the first level before generating mipmap
  41451. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  41452. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  41453. // TODO : Write a function to copy and scale the base mipmap in output
  41454. // I am just lazy here and just put a high specular power value, and do some if.
  41455. if (this.excludeBase && (levelIndex == 0)) {
  41456. // 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).
  41457. currentSpecularPower = 100000.0;
  41458. }
  41459. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  41460. var srcCubeImage = this.input;
  41461. var dstCubeImage = this._outputSurface[levelIndex];
  41462. var dstSize = this.outputSize >> levelIndex;
  41463. // Compute required angle.
  41464. var angle = this.getBaseFilterAngle(currentSpecularPower);
  41465. // filter cube surfaces
  41466. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  41467. // fix seams
  41468. if (this.fixup) {
  41469. this.fixupCubeEdges(dstCubeImage, dstSize);
  41470. }
  41471. // Decrease the specular power to generate the mipmap chain
  41472. // TODO : Use another method for Exclude (see first comment at start of the function
  41473. if (this.excludeBase && (levelIndex == 0)) {
  41474. currentSpecularPower = this.specularPower;
  41475. }
  41476. currentSpecularPower *= this.cosinePowerDropPerMip;
  41477. }
  41478. };
  41479. //--------------------------------------------------------------------------------------
  41480. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  41481. // It allow to optimize the texel to access base on the specular power.
  41482. //--------------------------------------------------------------------------------------
  41483. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  41484. // We want to find the alpha such that:
  41485. // cos(alpha)^cosinePower = epsilon
  41486. // That's: acos(epsilon^(1/cosinePower))
  41487. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  41488. var angle = 180.0;
  41489. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  41490. angle *= 180.0 / Math.PI; // Convert to degree
  41491. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  41492. return angle;
  41493. };
  41494. //--------------------------------------------------------------------------------------
  41495. //Builds the following lookup tables prior to filtering:
  41496. // -normalizer cube map
  41497. // -tap weight lookup table
  41498. //
  41499. //--------------------------------------------------------------------------------------
  41500. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  41501. var srcTexelAngle;
  41502. var iCubeFace;
  41503. //clear pre-existing normalizer cube map
  41504. this._normCubeMap = [];
  41505. //Normalized vectors per cubeface and per-texel solid angle
  41506. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  41507. };
  41508. //--------------------------------------------------------------------------------------
  41509. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  41510. //
  41511. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  41512. //
  41513. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  41514. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  41515. // below
  41516. //--------------------------------------------------------------------------------------
  41517. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  41518. var iCubeFace;
  41519. var u;
  41520. var v;
  41521. //iterate over cube faces
  41522. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41523. //First three channels for norm cube, and last channel for solid angle
  41524. this._normCubeMap.push(new Float32Array(size * size * 4));
  41525. //fast texture walk, build normalizer cube map
  41526. var facesData = this.input[iCubeFace];
  41527. for (v = 0; v < size; v++) {
  41528. for (u = 0; u < size; u++) {
  41529. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  41530. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  41531. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  41532. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  41533. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  41534. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  41535. }
  41536. }
  41537. }
  41538. };
  41539. //--------------------------------------------------------------------------------------
  41540. // Convert cubemap face texel coordinates and face idx to 3D vector
  41541. // note the U and V coords are integer coords and range from 0 to size-1
  41542. // this routine can be used to generate a normalizer cube map
  41543. //--------------------------------------------------------------------------------------
  41544. // SL BEGIN
  41545. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  41546. var nvcU;
  41547. var nvcV;
  41548. var tempVec;
  41549. // Change from original AMD code
  41550. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  41551. // + 0.5f is for texel center addressing
  41552. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  41553. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  41554. // warp fixup
  41555. if (fixup && size > 1) {
  41556. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  41557. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  41558. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  41559. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  41560. }
  41561. // Get current vector
  41562. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  41563. // U contribution
  41564. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  41565. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  41566. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  41567. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  41568. // V contribution and Sum
  41569. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  41570. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  41571. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  41572. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  41573. //add face axis
  41574. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  41575. PMREMGenerator._vectorTemp.x += faceAxis[0];
  41576. PMREMGenerator._vectorTemp.y += faceAxis[1];
  41577. PMREMGenerator._vectorTemp.z += faceAxis[2];
  41578. //normalize vector
  41579. PMREMGenerator._vectorTemp.normalize();
  41580. return PMREMGenerator._vectorTemp;
  41581. };
  41582. //--------------------------------------------------------------------------------------
  41583. // Convert 3D vector to cubemap face texel coordinates and face idx
  41584. // note the U and V coords are integer coords and range from 0 to size-1
  41585. // this routine can be used to generate a normalizer cube map
  41586. //
  41587. // returns face IDX and texel coords
  41588. //--------------------------------------------------------------------------------------
  41589. // SL BEGIN
  41590. /*
  41591. Mapping Texture Coordinates to Cube Map Faces
  41592. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  41593. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  41594. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  41595. map arrangement in Pixar's RenderMan package.
  41596. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  41597. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  41598. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  41599. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  41600. the major axis direction). The target column in the table below explains how the major axis direction
  41601. maps to the 2D image of a particular cube map target.
  41602. major axis
  41603. direction target sc tc ma
  41604. ---------- --------------------------------- --- --- ---
  41605. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  41606. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  41607. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  41608. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  41609. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  41610. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  41611. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  41612. an updated (s,t) is calculated as follows
  41613. s = ( sc/|ma| + 1 ) / 2
  41614. t = ( tc/|ma| + 1 ) / 2
  41615. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  41616. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  41617. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  41618. */
  41619. // Note this method return U and V in range from 0 to size-1
  41620. // SL END
  41621. // Store the information in vector3 for convenience (faceindex, u, v)
  41622. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  41623. var maxCoord;
  41624. var faceIdx;
  41625. //absolute value 3
  41626. var absX = Math.abs(x);
  41627. var absY = Math.abs(y);
  41628. var absZ = Math.abs(z);
  41629. if (absX >= absY && absX >= absZ) {
  41630. maxCoord = absX;
  41631. if (x >= 0) {
  41632. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  41633. }
  41634. else {
  41635. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  41636. }
  41637. }
  41638. else if (absY >= absX && absY >= absZ) {
  41639. maxCoord = absY;
  41640. if (y >= 0) {
  41641. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  41642. }
  41643. else {
  41644. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  41645. }
  41646. }
  41647. else {
  41648. maxCoord = absZ;
  41649. if (z >= 0) {
  41650. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  41651. }
  41652. else {
  41653. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  41654. }
  41655. }
  41656. //divide through by max coord so face vector lies on cube face
  41657. var scale = 1 / maxCoord;
  41658. x *= scale;
  41659. y *= scale;
  41660. z *= scale;
  41661. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  41662. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  41663. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  41664. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  41665. // Modify original AMD code to return value from 0 to Size - 1
  41666. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  41667. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  41668. PMREMGenerator._vectorTemp.x = faceIdx;
  41669. PMREMGenerator._vectorTemp.y = u;
  41670. PMREMGenerator._vectorTemp.z = v;
  41671. return PMREMGenerator._vectorTemp;
  41672. };
  41673. //--------------------------------------------------------------------------------------
  41674. //Original code from Ignacio CastaÒo
  41675. // This formula is from Manne ÷hrstrˆm's thesis.
  41676. // Take two coordiantes in the range [-1, 1] that define a portion of a
  41677. // cube face and return the area of the projection of that portion on the
  41678. // surface of the sphere.
  41679. //--------------------------------------------------------------------------------------
  41680. PMREMGenerator.prototype.areaElement = function (x, y) {
  41681. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  41682. };
  41683. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  41684. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  41685. // (+ 0.5f is for texel center addressing)
  41686. u = (2.0 * (u + 0.5) / size) - 1.0;
  41687. v = (2.0 * (v + 0.5) / size) - 1.0;
  41688. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  41689. var invResolution = 1.0 / size;
  41690. // U and V are the -1..1 texture coordinate on the current face.
  41691. // Get projected area for this texel
  41692. var x0 = u - invResolution;
  41693. var y0 = v - invResolution;
  41694. var x1 = u + invResolution;
  41695. var y1 = v + invResolution;
  41696. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  41697. return solidAngle;
  41698. };
  41699. //--------------------------------------------------------------------------------------
  41700. //The key to the speed of these filtering routines is to quickly define a per-face
  41701. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  41702. // Later these pixels are selectively processed based on their dot products to see if
  41703. // they reside within the filtering cone.
  41704. //
  41705. //This is done by computing the smallest per-texel angle to get a conservative estimate
  41706. // of the number of texels needed to be covered in width and height order to filter the
  41707. // region. the bounding box for the center taps face is defined first, and if the
  41708. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  41709. // defined next
  41710. //--------------------------------------------------------------------------------------
  41711. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  41712. // note that pixels within these regions may be rejected
  41713. // based on the anlge
  41714. var iCubeFace;
  41715. var u;
  41716. var v;
  41717. // bounding box per face to specify region to process
  41718. var filterExtents = [];
  41719. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41720. filterExtents.push(new CMGBoundinBox());
  41721. }
  41722. // min angle a src texel can cover (in degrees)
  41723. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  41724. // angle about center tap to define filter cone
  41725. // filter angle is 1/2 the cone angle
  41726. var filterAngle = filterConeAngle / 2.0;
  41727. //ensure filter angle is larger than a texel
  41728. if (filterAngle < srcTexelAngle) {
  41729. filterAngle = srcTexelAngle;
  41730. }
  41731. //ensure filter cone is always smaller than the hemisphere
  41732. if (filterAngle > 90.0) {
  41733. filterAngle = 90.0;
  41734. }
  41735. // the maximum number of texels in 1D the filter cone angle will cover
  41736. // used to determine bounding box size for filter extents
  41737. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  41738. // ensure conservative region always covers at least one texel
  41739. if (filterSize < 1) {
  41740. filterSize = 1;
  41741. }
  41742. // dotProdThresh threshold based on cone angle to determine whether or not taps
  41743. // reside within the cone angle
  41744. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  41745. // process required faces
  41746. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41747. //iterate over dst cube map face texel
  41748. for (v = 0; v < dstSize; v++) {
  41749. for (u = 0; u < dstSize; u++) {
  41750. //get center tap direction
  41751. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  41752. //clear old per-face filter extents
  41753. this.clearFilterExtents(filterExtents);
  41754. //define per-face filter extents
  41755. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  41756. //perform filtering of src faces using filter extents
  41757. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  41758. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  41759. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  41760. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  41761. }
  41762. }
  41763. }
  41764. };
  41765. //--------------------------------------------------------------------------------------
  41766. //Clear filter extents for the 6 cube map faces
  41767. //--------------------------------------------------------------------------------------
  41768. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  41769. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  41770. filterExtents[iCubeFaces].clear();
  41771. }
  41772. };
  41773. //--------------------------------------------------------------------------------------
  41774. //Define per-face bounding box filter extents
  41775. //
  41776. // These define conservative texel regions in each of the faces the filter can possibly
  41777. // process. When the pixels in the regions are actually processed, the dot product
  41778. // between the tap vector and the center tap vector is used to determine the weight of
  41779. // the tap and whether or not the tap is within the cone.
  41780. //
  41781. //--------------------------------------------------------------------------------------
  41782. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  41783. //neighboring face and bleed over amount, and width of BBOX for
  41784. // left, right, top, and bottom edges of this face
  41785. var bleedOverAmount = [0, 0, 0, 0];
  41786. var bleedOverBBoxMin = [0, 0, 0, 0];
  41787. var bleedOverBBoxMax = [0, 0, 0, 0];
  41788. var neighborFace;
  41789. var neighborEdge;
  41790. var oppositeFaceIdx;
  41791. //get face idx, and u, v info from center tap dir
  41792. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  41793. var faceIdx = result.x;
  41794. var u = result.y;
  41795. var v = result.z;
  41796. //define bbox size within face
  41797. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  41798. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  41799. filterExtents[faceIdx].clampMin(0, 0, 0);
  41800. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  41801. //u and v extent in face corresponding to center tap
  41802. var minU = filterExtents[faceIdx].min.x;
  41803. var minV = filterExtents[faceIdx].min.y;
  41804. var maxU = filterExtents[faceIdx].max.x;
  41805. var maxV = filterExtents[faceIdx].max.y;
  41806. //bleed over amounts for face across u=0 edge (left)
  41807. bleedOverAmount[0] = (bboxSize - u);
  41808. bleedOverBBoxMin[0] = minV;
  41809. bleedOverBBoxMax[0] = maxV;
  41810. //bleed over amounts for face across u=1 edge (right)
  41811. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  41812. bleedOverBBoxMin[1] = minV;
  41813. bleedOverBBoxMax[1] = maxV;
  41814. //bleed over to face across v=0 edge (up)
  41815. bleedOverAmount[2] = (bboxSize - v);
  41816. bleedOverBBoxMin[2] = minU;
  41817. bleedOverBBoxMax[2] = maxU;
  41818. //bleed over to face across v=1 edge (down)
  41819. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  41820. bleedOverBBoxMin[3] = minU;
  41821. bleedOverBBoxMax[3] = maxU;
  41822. //compute bleed over regions in neighboring faces
  41823. for (var i = 0; i < 4; i++) {
  41824. if (bleedOverAmount[i] > 0) {
  41825. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  41826. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  41827. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  41828. // be flipped: the cases are
  41829. // if a left edge mates with a left or bottom edge on the neighbor
  41830. // if a top edge mates with a top or right edge on the neighbor
  41831. // if a right edge mates with a right or top edge on the neighbor
  41832. // if a bottom edge mates with a bottom or left edge on the neighbor
  41833. //Seeing as the edges are enumerated as follows
  41834. // left =0
  41835. // right =1
  41836. // top =2
  41837. // bottom =3
  41838. //
  41839. // so if the edge enums are the same, or the sum of the enums == 3,
  41840. // the bbox needs to be flipped
  41841. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  41842. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  41843. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  41844. }
  41845. //The way the bounding box is extended onto the neighboring face
  41846. // depends on which edge of neighboring face abuts with this one
  41847. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  41848. case PMREMGenerator.CP_EDGE_LEFT:
  41849. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  41850. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  41851. break;
  41852. case PMREMGenerator.CP_EDGE_RIGHT:
  41853. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  41854. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  41855. break;
  41856. case PMREMGenerator.CP_EDGE_TOP:
  41857. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  41858. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  41859. break;
  41860. case PMREMGenerator.CP_EDGE_BOTTOM:
  41861. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  41862. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  41863. break;
  41864. }
  41865. //clamp filter extents in non-center tap faces to remain within surface
  41866. filterExtents[neighborFace].clampMin(0, 0, 0);
  41867. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  41868. }
  41869. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  41870. // from the center tap face, then process the opposite face entirely for now.
  41871. //Note that the cases in which this happens, what usually happens is that
  41872. // more than one edge bleeds onto the opposite face, and the bounding box
  41873. // encompasses the entire cube map face.
  41874. if (bleedOverAmount[i] > srcSize) {
  41875. //determine opposite face
  41876. switch (faceIdx) {
  41877. case PMREMGenerator.CP_FACE_X_POS:
  41878. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  41879. break;
  41880. case PMREMGenerator.CP_FACE_X_NEG:
  41881. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  41882. break;
  41883. case PMREMGenerator.CP_FACE_Y_POS:
  41884. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  41885. break;
  41886. case PMREMGenerator.CP_FACE_Y_NEG:
  41887. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  41888. break;
  41889. case PMREMGenerator.CP_FACE_Z_POS:
  41890. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  41891. break;
  41892. case PMREMGenerator.CP_FACE_Z_NEG:
  41893. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  41894. break;
  41895. default:
  41896. break;
  41897. }
  41898. //just encompass entire face for now
  41899. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  41900. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  41901. }
  41902. }
  41903. };
  41904. //--------------------------------------------------------------------------------------
  41905. //ProcessFilterExtents
  41906. // Process bounding box in each cube face
  41907. //
  41908. //--------------------------------------------------------------------------------------
  41909. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  41910. //accumulators are 64-bit floats in order to have the precision needed
  41911. // over a summation of a large number of pixels
  41912. var dstAccum = [0, 0, 0, 0];
  41913. var weightAccum = 0;
  41914. var k = 0;
  41915. var nSrcChannels = this.numChannels;
  41916. // norm cube map and srcCubeMap have same face width
  41917. var faceWidth = srcSize;
  41918. //amount to add to pointer to move to next scanline in images
  41919. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  41920. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  41921. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  41922. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  41923. // iterate over cubefaces
  41924. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  41925. //if bbox is non empty
  41926. if (!filterExtents[iFaceIdx].empty()) {
  41927. var uStart = filterExtents[iFaceIdx].min.x;
  41928. var vStart = filterExtents[iFaceIdx].min.y;
  41929. var uEnd = filterExtents[iFaceIdx].max.x;
  41930. var vEnd = filterExtents[iFaceIdx].max.y;
  41931. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  41932. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  41933. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  41934. for (var v = vStart; v <= vEnd; v++) {
  41935. var normCubeRowWalk = 0;
  41936. var srcCubeRowWalk = 0;
  41937. for (var u = uStart; u <= uEnd; u++) {
  41938. //pointer to direction in cube map associated with texel
  41939. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  41940. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  41941. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  41942. //check dot product to see if texel is within cone
  41943. var tapDotProd = texelVectX * centerTapDir.x +
  41944. texelVectY * centerTapDir.y +
  41945. texelVectZ * centerTapDir.z;
  41946. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  41947. //solid angle stored in 4th channel of normalizer/solid angle cube map
  41948. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  41949. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  41950. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  41951. // so just adding one to specularpower do the trick.
  41952. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  41953. //iterate over channels
  41954. for (k = 0; k < nSrcChannels; k++) {
  41955. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  41956. srcCubeRowWalk++;
  41957. }
  41958. weightAccum += weight; //accumulate weight
  41959. }
  41960. else {
  41961. //step across source pixel
  41962. srcCubeRowWalk += nSrcChannels;
  41963. }
  41964. normCubeRowWalk += 4; // 4 channels per norm cube map.
  41965. }
  41966. startIndexNormCubeMap += normCubePitch;
  41967. startIndexSrcCubeMap += srcCubePitch;
  41968. }
  41969. }
  41970. }
  41971. //divide through by weights if weight is non zero
  41972. if (weightAccum != 0.0) {
  41973. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  41974. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  41975. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  41976. if (this.numChannels > 3) {
  41977. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  41978. }
  41979. }
  41980. else {
  41981. // otherwise sample nearest
  41982. // get face idx and u, v texel coordinate in face
  41983. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  41984. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  41985. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  41986. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  41987. if (this.numChannels > 3) {
  41988. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  41989. }
  41990. }
  41991. return PMREMGenerator._vectorTemp;
  41992. };
  41993. //--------------------------------------------------------------------------------------
  41994. // Fixup cube edges
  41995. //
  41996. // average texels on cube map faces across the edges
  41997. // WARP/BENT Method Only.
  41998. //--------------------------------------------------------------------------------------
  41999. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  42000. var k;
  42001. var j;
  42002. var i;
  42003. var iFace;
  42004. var iCorner = 0;
  42005. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  42006. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  42007. // note that if functionality to filter across the three texels for each corner, then
  42008. //indexed by corner and face idx. the array contains the face the start points belongs to.
  42009. var cornerPtr = [
  42010. [[], [], []],
  42011. [[], [], []],
  42012. [[], [], []],
  42013. [[], [], []],
  42014. [[], [], []],
  42015. [[], [], []],
  42016. [[], [], []],
  42017. [[], [], []]
  42018. ];
  42019. //if there is no fixup, or fixup width = 0, do nothing
  42020. if (cubeMapSize < 1) {
  42021. return;
  42022. }
  42023. //special case 1x1 cubemap, average face colors
  42024. if (cubeMapSize == 1) {
  42025. //iterate over channels
  42026. for (k = 0; k < this.numChannels; k++) {
  42027. var accum = 0.0;
  42028. //iterate over faces to accumulate face colors
  42029. for (iFace = 0; iFace < 6; iFace++) {
  42030. accum += cubeMap[iFace][k];
  42031. }
  42032. //compute average over 6 face colors
  42033. accum /= 6.0;
  42034. //iterate over faces to distribute face colors
  42035. for (iFace = 0; iFace < 6; iFace++) {
  42036. cubeMap[iFace][k] = accum;
  42037. }
  42038. }
  42039. return;
  42040. }
  42041. //iterate over faces to collect list of corner texel pointers
  42042. for (iFace = 0; iFace < 6; iFace++) {
  42043. //the 4 corner pointers for this face
  42044. faceCornerStartIndicies[0] = [iFace, 0];
  42045. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  42046. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  42047. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  42048. //iterate over face corners to collect cube corner pointers
  42049. for (iCorner = 0; iCorner < 4; iCorner++) {
  42050. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  42051. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  42052. cornerNumPtrs[corner]++;
  42053. }
  42054. }
  42055. //iterate over corners to average across corner tap values
  42056. for (iCorner = 0; iCorner < 8; iCorner++) {
  42057. for (k = 0; k < this.numChannels; k++) {
  42058. var cornerTapAccum = 0.0;
  42059. //iterate over corner texels and average results
  42060. for (i = 0; i < 3; i++) {
  42061. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  42062. }
  42063. //divide by 3 to compute average of corner tap values
  42064. cornerTapAccum *= (1.0 / 3.0);
  42065. //iterate over corner texels and average results
  42066. for (i = 0; i < 3; i++) {
  42067. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  42068. }
  42069. }
  42070. }
  42071. //iterate over the twelve edges of the cube to average across edges
  42072. for (i = 0; i < 12; i++) {
  42073. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  42074. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  42075. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  42076. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  42077. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  42078. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  42079. var edgeWalk = 0;
  42080. var neighborEdgeWalk = 0;
  42081. //Determine walking pointers based on edge type
  42082. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  42083. switch (edge) {
  42084. case PMREMGenerator.CP_EDGE_LEFT:
  42085. // no change to faceEdgeStartPtr
  42086. edgeWalk = this.numChannels * cubeMapSize;
  42087. break;
  42088. case PMREMGenerator.CP_EDGE_RIGHT:
  42089. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  42090. edgeWalk = this.numChannels * cubeMapSize;
  42091. break;
  42092. case PMREMGenerator.CP_EDGE_TOP:
  42093. // no change to faceEdgeStartPtr
  42094. edgeWalk = this.numChannels;
  42095. break;
  42096. case PMREMGenerator.CP_EDGE_BOTTOM:
  42097. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  42098. edgeWalk = this.numChannels;
  42099. break;
  42100. }
  42101. //For certain types of edge abutments, the neighbor edge walk needs to
  42102. // be flipped: the cases are
  42103. // if a left edge mates with a left or bottom edge on the neighbor
  42104. // if a top edge mates with a top or right edge on the neighbor
  42105. // if a right edge mates with a right or top edge on the neighbor
  42106. // if a bottom edge mates with a bottom or left edge on the neighbor
  42107. //Seeing as the edges are enumerated as follows
  42108. // left =0
  42109. // right =1
  42110. // top =2
  42111. // bottom =3
  42112. //
  42113. //If the edge enums are the same, or the sum of the enums == 3,
  42114. // the neighbor edge walk needs to be flipped
  42115. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  42116. switch (neighborEdge) {
  42117. case PMREMGenerator.CP_EDGE_LEFT:
  42118. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  42119. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  42120. break;
  42121. case PMREMGenerator.CP_EDGE_RIGHT:
  42122. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  42123. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  42124. break;
  42125. case PMREMGenerator.CP_EDGE_TOP:
  42126. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  42127. neighborEdgeWalk = -this.numChannels;
  42128. break;
  42129. case PMREMGenerator.CP_EDGE_BOTTOM:
  42130. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  42131. neighborEdgeWalk = -this.numChannels;
  42132. break;
  42133. }
  42134. }
  42135. else {
  42136. //swapped direction neighbor edge walk
  42137. switch (neighborEdge) {
  42138. case PMREMGenerator.CP_EDGE_LEFT:
  42139. //no change to neighborEdgeStartPtr for this case since it points
  42140. // to the upper left corner already
  42141. neighborEdgeWalk = this.numChannels * cubeMapSize;
  42142. break;
  42143. case PMREMGenerator.CP_EDGE_RIGHT:
  42144. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  42145. neighborEdgeWalk = this.numChannels * cubeMapSize;
  42146. break;
  42147. case PMREMGenerator.CP_EDGE_TOP:
  42148. //no change to neighborEdgeStartPtr for this case since it points
  42149. // to the upper left corner already
  42150. neighborEdgeWalk = this.numChannels;
  42151. break;
  42152. case PMREMGenerator.CP_EDGE_BOTTOM:
  42153. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  42154. neighborEdgeWalk = this.numChannels;
  42155. break;
  42156. }
  42157. }
  42158. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  42159. //nearby neighborhood
  42160. //step ahead one texel on edge
  42161. edgeStartIndex += edgeWalk;
  42162. neighborEdgeStartIndex += neighborEdgeWalk;
  42163. // note that this loop does not process the corner texels, since they have already been
  42164. // averaged across faces across earlier
  42165. for (j = 1; j < (cubeMapSize - 1); j++) {
  42166. //for each set of taps along edge, average them
  42167. // and rewrite the results into the edges
  42168. for (k = 0; k < this.numChannels; k++) {
  42169. var edgeTap = cubeMap[face][edgeStartIndex + k];
  42170. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  42171. //compute average of tap intensity values
  42172. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  42173. //propagate average of taps to edge taps
  42174. cubeMap[face][edgeStartIndex + k] = avgTap;
  42175. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  42176. }
  42177. edgeStartIndex += edgeWalk;
  42178. neighborEdgeStartIndex += neighborEdgeWalk;
  42179. }
  42180. }
  42181. };
  42182. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  42183. PMREMGenerator.CP_UDIR = 0;
  42184. PMREMGenerator.CP_VDIR = 1;
  42185. PMREMGenerator.CP_FACEAXIS = 2;
  42186. //used to index cube faces
  42187. PMREMGenerator.CP_FACE_X_POS = 0;
  42188. PMREMGenerator.CP_FACE_X_NEG = 1;
  42189. PMREMGenerator.CP_FACE_Y_POS = 2;
  42190. PMREMGenerator.CP_FACE_Y_NEG = 3;
  42191. PMREMGenerator.CP_FACE_Z_POS = 4;
  42192. PMREMGenerator.CP_FACE_Z_NEG = 5;
  42193. //used to index image edges
  42194. // NOTE.. the actual number corresponding to the edge is important
  42195. // do not change these, or the code will break
  42196. //
  42197. // CP_EDGE_LEFT is u = 0
  42198. // CP_EDGE_RIGHT is u = width-1
  42199. // CP_EDGE_TOP is v = 0
  42200. // CP_EDGE_BOTTOM is v = height-1
  42201. PMREMGenerator.CP_EDGE_LEFT = 0;
  42202. PMREMGenerator.CP_EDGE_RIGHT = 1;
  42203. PMREMGenerator.CP_EDGE_TOP = 2;
  42204. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  42205. //corners of CUBE map (P or N specifys if it corresponds to the
  42206. // positive or negative direction each of X, Y, and Z
  42207. PMREMGenerator.CP_CORNER_NNN = 0;
  42208. PMREMGenerator.CP_CORNER_NNP = 1;
  42209. PMREMGenerator.CP_CORNER_NPN = 2;
  42210. PMREMGenerator.CP_CORNER_NPP = 3;
  42211. PMREMGenerator.CP_CORNER_PNN = 4;
  42212. PMREMGenerator.CP_CORNER_PNP = 5;
  42213. PMREMGenerator.CP_CORNER_PPN = 6;
  42214. PMREMGenerator.CP_CORNER_PPP = 7;
  42215. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  42216. //3x2 matrices that map cube map indexing vectors in 3d
  42217. // (after face selection and divide through by the
  42218. // _ABSOLUTE VALUE_ of the max coord)
  42219. // into NVC space
  42220. //Note this currently assumes the D3D cube face ordering and orientation
  42221. PMREMGenerator._sgFace2DMapping = [
  42222. //XPOS face
  42223. [[0, 0, -1],
  42224. [0, -1, 0],
  42225. [1, 0, 0]],
  42226. //XNEG face
  42227. [[0, 0, 1],
  42228. [0, -1, 0],
  42229. [-1, 0, 0]],
  42230. //YPOS face
  42231. [[1, 0, 0],
  42232. [0, 0, 1],
  42233. [0, 1, 0]],
  42234. //YNEG face
  42235. [[1, 0, 0],
  42236. [0, 0, -1],
  42237. [0, -1, 0]],
  42238. //ZPOS face
  42239. [[1, 0, 0],
  42240. [0, -1, 0],
  42241. [0, 0, 1]],
  42242. //ZNEG face
  42243. [[-1, 0, 0],
  42244. [0, -1, 0],
  42245. [0, 0, -1]],
  42246. ];
  42247. //------------------------------------------------------------------------------
  42248. // D3D cube map face specification
  42249. // mapping from 3D x,y,z cube map lookup coordinates
  42250. // to 2D within face u,v coordinates
  42251. //
  42252. // --------------------> U direction
  42253. // | (within-face texture space)
  42254. // | _____
  42255. // | | |
  42256. // | | +Y |
  42257. // | _____|_____|_____ _____
  42258. // | | | | | |
  42259. // | | -X | +Z | +X | -Z |
  42260. // | |_____|_____|_____|_____|
  42261. // | | |
  42262. // | | -Y |
  42263. // | |_____|
  42264. // |
  42265. // v V direction
  42266. // (within-face texture space)
  42267. //------------------------------------------------------------------------------
  42268. //Information about neighbors and how texture coorrdinates change across faces
  42269. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  42270. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  42271. //Note this currently assumes the D3D cube face ordering and orientation
  42272. PMREMGenerator._sgCubeNgh = [
  42273. //XPOS face
  42274. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42275. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42276. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42277. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  42278. //XNEG face
  42279. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42280. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  42281. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  42282. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  42283. //YPOS face
  42284. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  42285. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  42286. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  42287. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  42288. //YNEG face
  42289. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  42290. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42291. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42292. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  42293. //ZPOS face
  42294. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42295. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  42296. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42297. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  42298. //ZNEG face
  42299. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42300. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42301. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  42302. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  42303. ];
  42304. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  42305. // this table is used to average over the edges.
  42306. PMREMGenerator._sgCubeEdgeList = [
  42307. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  42308. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42309. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  42310. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42311. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42312. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42313. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  42314. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  42315. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  42316. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42317. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  42318. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  42319. ];
  42320. //Information about which of the 8 cube corners are correspond to the
  42321. // the 4 corners in each cube face
  42322. // the order is upper left, upper right, lower left, lower right
  42323. PMREMGenerator._sgCubeCornerList = [
  42324. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  42325. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  42326. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  42327. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  42328. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  42329. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  42330. ];
  42331. return PMREMGenerator;
  42332. })();
  42333. Internals.PMREMGenerator = PMREMGenerator;
  42334. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42335. })(BABYLON || (BABYLON = {}));
  42336. var BABYLON;
  42337. (function (BABYLON) {
  42338. /**
  42339. * This represents a texture coming from an HDR input.
  42340. *
  42341. * The only supported format is currently panorama picture stored in RGBE format.
  42342. * Example of such files can be found on HDRLib: http://hdrlib.com/
  42343. */
  42344. var HDRCubeTexture = (function (_super) {
  42345. __extends(HDRCubeTexture, _super);
  42346. /**
  42347. * Instantiates an HDRTexture from the following parameters.
  42348. *
  42349. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  42350. * @param scene The scene the texture will be used in
  42351. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  42352. * @param noMipmap Forces to not generate the mipmap if true
  42353. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  42354. * @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)
  42355. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  42356. */
  42357. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  42358. if (noMipmap === void 0) { noMipmap = false; }
  42359. if (generateHarmonics === void 0) { generateHarmonics = true; }
  42360. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  42361. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  42362. _super.call(this, scene);
  42363. this._useInGammaSpace = false;
  42364. this._generateHarmonics = true;
  42365. /**
  42366. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  42367. */
  42368. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42369. /**
  42370. * The spherical polynomial data extracted from the texture.
  42371. */
  42372. this.sphericalPolynomial = null;
  42373. /**
  42374. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  42375. * This is usefull at run time to apply the good shader.
  42376. */
  42377. this.isPMREM = false;
  42378. this.name = url;
  42379. this.url = url;
  42380. this._noMipmap = noMipmap;
  42381. this.hasAlpha = false;
  42382. this._size = size;
  42383. this._useInGammaSpace = useInGammaSpace;
  42384. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  42385. this.isPMREM = this._usePMREMGenerator;
  42386. if (!url) {
  42387. return;
  42388. }
  42389. this._texture = this._getFromCache(url, noMipmap);
  42390. if (!this._texture) {
  42391. if (!scene.useDelayedTextureLoading) {
  42392. this.loadTexture();
  42393. }
  42394. else {
  42395. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42396. }
  42397. }
  42398. this.isCube = true;
  42399. this._textureMatrix = BABYLON.Matrix.Identity();
  42400. }
  42401. HDRCubeTexture.prototype.loadTexture = function () {
  42402. var _this = this;
  42403. var callback = function (buffer) {
  42404. // Extract the raw linear data.
  42405. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  42406. // Generate harmonics if needed.
  42407. if (_this._generateHarmonics) {
  42408. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  42409. }
  42410. var results = [];
  42411. var byteArray = null;
  42412. // Create uintarray fallback.
  42413. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  42414. // 3 channels of 1 bytes per pixel in bytes.
  42415. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  42416. byteArray = new Uint8Array(byteBuffer);
  42417. }
  42418. // Push each faces.
  42419. for (var j = 0; j < 6; j++) {
  42420. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  42421. // If special cases.
  42422. if (_this._useInGammaSpace || byteArray) {
  42423. for (var i = 0; i < _this._size * _this._size; i++) {
  42424. // Put in gamma space if requested.
  42425. if (_this._useInGammaSpace) {
  42426. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  42427. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  42428. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  42429. }
  42430. // Convert to int texture for fallback.
  42431. if (byteArray) {
  42432. // R
  42433. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  42434. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  42435. // G
  42436. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  42437. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  42438. // B
  42439. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  42440. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  42441. }
  42442. }
  42443. }
  42444. results.push(dataFace);
  42445. }
  42446. return results;
  42447. };
  42448. var mipmapGenerator = null;
  42449. if (!this._noMipmap && this._usePMREMGenerator) {
  42450. mipmapGenerator = function (data) {
  42451. // Custom setup of the generator matching with the PBR shader values.
  42452. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  42453. return generator.filterCubeMap();
  42454. };
  42455. }
  42456. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  42457. };
  42458. HDRCubeTexture.prototype.clone = function () {
  42459. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  42460. // Base texture
  42461. newTexture.level = this.level;
  42462. newTexture.wrapU = this.wrapU;
  42463. newTexture.wrapV = this.wrapV;
  42464. newTexture.coordinatesIndex = this.coordinatesIndex;
  42465. newTexture.coordinatesMode = this.coordinatesMode;
  42466. return newTexture;
  42467. };
  42468. // Methods
  42469. HDRCubeTexture.prototype.delayLoad = function () {
  42470. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42471. return;
  42472. }
  42473. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42474. this._texture = this._getFromCache(this.url, this._noMipmap);
  42475. if (!this._texture) {
  42476. this.loadTexture();
  42477. }
  42478. };
  42479. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  42480. return this._textureMatrix;
  42481. };
  42482. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42483. var texture = null;
  42484. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  42485. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  42486. texture.name = parsedTexture.name;
  42487. texture.hasAlpha = parsedTexture.hasAlpha;
  42488. texture.level = parsedTexture.level;
  42489. texture.coordinatesMode = parsedTexture.coordinatesMode;
  42490. }
  42491. return texture;
  42492. };
  42493. HDRCubeTexture.prototype.serialize = function () {
  42494. if (!this.name) {
  42495. return null;
  42496. }
  42497. var serializationObject = {};
  42498. serializationObject.name = this.name;
  42499. serializationObject.hasAlpha = this.hasAlpha;
  42500. serializationObject.isCube = true;
  42501. serializationObject.level = this.level;
  42502. serializationObject.size = this._size;
  42503. serializationObject.coordinatesMode = this.coordinatesMode;
  42504. serializationObject.useInGammaSpace = this._useInGammaSpace;
  42505. serializationObject.generateHarmonics = this._generateHarmonics;
  42506. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  42507. return serializationObject;
  42508. };
  42509. HDRCubeTexture._facesMapping = [
  42510. "right",
  42511. "up",
  42512. "front",
  42513. "left",
  42514. "down",
  42515. "back"
  42516. ];
  42517. return HDRCubeTexture;
  42518. })(BABYLON.BaseTexture);
  42519. BABYLON.HDRCubeTexture = HDRCubeTexture;
  42520. })(BABYLON || (BABYLON = {}));
  42521. var BABYLON;
  42522. (function (BABYLON) {
  42523. var Debug;
  42524. (function (Debug) {
  42525. /**
  42526. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  42527. */
  42528. var SkeletonViewer = (function () {
  42529. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  42530. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  42531. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  42532. this.skeleton = skeleton;
  42533. this.mesh = mesh;
  42534. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  42535. this.renderingGroupId = renderingGroupId;
  42536. this.color = BABYLON.Color3.White();
  42537. this._debugLines = [];
  42538. this._isEnabled = false;
  42539. this._scene = scene;
  42540. this.update();
  42541. this._renderFunction = this.update.bind(this);
  42542. }
  42543. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  42544. get: function () {
  42545. return this._isEnabled;
  42546. },
  42547. set: function (value) {
  42548. if (this._isEnabled === value) {
  42549. return;
  42550. }
  42551. this._isEnabled = value;
  42552. if (value) {
  42553. this._scene.registerBeforeRender(this._renderFunction);
  42554. }
  42555. else {
  42556. this._scene.unregisterBeforeRender(this._renderFunction);
  42557. }
  42558. },
  42559. enumerable: true,
  42560. configurable: true
  42561. });
  42562. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  42563. if (x === void 0) { x = 0; }
  42564. if (y === void 0) { y = 0; }
  42565. if (z === void 0) { z = 0; }
  42566. var tmat = BABYLON.Tmp.Matrix[0];
  42567. var parentBone = bone.getParent();
  42568. tmat.copyFrom(bone.getLocalMatrix());
  42569. if (x !== 0 || y !== 0 || z !== 0) {
  42570. var tmat2 = BABYLON.Tmp.Matrix[1];
  42571. BABYLON.Matrix.IdentityToRef(tmat2);
  42572. tmat2.m[12] = x;
  42573. tmat2.m[13] = y;
  42574. tmat2.m[14] = z;
  42575. tmat2.multiplyToRef(tmat, tmat);
  42576. }
  42577. if (parentBone) {
  42578. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  42579. }
  42580. tmat.multiplyToRef(meshMat, tmat);
  42581. position.x = tmat.m[12];
  42582. position.y = tmat.m[13];
  42583. position.z = tmat.m[14];
  42584. };
  42585. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  42586. var len = bones.length;
  42587. for (var i = 0; i < len; i++) {
  42588. var bone = bones[i];
  42589. var points = this._debugLines[i];
  42590. if (!points) {
  42591. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  42592. this._debugLines[i] = points;
  42593. }
  42594. this._getBonePosition(points[0], bone, meshMat);
  42595. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  42596. }
  42597. };
  42598. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  42599. var len = bones.length;
  42600. var boneNum = 0;
  42601. for (var i = len - 1; i >= 0; i--) {
  42602. var childBone = bones[i];
  42603. var parentBone = childBone.getParent();
  42604. if (!parentBone) {
  42605. continue;
  42606. }
  42607. var points = this._debugLines[boneNum];
  42608. if (!points) {
  42609. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  42610. this._debugLines[boneNum] = points;
  42611. }
  42612. this._getBonePosition(points[0], childBone, meshMat);
  42613. this._getBonePosition(points[1], parentBone, meshMat);
  42614. boneNum++;
  42615. }
  42616. };
  42617. SkeletonViewer.prototype.update = function () {
  42618. if (this.autoUpdateBonesMatrices) {
  42619. this._updateBoneMatrix(this.skeleton.bones[0]);
  42620. }
  42621. if (this.skeleton.bones[0].length === undefined) {
  42622. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  42623. }
  42624. else {
  42625. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  42626. }
  42627. if (!this._debugMesh) {
  42628. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  42629. this._debugMesh.renderingGroupId = this.renderingGroupId;
  42630. }
  42631. else {
  42632. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  42633. }
  42634. this._debugMesh.color = this.color;
  42635. };
  42636. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  42637. if (bone.getParent()) {
  42638. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  42639. }
  42640. var children = bone.children;
  42641. var len = children.length;
  42642. for (var i = 0; i < len; i++) {
  42643. this._updateBoneMatrix(children[i]);
  42644. }
  42645. };
  42646. SkeletonViewer.prototype.dispose = function () {
  42647. if (this._debugMesh) {
  42648. this.isEnabled = false;
  42649. this._debugMesh.dispose();
  42650. this._debugMesh = null;
  42651. }
  42652. };
  42653. return SkeletonViewer;
  42654. })();
  42655. Debug.SkeletonViewer = SkeletonViewer;
  42656. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  42657. })(BABYLON || (BABYLON = {}));
  42658. 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}"};
  42659. 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"};
  42660. 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={}));";
  42661. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  42662. module.exports = BABYLON;
  42663. };